github-actions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GitHub Actions Core Knowledge

GitHub Actions 核心知识

Deep Knowledge: Use
mcp__documentation__fetch_docs
with technology:
github-actions
for comprehensive documentation.
深度参考:使用
mcp__documentation__fetch_docs
工具并指定技术为
github-actions
,可获取完整文档。

Basic CI Workflow

基础CI工作流

yaml
undefined
yaml
undefined

.github/workflows/ci.yml

.github/workflows/ci.yml

name: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: test: runs-on: ubuntu-latest
steps:
  - uses: actions/checkout@v4

  - name: Setup Node.js
    uses: actions/setup-node@v4
    with:
      node-version: '20'
      cache: 'npm'

  - name: Install dependencies
    run: npm ci

  - name: Run linter
    run: npm run lint

  - name: Run tests
    run: npm test

  - name: Build
    run: npm run build
undefined
name: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: test: runs-on: ubuntu-latest
steps:
  - uses: actions/checkout@v4

  - name: Setup Node.js
    uses: actions/setup-node@v4
    with:
      node-version: '20'
      cache: 'npm'

  - name: Install dependencies
    run: npm ci

  - name: Run linter
    run: npm run lint

  - name: Run tests
    run: npm test

  - name: Build
    run: npm run build
undefined

With Database

含数据库的工作流

yaml
jobs:
  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
          POSTGRES_DB: testdb
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    env:
      DATABASE_URL: postgresql://test:test@localhost:5432/testdb

    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npx prisma migrate deploy
      - run: npm test
yaml
jobs:
  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
          POSTGRES_DB: testdb
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    env:
      DATABASE_URL: postgresql://test:test@localhost:5432/testdb

    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npx prisma migrate deploy
      - run: npm test

Deploy Workflow

部署工作流

yaml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v25
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          vercel-args: '--prod'
yaml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Deploy to Vercel
        uses: amondnet/vercel-action@v25
        with:
          vercel-token: ${{ secrets.VERCEL_TOKEN }}
          vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
          vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
          vercel-args: '--prod'

Matrix Strategy

矩阵策略

yaml
jobs:
  test:
    strategy:
      matrix:
        node: [18, 20, 22]
        os: [ubuntu-latest, macos-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}
yaml
jobs:
  test:
    strategy:
      matrix:
        node: [18, 20, 22]
        os: [ubuntu-latest, macos-latest]
    runs-on: ${{ matrix.os }}
    steps:
      - uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node }}

Reusable Workflows

可复用工作流

yaml
undefined
yaml
undefined

.github/workflows/test.yml

.github/workflows/test.yml

on: workflow_call:
jobs: test: runs-on: ubuntu-latest steps: [...]
on: workflow_call:
jobs: test: runs-on: ubuntu-latest steps: [...]

Usage in another workflow

在其他工作流中使用

jobs: call-tests: uses: ./.github/workflows/test.yml
undefined
jobs: call-tests: uses: ./.github/workflows/test.yml
undefined

When NOT to Use This Skill

不适用本技能的场景

Skip this skill when:
  • Using GitLab CI/CD (.gitlab-ci.yml) - different syntax
  • Using Jenkins, CircleCI, Travis CI - different platforms
  • Setting up local development environments - use
    docker-compose
    skill
  • Building Docker images only (no CI needed) - use
    docker
    skill
  • Working with Bitbucket Pipelines - different platform
以下情况请跳过本技能:
  • 使用GitLab CI/CD(.gitlab-ci.yml)——语法不同
  • 使用Jenkins、CircleCI、Travis CI——平台不同
  • 搭建本地开发环境——使用
    docker-compose
    技能
  • 仅构建Docker镜像(无需CI)——使用
    docker
    技能
  • 使用Bitbucket Pipelines——平台不同

Anti-Patterns

反模式

Anti-PatternProblemSolution
No permission restrictionsSecurity risk, excessive accessSet minimal
permissions:
per job
Using action tags like
@v1
Breaking changes on updatesPin to SHA:
@60edb5dd545a775178f52524783378180af0d1f8
Secrets in logsCredential exposureNever
echo
secrets, use
env:
only
No timeout setRunaway jobs consuming minutesSet
timeout-minutes: 15
on jobs
Caching nothingSlow builds, wasted timeCache dependencies with
actions/cache
Running on every commitWasted CI minutesUse
paths:
filters or
pull_request:
only
Hardcoded versionsInconsistent environmentsUse matrix strategy or env vars
No artifact retention limitHigh storage costsSet
retention-days: 7
on artifacts
Storing secrets in codeSecurity breachUse GitHub Secrets, never commit
No branch protectionBypassing CI checksRequire status checks in branch rules
反模式问题解决方案
无权限限制安全风险,权限过度为每个任务设置最小化
permissions:
使用
@v1
这类动作标签
更新时可能引入破坏性变更固定到SHA值:
@60edb5dd545a775178f52524783378180af0d1f8
日志中输出密钥凭证泄露绝不
echo
密钥,仅通过
env:
使用
未设置超时任务失控消耗运行时长为任务设置
timeout-minutes: 15
未配置缓存构建缓慢,浪费时间使用
actions/cache
缓存依赖
每次提交都触发浪费CI运行时长使用
paths:
过滤器或仅在
pull_request:
时触发
硬编码版本环境不一致使用矩阵策略或环境变量
无制品保留期限存储成本过高为制品设置
retention-days: 7
代码中存储密钥安全漏洞使用GitHub Secrets,绝不提交密钥
无分支保护绕过CI检查在分支规则中要求状态检查

Quick Troubleshooting

快速排查指南

IssueDiagnosisFix
Workflow doesn't triggerWrong event, branch filterCheck
on:
triggers and branch names
Job fails silentlyScript errors ignoredDon't use `
Cache never hitsCache key changingUse stable keys:
hashFiles('**/package-lock.json')
"Resource not accessible"Wrong permissionsAdd required
permissions:
to job
Secrets not available in PRForks don't have accessUse
pull_request_target
(carefully) or skip secret steps
Artifact upload failsPath doesn't existCheck build output path, use
if: always()
Matrix job failuresOne config fails allUse
fail-fast: false
to continue other jobs
Workflow takes too longNo caching, sequential jobsAdd caching, parallelize with
needs:
"Context access might be invalid"Wrong context syntaxUse
${{ }}
syntax, check context availability
Can't trigger another workflowNo token permissionUse PAT or
GITHUB_TOKEN
with write permissions
问题诊断修复方案
工作流未触发事件或分支过滤器错误检查
on:
触发器和分支名称
任务静默失败脚本错误被忽略不要使用`
缓存始终不命中缓存键频繁变化使用稳定键:
hashFiles('**/package-lock.json')
"资源不可访问"权限错误为任务添加所需的
permissions:
PR中无法获取密钥分支无权限谨慎使用
pull_request_target
或跳过需要密钥的步骤
制品上传失败路径不存在检查构建输出路径,使用
if: always()
矩阵任务失败一个配置失败导致全部终止使用
fail-fast: false
继续其他任务
工作流耗时过长无缓存、任务串行添加缓存,使用
needs:
并行化任务
"上下文访问可能无效"上下文语法错误使用
${{ }}
语法,检查上下文可用性
无法触发其他工作流令牌无权限使用PAT或具备写入权限的
GITHUB_TOKEN

Production Readiness

生产就绪规范

Security Best Practices

安全最佳实践

yaml
undefined
yaml
undefined

Secure workflow

安全工作流示例

name: CI
on: push: branches: [main] pull_request: branches: [main]
permissions: contents: read pull-requests: write
jobs: build: runs-on: ubuntu-latest timeout-minutes: 15
steps:
  - uses: actions/checkout@v4
    with:
      persist-credentials: false

  # Pin actions to SHA for security
  - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
    with:
      node-version: '20'

  # Use environment secrets
  - name: Deploy
    env:
      API_KEY: ${{ secrets.API_KEY }}
    run: |
      # Never echo secrets
      ./deploy.sh
undefined
name: CI
on: push: branches: [main] pull_request: branches: [main]
permissions: contents: read pull-requests: write
jobs: build: runs-on: ubuntu-latest timeout-minutes: 15
steps:
  - uses: actions/checkout@v4
    with:
      persist-credentials: false

  # 固定动作到SHA值以保障安全
  - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
    with:
      node-version: '20'

  # 使用环境密钥
  - name: Deploy
    env:
      API_KEY: ${{ secrets.API_KEY }}
    run: |
      # 绝不输出密钥
      ./deploy.sh
undefined

Caching Strategy

缓存策略

yaml
jobs:
  build:
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      # Custom caching
      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: |
            ~/.npm
            node_modules
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      # Turbo cache for monorepos
      - name: Cache Turbo
        uses: actions/cache@v4
        with:
          path: .turbo
          key: ${{ runner.os }}-turbo-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-turbo-
yaml
jobs:
  build:
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'

      # 自定义缓存
      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: |
            ~/.npm
            node_modules
          key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
          restore-keys: |
            ${{ runner.os }}-node-

      # 单体仓库Turbo缓存
      - name: Cache Turbo
        uses: actions/cache@v4
        with:
          path: .turbo
          key: ${{ runner.os }}-turbo-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-turbo-

Artifact Management

制品管理

yaml
jobs:
  build:
    steps:
      - name: Build
        run: npm run build

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: build-${{ github.sha }}
          path: dist/
          retention-days: 7

  deploy:
    needs: build
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: build-${{ github.sha }}
          path: dist/
yaml
jobs:
  build:
    steps:
      - name: Build
        run: npm run build

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: build-${{ github.sha }}
          path: dist/
          retention-days: 7

  deploy:
    needs: build
    steps:
      - name: Download artifacts
        uses: actions/download-artifact@v4
        with:
          name: build-${{ github.sha }}
          path: dist/

Environment Protection

环境保护

yaml
jobs:
  deploy-staging:
    runs-on: ubuntu-latest
    environment: staging

  deploy-production:
    runs-on: ubuntu-latest
    needs: deploy-staging
    environment:
      name: production
      url: https://example.com
    concurrency:
      group: production-deploy
      cancel-in-progress: false
yaml
jobs:
  deploy-staging:
    runs-on: ubuntu-latest
    environment: staging

  deploy-production:
    runs-on: ubuntu-latest
    needs: deploy-staging
    environment:
      name: production
      url: https://example.com
    concurrency:
      group: production-deploy
      cancel-in-progress: false

Error Handling

错误处理

yaml
jobs:
  build:
    steps:
      - name: Run tests
        id: tests
        continue-on-error: true
        run: npm test

      - name: Upload test results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: test-results
          path: coverage/

      - name: Check test status
        if: steps.tests.outcome == 'failure'
        run: |
          echo "Tests failed"
          exit 1

      - name: Notify on failure
        if: failure()
        uses: slackapi/slack-github-action@v1
        with:
          payload: |
            {"text": "Build failed: ${{ github.repository }}"}
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
yaml
jobs:
  build:
    steps:
      - name: Run tests
        id: tests
        continue-on-error: true
        run: npm test

      - name: Upload test results
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: test-results
          path: coverage/

      - name: Check test status
        if: steps.tests.outcome == 'failure'
        run: |
          echo "Tests failed"
          exit 1

      - name: Notify on failure
        if: failure()
        uses: slackapi/slack-github-action@v1
        with:
          payload: |
            {"text": "Build failed: ${{ github.repository }}"}
        env:
          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}

Dependabot Configuration

Dependabot 配置

yaml
undefined
yaml
undefined

.github/dependabot.yml

.github/dependabot.yml

version: 2 updates:
  • package-ecosystem: "npm" directory: "/" schedule: interval: "weekly" groups: development-dependencies: patterns: - "@types/" - "eslint" - "prettier*"
  • package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly"
undefined
version: 2 updates:
  • package-ecosystem: "npm" directory: "/" schedule: interval: "weekly" groups: development-dependencies: patterns: - "@types/" - "eslint" - "prettier*"
  • package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly"
undefined

Release Workflow

发布工作流

yaml
name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4

      - name: Build
        run: npm run build

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
          generate_release_notes: true
yaml
name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4

      - name: Build
        run: npm run build

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
          generate_release_notes: true

Monitoring Metrics

监控指标

MetricTarget
Build success rate> 95%
Build duration< 10min
Cache hit rate> 80%
Deployment frequencyAs needed
指标目标值
构建成功率> 95%
构建时长< 10分钟
缓存命中率> 80%
部署频率按需进行

Checklist

检查清单

  • Minimal permissions declared
  • Actions pinned to SHA
  • Secrets not exposed in logs
  • Caching configured
  • Timeouts set
  • Error notifications
  • Environment protection rules
  • Dependabot enabled
  • Branch protection rules
  • Concurrency controls
  • 已声明最小权限
  • 动作已固定到SHA值
  • 密钥未在日志中暴露
  • 已配置缓存
  • 已设置超时
  • 已配置错误通知
  • 已设置环境保护规则
  • 已启用Dependabot
  • 已设置分支保护规则
  • 已配置并发控制

Reference Documentation

参考文档

  • Caching
  • Secrets
  • 缓存
  • 密钥