Contents

BitBucket的CI簡單測試記錄

Bitbucket Pipelines 是 Atlassian 提供的 CI/CD(持續整合/持續部署)服務,整合在 Bitbucket 版本控制平台中。只要在專案根目錄建立 bitbucket-pipelines.yml,每次 push 程式碼時就會自動觸發指定的建置、測試或部署流程。

bitbucket-pipelines.yml 的基本結構

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
image: node:18  # 使用的 Docker 映像

pipelines:
  default:          # 預設所有分支都會觸發
    - step:
        name: Build and Test
        caches:
          - node
        script:
          - npm install
          - npm test

  branches:
    main:           # 只在 main 分支觸發
      - step:
          name: Deploy to Production
          script:
            - npm run build
            - npm run deploy

使用 yaml-lint 驗證 YAML 設定檔

在 CI 管道中加入 YAML 語法驗證,可以在早期發現設定檔錯誤,避免部署到一半才出問題。

原本嘗試使用 Python 的 yamllint,但它有嚴格的格式規則(例如每行不能超過 80 字元),對現有設定改動較大。改用 Node.js 的 yaml-lint 套件,規則較寬鬆且更容易整合。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# bitbucket-pipelines.yml
image: node:18

pipelines:
  default:
    - step:
        name: Validate YAML
        script:
          - npm install -g yaml-lint
          - yamllint bitbucket-pipelines.yml

驗證通過時不會有輸出,若 YAML 格式有錯(例如縮排錯誤、語法問題),會輸出錯誤訊息,並讓 Pipeline 失敗,Bitbucket 會發 Email 通知給相關人員。

更完整的 Pipeline 範例(安裝 → 測試 → 部署)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
image: node:18

definitions:
  caches:
    npm: ~/.npm

pipelines:
  default:
    - step:
        name: Install & Lint
        caches:
          - npm
        script:
          - npm ci
          - npm install -g yaml-lint
          - yamllint bitbucket-pipelines.yml
          - npm run lint

    - step:
        name: Unit Tests
        caches:
          - npm
        script:
          - npm ci
          - npm test -- --coverage

  branches:
    main:
      - step:
          name: Build
          script:
            - npm ci
            - npm run build
          artifacts:
            - dist/**

      - step:
          name: Deploy to Production
          deployment: production
          script:
            - pipe: atlassian/aws-s3-deploy:1.1.0
              variables:
                AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID
                AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY
                S3_BUCKET: my-production-bucket
                LOCAL_PATH: dist

環境變數設定

敏感資料(API 金鑰、密碼)不應寫在 YAML 檔案中,應透過 Bitbucket 的 Repository Settings → Pipelines → Repository variables 設定,在 YAML 中用 $VARIABLE_NAME 引用。

常用功能

功能 說明
image 指定 Docker 映像,決定執行環境
caches 快取 node_modules 等目錄,加速重複執行
artifacts 步驟間傳遞檔案(如建置產物)
deployment 標記部署環境(development/staging/production)
parallel 多個步驟並行執行,縮短 Pipeline 時間

參考資料