workflow 結構、on 觸發、job·step、常用 action、secret
GitHub Actions 讓你在「特定事件發生時」自動跑工作流程——最常見的就是 CI/CD:程式碼 push 後自動測試、建置、部署。CI(持續整合)=每次變更自動檢查;CD(持續部署)=檢查通過自動上線。
| 名詞 | 意義 |
|---|---|
| Workflow | 一個自動化流程,寫在 .github/workflows/*.yml |
| Event | 觸發條件(push、pull_request、schedule…) |
| Job | 一個工作單位(在一台 runner 上跑) |
| Step | Job 裡的一步(跑指令或呼叫 action) |
| Action | 可重用的步驟套件(Marketplace 下載) |
| Runner | 執行環境(ubuntu-latest 等虛擬機) |
Workflow(檔案)
└── on(事件)
└── jobs
└── job A(runner 1)
├── step 1:uses 某 action
└── step 2:run 某指令
└── job B(runner 2,可並行)
放在 .github/workflows/ci.yml:
name: CI on: push: branches: [main] pull_request: jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 - run: npm ci - run: npm test
on: push: # push 時 pull_request: # 開/更新 PR 時 schedule: # 定時(cron) - cron: "0 3 * * *" # 每天凌晨 3 點 workflow_dispatch: # 手動按鈕 issues: # issue 事件
cron 語法為「分 時 日 月 週」五段。0 3 * * * = 每天凌晨 3 點。手動觸發(workflow_dispatch)在 Actions 分頁按「Run workflow」。
| Action | 用途 |
|---|---|
actions/checkout | 把 repo 程式碼抓到 runner(幾乎每個 workflow 第一步) |
actions/setup-node / setup-python | 安裝指定語言環境 |
actions/cache | 快取相依套件,加速 CI |
actions/upload-artifact / download-artifact | 上傳/下載建置產物(跨 job) |
actions/deploy-pages | 部署到 GitHub Pages(單元 6) |
dependabot(內建) | 自動更新相依套件並開 PR(單元 8) |
workflow 需要 API key、Token 時,不要寫死在 YAML——寫進去就等於公開給所有能看到 repo 的人。用 Secrets 加密存放:
# 設定:Settings → Secrets and variables → Actions # 名稱如:MY_API_KEY # 使用:在 workflow 中以 ${{ secrets.MY_API_KEY }} 引用 env: API_KEY: ${{ secrets.MY_API_KEY }}
echo $API_KEY」這種 debug 動作會把機密印出來,GitHub 有時會事後遮罩,但別賭。把 workflow 接上「保護分支」(單元 4),PR 的 CI 沒通過就不能合併——這是團隊品質的第一道防線:
Settings → Branches → Branch protection ├── Require status checks to pass └── 勾選你的 workflow 名稱(如「test」)
strategy: matrix: node-version: [18, 20, 22] os: [ubuntu-latest, macos-latest] # 產生 3×2 = 6 台 runner 平行跑,確保多環境相容
- uses: actions/cache@v4 with: path: ~/.npm key: ${{ runner.os }}-npm-${{ hashFiles('package-lock.json') }}
1. 新增 .github/workflows/ci.yml
- on push + pull_request
- job test:checkout + setup-node
+ npm ci + npm test
2. 開 PR 測試 CI 是否啟動
3. 故意改壞一行 → CI 紅 → 修回 → 綠
4. 到 Settings → Branches 勾 Require status checks✅ PR 上看到 CI 通過
✅ 壞 PR 無法合併(閘門生效)
✅ Actions 分頁看得到執行歷史
✅ Matrix 有多環境時全部通過
你是一個開源 CLI 工具的維護者, 需要在每次 PR 上: - 在 3 個 OS × 3 個 Node 版本 = 9 台 runner 測試 - 測試通過後上傳 build artifact - 合併到 main 時自動發佈 npm 套件
name: CI + Release on: push: { branches: [main] } pull_request: jobs: test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, macos-latest, windows-latest] node: [18, 20, 22] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: ${{ matrix.node }} } - run: npm ci - run: npm test - uses: actions/upload-artifact@v4 if: ${{ matrix.os == 'ubuntu-latest' }} with: name: dist path: dist/ release: needs: test if: ${{ github.ref == 'refs/heads/main' }} runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: { node-version: 22, registry-url: https://registry.npmjs.org } - run: npm publish --provenance env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
GitHub Actions Runner 架構:
┌─────────────────────────────────┐
│ GitHub.com │
│ └── Event Queue │
│ └── Workflow Run (待派送) │
└────────────┬────────────────────┘
│ 調度
┌────────────▼────────────────────┐
│ Runner VM(Ubuntu / macOS / Win)│
│ └── Runner Application(程式) │
│ └── 執行 Step(依序) │
│ ├── uses: action@v4 │
│ │ └── Node.js 子程序 │
│ └── run: npm test │
│ └── Shell 子程序 │
└─────────────────────────────────┘
.github/actions/ 資料夾。比 Marketplace 上的 action 更輕量、更可定制。uses: ./.github/workflows/ci.yml),避免重複 YAML——大型專案的必備技巧。| 症狀 | 可能原因 | 解決方案 |
|---|---|---|
| Workflow 完全沒觸發 | YAML 檔案位置錯 / 觸發條件不對 | 確認 .github/workflows/ 資料夾正確;on.push.branches 包含目標分支 |
Unrecognized named-value: "secrets" | Secrets 在 PR 的 fork 中不可用 | 改用 pull_request_target(有安全風險)或在 workflow 中做條件判斷 |
| Matrix 測試其中一台紅了 | 跨平台相容問題 | 查看該 job 的 log;用 if: matrix.os == 'ubuntu-latest' 限制只在特定 OS 執行某 step |
Error: Input required and not supplied: node-version | setup-node 參數格式錯 | 確認 with: 底下有正確縮排(2 空格) |
| Artifact 上傳失敗 | 路徑不存在 | 在 upload-artifact 前先 ls dist/ 確認目錄存在 |
workflow_dispatch 的 inputs 功能,建立一個手動觸發的 workflow,讓你在 Actions 頁面輸入參數(如環境名稱、版本號),workflow 根據輸入執行不同分支。pull_request 與 pull_request_target 的安全差異。為什麼 fork 的 PR 不能用 pull_request 存取 Secrets?什麼時候用 pull_request_target 是安全的?單元 7.10 是一條 workflow 的矩陣測試;這裡把 CI/CD 放大成整個平台的流水線:可重用 action、相依快取、多服務矩陣、安全掃描、部署與發佈串成一條鏈。做完它,你的 repo 就是「推上 main 就自動走完整套品管」的狀態——這是單元 7.10 之上的平台架構設計。
techco-app/ ├── .github/ │ ├── actions/ │ │ └── setup-env/ # 共用「裝環境 + 快取」action │ └── workflows/ │ ├── ci.yml # 閘門:lint + test + build │ ├── security.yml # CodeQL + 依賴掃描 │ └── release.yml # 打 tag → 建置 → 發佈 ├── services/ │ ├── api/ # Python 服務 │ ├── web/ # Node 服務 │ └── worker/ # Rust 服務 └── README.md # 內含 CI 狀態徽章
# .github/workflows/ci.yml 重點 jobs: test: runs-on: ubuntu-latest strategy: matrix: { service: [api, web, worker] } steps: - uses: actions/checkout@v4 - uses: ./.github/actions/setup-env with: { service: ${{ matrix.service }} } - run: make test-${{ matrix.service }} - uses: actions/cache@v4 # 相依快取 with: path: ~/.cache key: ${{ matrix.service }}-${{ hashFiles('**/lock*') }}
# 1. 跑一次完整 CI(3 服務平行) gh run list --workflow ci.yml --limit 1 \ --json status,conclusion,displayTitle # 輸出 → {"status":"completed","conclusion":"success",...} # 2. 快取命中(第二次跑更快) gh run view <run-id> --json jobs \ --jq '.jobs[].steps[] | select(.name|contains("cache")) | .conclusion' # 輸出 → success(且 log 顯示 Cache hit) # 3. 安全掃描結果 gh api /repos/TechCo/app/code-scanning/alerts --jq 'length' # 輸出 → 0(無未修漏洞) # 4. Release 產物 gh release view v2.0.0 --json assets --jq '.assets[].name' # 輸出 → techco-api_2.0.0.tar.gz ...
- 相依快取:key 用 hashFiles 鎖定內容, 命中時省下數分鐘與額度 - Matrix 平行:多 OS / 多版本同時跑 - concurrency 取消「過時的 run」, 避免堆積浪費額度 - 重度建置可改用 container 或 self-hosted runner - 快取 key 記得在依賴變更時自動失效
- 用 reusable workflows / composite actions 消除 YAML 重複,規則只寫一次 - Status check 當閘門:沒過就不能合併 - Artifact 保存測試報告 / 建置產物,供事後檢討 - action 固定到 tag 或完整 SHA(可重現) - README 放 CI 徽章,品質對外可見
- Secrets 放 Settings:repo / org / 環境三層 - GITHUB_TOKEN 最小權限(permissions 明確宣告) - 別在 fork 的 PR 上執行未受信任程式碼 (pull_request_target 有 SSRF / 注入風險) - action 一律固定版本或 SHA,防供應鏈竄改 - Dependabot 掃依賴 + CodeQL 掃程式碼, 納入閘門(單元 8 會再深談)
| 面向 | github | gitlab | markdown | yaml | json |
|---|---|---|---|---|---|
| CI 定義 | .github/workflows/*.yml | .gitlab-ci.yml | —(不涉及) | 兩者都以 YAML 定義 pipeline | — |
| Runner | GitHub-hosted / self-hosted | GitLab Runner(自架為主) | — | — | — |
| 快取 / 矩陣 | 內建 cache + matrix | cache + parallel + include | — | — | — |
| Secrets | repo / org / environment secrets | CI/CD variables(階層制) | — | — | — |
| 與其他欄的關係 | Actions 全部以 YAML 撰寫 | 同左 | workflow 描述與文件用 Markdown | workflow / pipeline 的定義載體 | 事件 payload 與 API 回應用 JSON |