github-actions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseGitHub Actions Core Knowledge
GitHub Actions 核心知识
Deep Knowledge: Usewith technology:mcp__documentation__fetch_docsfor comprehensive documentation.github-actions
深度参考:使用工具并指定技术为mcp__documentation__fetch_docs,可获取完整文档。github-actions
Basic CI Workflow
基础CI工作流
yaml
undefinedyaml
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 buildundefinedname: 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 buildundefinedWith 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 testyaml
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 testDeploy 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
undefinedyaml
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
undefinedjobs:
call-tests:
uses: ./.github/workflows/test.yml
undefinedWhen 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 skill
docker-compose - Building Docker images only (no CI needed) - use skill
docker - 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-Pattern | Problem | Solution |
|---|---|---|
| No permission restrictions | Security risk, excessive access | Set minimal |
Using action tags like | Breaking changes on updates | Pin to SHA: |
| Secrets in logs | Credential exposure | Never |
| No timeout set | Runaway jobs consuming minutes | Set |
| Caching nothing | Slow builds, wasted time | Cache dependencies with |
| Running on every commit | Wasted CI minutes | Use |
| Hardcoded versions | Inconsistent environments | Use matrix strategy or env vars |
| No artifact retention limit | High storage costs | Set |
| Storing secrets in code | Security breach | Use GitHub Secrets, never commit |
| No branch protection | Bypassing CI checks | Require status checks in branch rules |
| 反模式 | 问题 | 解决方案 |
|---|---|---|
| 无权限限制 | 安全风险,权限过度 | 为每个任务设置最小化 |
使用 | 更新时可能引入破坏性变更 | 固定到SHA值: |
| 日志中输出密钥 | 凭证泄露 | 绝不 |
| 未设置超时 | 任务失控消耗运行时长 | 为任务设置 |
| 未配置缓存 | 构建缓慢,浪费时间 | 使用 |
| 每次提交都触发 | 浪费CI运行时长 | 使用 |
| 硬编码版本 | 环境不一致 | 使用矩阵策略或环境变量 |
| 无制品保留期限 | 存储成本过高 | 为制品设置 |
| 代码中存储密钥 | 安全漏洞 | 使用GitHub Secrets,绝不提交密钥 |
| 无分支保护 | 绕过CI检查 | 在分支规则中要求状态检查 |
Quick Troubleshooting
快速排查指南
| Issue | Diagnosis | Fix |
|---|---|---|
| Workflow doesn't trigger | Wrong event, branch filter | Check |
| Job fails silently | Script errors ignored | Don't use ` |
| Cache never hits | Cache key changing | Use stable keys: |
| "Resource not accessible" | Wrong permissions | Add required |
| Secrets not available in PR | Forks don't have access | Use |
| Artifact upload fails | Path doesn't exist | Check build output path, use |
| Matrix job failures | One config fails all | Use |
| Workflow takes too long | No caching, sequential jobs | Add caching, parallelize with |
| "Context access might be invalid" | Wrong context syntax | Use |
| Can't trigger another workflow | No token permission | Use PAT or |
| 问题 | 诊断 | 修复方案 |
|---|---|---|
| 工作流未触发 | 事件或分支过滤器错误 | 检查 |
| 任务静默失败 | 脚本错误被忽略 | 不要使用` |
| 缓存始终不命中 | 缓存键频繁变化 | 使用稳定键: |
| "资源不可访问" | 权限错误 | 为任务添加所需的 |
| PR中无法获取密钥 | 分支无权限 | 谨慎使用 |
| 制品上传失败 | 路径不存在 | 检查构建输出路径,使用 |
| 矩阵任务失败 | 一个配置失败导致全部终止 | 使用 |
| 工作流耗时过长 | 无缓存、任务串行 | 添加缓存,使用 |
| "上下文访问可能无效" | 上下文语法错误 | 使用 |
| 无法触发其他工作流 | 令牌无权限 | 使用PAT或具备写入权限的 |
Production Readiness
生产就绪规范
Security Best Practices
安全最佳实践
yaml
undefinedyaml
undefinedSecure 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.shundefinedname: 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.shundefinedCaching 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: falseyaml
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: falseError 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
undefinedyaml
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"
undefinedversion: 2
updates:
-
package-ecosystem: "npm" directory: "/" schedule: interval: "weekly" groups: development-dependencies: patterns: - "@types/" - "eslint" - "prettier*"
-
package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly"
undefinedRelease 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: trueyaml
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: trueMonitoring Metrics
监控指标
| Metric | Target |
|---|---|
| Build success rate | > 95% |
| Build duration | < 10min |
| Cache hit rate | > 80% |
| Deployment frequency | As 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
- 缓存
- 密钥