YAML 語法

部分內容由 LLM 生成,尚未經過人工驗證。

GitHub Actions workflow 檔案的 YAML 語法關鍵字快速參考。

Workflow 基本結構

頂層關鍵字

關鍵字說明用途範例
nameWorkflow 名稱在 Actions 介面顯示的識別名稱name: CI Pipeline
run-name執行實例名稱動態顯示每次執行的名稱(可用表達式)run-name: Deploy by @${{ github.actor }}
on觸發事件定義何時執行 workflowon: push
permissions權限設定控制 GITHUB_TOKEN 的存取權限permissions: read-all
env環境變數全域環境變數(所有 jobs 可用)env: NODE_ENV: production
defaults預設設定為所有 jobs/steps 設定預設值defaults: run: shell: bash
concurrency並發控制限制同時執行的 workflow 數量concurrency: production
jobs工作定義包含一個或多個 job(必填)jobs: build: ...

觸發事件(on)

單一事件

on: push

多事件觸發

on: [push, pull_request, workflow_dispatch]

事件類型與過濾器

關鍵字說明範例
push推送代碼時觸發on: push: branches: [main]
pull_requestPR 事件觸發on: pull_request: types: [opened, synchronize]
workflow_dispatch手動觸發on: workflow_dispatch: inputs: ...
schedule定時觸發(cron)on: schedule: - cron: '0 0 * * *'
workflow_call被其他 workflow 呼叫on: workflow_call: inputs: ...
repository_dispatch外部 API 觸發on: repository_dispatch: types: [custom-event]

過濾器關鍵字

關鍵字說明範例
branches限制分支branches: [main, 'releases/**']
branches-ignore排除分支branches-ignore: [staging]
tags限制標籤tags: ['v*.*.*']
paths限制檔案路徑paths: ['src/**', '**.js']
paths-ignore排除檔案路徑paths-ignore: ['docs/**']
types事件子類型types: [opened, reopened, closed]

Jobs 定義

Job 層級關鍵字

關鍵字說明用途範例
runs-on執行環境指定 runner(必填)runs-on: ubuntu-latest
needs依賴關係定義 job 執行順序needs: [build, test]
if條件執行根據條件決定是否執行if: github.ref == 'refs/heads/main'
strategy執行策略矩陣建構、並行控制strategy: matrix: node: [14, 16, 18]
steps步驟列表包含一系列 step(必填)steps: - uses: actions/checkout@v4
timeout-minutes超時時間限制 job 最大執行時間timeout-minutes: 30
continue-on-error忽略錯誤允許 job 失敗但不中斷 workflowcontinue-on-error: true
container容器執行在容器中執行 jobcontainer: node:18
services服務容器啟動服務容器(如 Redis、Postgres)services: redis: image: redis
outputs輸出變數傳遞資料給其他 joboutputs: version: ${{ steps.get-version.outputs.value }}
env環境變數Job 層級環境變數env: NODE_ENV: test
defaults預設設定Job 層級預設值defaults: run: working-directory: ./app
concurrency並發控制Job 層級並發限制concurrency: deploy-${{ github.ref }}
permissions權限設定Job 層級權限覆寫permissions: contents: read

Runs-on 可用值

說明
ubuntu-latestUbuntu 最新版(目前 Ubuntu 22.04)
ubuntu-22.04Ubuntu 22.04
ubuntu-20.04Ubuntu 20.04
windows-latestWindows Server 最新版
windows-2022Windows Server 2022
macos-latestmacOS 最新版
macos-13macOS 13 Ventura
self-hosted自託管 runner

Strategy 矩陣建構

關鍵字說明範例
matrix矩陣變數matrix: os: [ubuntu, windows] node: [14, 16]
include新增矩陣組合include: - os: ubuntu, node: 18, experimental: true
exclude排除矩陣組合exclude: - os: windows, node: 14
fail-fast快速失敗任一組合失敗立即停止其他
max-parallel最大並行數限制同時執行的 job 數量

Steps 定義

Step 層級關鍵字

關鍵字說明用途範例
name步驟名稱顯示在 logs 中的識別名稱name: Install dependencies
id步驟 ID唯一識別碼,用於引用輸出id: get-version
uses使用 Action引用預建 Actionuses: actions/checkout@v4
run執行命令執行 shell 命令run: npm install
with傳入參數傳遞輸入參數給 Actionwith: node-version: 18
env環境變數Step 層級環境變數env: API_KEY: ${{ secrets.API_KEY }}
if條件執行根據條件決定是否執行if: success()
continue-on-error忽略錯誤允許 step 失敗但不中斷 jobcontinue-on-error: true
timeout-minutes超時時間限制 step 最大執行時間timeout-minutes: 5
shellShell 類型指定執行命令的 shellshell: bash
working-directory工作目錄指定命令執行的目錄working-directory: ./backend

Shell 可用值

說明適用平台
bashBash shell(預設)Linux, macOS, Windows (Git Bash)
pwshPowerShell CoreLinux, macOS, Windows
powershellWindows PowerShellWindows
cmd命令提示字元Windows
shPOSIX shellLinux, macOS
pythonPython 解釋器所有平台

條件與表達式(if)

常用狀態檢查函式

函式說明範例
success()前面所有步驟成功if: success()
failure()任一前面步驟失敗if: failure()
always()無論成功失敗都執行if: always()
cancelled()Workflow 被取消if: cancelled()

常用表達式語法

語法說明範例
${{ ... }}表達式語法${{ github.ref }}
github.event_name觸發事件名稱if: github.event_name == 'push'
github.refGit 引用(分支/標籤)if: github.ref == 'refs/heads/main'
github.actor觸發者用戶名${{ github.actor }}
secrets.SECRET_NAME存取 secret${{ secrets.GITHUB_TOKEN }}
steps.<step-id>.outputs.<output-name>引用 step 輸出${{ steps.build.outputs.version }}

環境與 Secrets

環境變數優先級

  1. Step 層級 env - 最高優先級
  2. Job 層級 env
  3. Workflow 層級 env
  4. 系統環境變數 - 最低優先級

預定義環境變數

變數說明
GITHUB_TOKEN自動產生的驗證 token
GITHUB_REPOSITORY儲存庫名稱(owner/repo)
GITHUB_REFGit 引用(分支/標籤)
GITHUB_SHACommit SHA
GITHUB_WORKFLOWWorkflow 名稱
GITHUB_RUN_IDWorkflow 執行 ID
GITHUB_ACTOR觸發者用戶名
RUNNER_OSRunner 作業系統(Linux/Windows/macOS)
RUNNER_TEMPRunner 暫存目錄

Secrets 存取

env:
  API_KEY: ${{ secrets.API_KEY }}

Permissions 權限控制

可設定權限

權限說明可用值
actionsGitHub Actions 工作流程read, write, none
checks檢查執行read, write, none
contents儲存庫內容read, write, none
deployments部署read, write, none
id-tokenOIDC tokenread, write, none
issuesIssuesread, write, none
packagesGitHub Packagesread, write, none
pull-requestsPull Requestsread, write, none
security-events安全事件read, write, none

快捷設定

permissions: read-all    # 所有權限設為 read
permissions: write-all   # 所有權限設為 write
permissions: {}          # 停用所有權限

其他進階關鍵字

Concurrency 並發控制

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true  # 取消進行中的舊執行

Container 容器執行

container:
  image: node:18
  credentials:
    username: ${{ github.actor }}
    password: ${{ secrets.GITHUB_TOKEN }}
  env:
    NODE_ENV: test
  volumes:
    - /tmp:/workspace
  options: --cpus 2

Services 服務容器

services:
  postgres:
    image: postgres:14
    env:
      POSTGRES_PASSWORD: postgres
    options: >-
      --health-cmd pg_isready
      --health-interval 10s
      --health-timeout 5s
      --health-retries 5
    ports:
      - 5432:5432

Workflow_dispatch 手動觸發輸入

on:
  workflow_dispatch:
    inputs:
      environment:
        description: 'Deployment environment'
        required: true
        type: choice
        options:
          - dev
          - staging
          - production
      debug:
        description: 'Enable debug mode'
        required: false
        type: boolean
        default: false