| name | github-actions-setup |
| description | 配置 GitHub Actions 工作流,包括 CI/CD 自动触发、构建、测试等。
当用户提到"配置 GitHub Actions"、"设置 CI/CD"、"添加 workflow"、"自动构建"、"自动测试"、
"github action 触发"、"workflow 配置"、"CI 流水线"、"持续集成"时使用此技能。
也适用于需要修改现有 workflow、排查 workflow 失败、或添加新的自动化流程的场景。
|
GitHub Actions 工作流配置指南
帮助快速配置 GitHub Actions 工作流,覆盖常见的 CI/CD 场景。
工作流基础结构
name: Workflow Name
on:
push:
branches: [main]
jobs:
job-name:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Step name
run: echo "Hello"
触发器配置
on:
push:
branches: [main, develop]
paths: ['src/**', 'package.json']
tags: ['v*']
on:
pull_request:
branches: [main]
on:
release:
types: [published]
on:
schedule:
- cron: '0 2 * * 1-5'
on:
workflow_dispatch:
inputs:
environment:
description: 'Deploy environment'
type: choice
options: [staging, production]
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
常用工作流模板
Node.js 项目 CI
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [20, 22, 24]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm run build
- run: npm test
Docker 构建推送
name: Docker
on:
push:
tags: ['v*']
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
push: true
tags: ghcr.io/${{ github.repository }}:${{ github.ref_name }}
Environment、Secrets 与 Permissions
Environment 与 Secret 管理
gh api repos/{owner}/{repo}/environments/{env-name} -X PUT --input - <<< '{}'
gh secret set SECRET_NAME --body "value"
gh secret set SECRET_NAME --env production --body "value"
在 workflow 中引用:environment: production + ${{ secrets.DEPLOY_TOKEN }}
Permissions
GitHub Actions 默认权限较小,按需显式声明:
permissions:
contents: read
id-token: write
packages: write
pull-requests: write
最小权限原则:只声明需要的权限。
实用技巧
- run: npm run deploy
if: github.ref == 'refs/heads/main'
jobs:
lint: ...
test: ...
build:
needs: [lint, test]
排查 Workflow 失败
gh run list --limit 5
gh run view {run-id} --log-failed
gh run rerun {run-id} --failed
常见原因:Node 版本过低、permissions 不足、Secret 未配置、package-lock.json 未提交、actions 版本过旧。
参考文档