writing-github-actions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseWriting GitHub Actions
编写GitHub Actions
Create GitHub Actions workflows for CI/CD pipelines, automated testing, deployments, and repository automation using YAML-based configuration with native GitHub integration.
利用基于YAML的配置以及GitHub原生集成能力,为CI/CD流水线、自动化测试、部署和仓库自动化场景创建GitHub Actions工作流。
Purpose
用途
GitHub Actions is the native CI/CD platform for GitHub repositories. This skill covers workflow syntax, triggers, job orchestration, reusable patterns, optimization techniques, and security practices specific to GitHub Actions.
Core Focus:
- Workflow YAML syntax and structure
- Reusable workflows and composite actions
- Matrix builds and parallel execution
- Caching and optimization strategies
- Secrets management and OIDC authentication
- Concurrency control and artifact management
Not Covered:
- CI/CD pipeline design strategy → See
building-ci-pipelines - GitOps deployment patterns → See
gitops-workflows - Infrastructure as code → See
infrastructure-as-code - Testing frameworks → See
testing-strategies
GitHub Actions是GitHub仓库的原生CI/CD平台。本技能涵盖GitHub Actions特有的工作流语法、触发器、任务编排、可复用模式、优化技巧和安全实践。
核心重点:
- 工作流YAML语法与结构
- 可复用工作流与复合操作
- 矩阵构建与并行执行
- 缓存与优化策略
- 密钥管理与OIDC认证
- 并发控制与制品管理
未涵盖内容:
- CI/CD流水线设计策略 → 参见
building-ci-pipelines - GitOps部署模式 → 参见
gitops-workflows - 基础设施即代码 → 参见
infrastructure-as-code - 测试框架 → 参见
testing-strategies
When to Use This Skill
适用场景
Trigger this skill when:
- Creating CI/CD workflows for GitHub repositories
- Automating tests, builds, and deployments via GitHub Actions
- Setting up reusable workflows across multiple repositories
- Optimizing workflow performance with caching and parallelization
- Implementing security best practices for GitHub Actions
- Troubleshooting GitHub Actions YAML syntax or behavior
以下场景可使用本技能:
- 为GitHub仓库创建CI/CD工作流
- 通过GitHub Actions自动化测试、构建与部署
- 在多个仓库间配置可复用工作流
- 利用缓存与并行化优化工作流性能
- 实施GitHub Actions安全最佳实践
- 排查GitHub Actions YAML语法或运行问题
Workflow Fundamentals
工作流基础
Basic Workflow Structure
基础工作流结构
yaml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm testKey Components:
- : Workflow display name
name - : Trigger events (push, pull_request, schedule, workflow_dispatch)
on - : Job definitions (run in parallel by default)
jobs - : Runner type (ubuntu-latest, windows-latest, macos-latest)
runs-on - : Sequential operations (uses actions or run commands)
steps
yaml
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test核心组件:
- : 工作流显示名称
name - : 触发事件(push、pull_request、schedule、workflow_dispatch)
on - : 任务定义(默认并行运行)
jobs - : 运行器类型(ubuntu-latest、windows-latest、macos-latest)
runs-on - : 顺序执行的操作(使用已有actions或运行命令)
steps
Common Triggers
常见触发器
yaml
undefinedyaml
undefinedCode events
代码事件
on:
push:
branches: [main, develop]
paths: ['src/**']
pull_request:
types: [opened, synchronize, reopened]
on:
push:
branches: [main, develop]
paths: ['src/**']
pull_request:
types: [opened, synchronize, reopened]
Manual trigger
手动触发
on:
workflow_dispatch:
inputs:
environment:
type: choice
options: [dev, staging, production]
on:
workflow_dispatch:
inputs:
environment:
type: choice
options: [dev, staging, production]
Scheduled
定时触发
on:
schedule:
- cron: '0 2 * * *' # Daily at 2 AM UTC
For complete trigger reference, see `references/triggers-events.md`.on:
schedule:
- cron: '0 2 * * *' # UTC时间每日凌晨2点
完整触发器参考请见`references/triggers-events.md`。Decision Frameworks
决策框架
Reusable Workflow vs Composite Action
可复用工作流 vs 复合操作
Use Reusable Workflow when:
- Standardizing entire CI/CD jobs across repositories
- Need complete job replacement with inputs/outputs
- Want secrets to inherit by default
- Orchestrating multiple steps with job-level configuration
Use Composite Action when:
- Packaging 5-20 step sequences for reuse
- Need step-level abstraction within jobs
- Want to distribute via marketplace or private repos
- Require local file access without artifacts
| Feature | Reusable Workflow | Composite Action |
|---|---|---|
| Scope | Complete job | Step sequence |
| Trigger | | |
| Secrets | Inherit by default | Must pass explicitly |
| File Sharing | Requires artifacts | Same runner/workspace |
For detailed patterns, see and .
references/reusable-workflows.mdreferences/composite-actions.md使用可复用工作流的场景:
- 在多个仓库间标准化完整的CI/CD任务
- 需要通过输入/输出实现完整任务替换
- 希望默认继承密钥
- 通过任务级编排管理多步骤操作
使用复合操作的场景:
- 封装5-20个步骤的序列以供复用
- 需要在任务内实现步骤级抽象
- 希望通过市场或私有仓库分发
- 需要无需制品即可访问本地文件
| 特性 | 可复用工作流 | 复合操作 |
|---|---|---|
| 范围 | 完整任务 | 步骤序列 |
| 触发方式 | | 步骤中使用 |
| 密钥 | 默认继承 | 必须显式传递 |
| 文件共享 | 需要借助制品 | 同一运行器/工作区 |
详细模式请见和。
references/reusable-workflows.mdreferences/composite-actions.mdCaching Strategy
缓存策略
Use Built-in Setup Action Caching (Recommended):
yaml
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm' # or 'yarn', 'pnpm'Available for: Node.js, Python (pip), Java (maven/gradle), .NET, Go
Use Manual Caching when:
- Need custom cache keys
- Caching build outputs or non-standard paths
- Implementing multi-layer cache strategies
yaml
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json') }}
restore-keys: ${{ runner.os }}-deps-For optimization techniques, see .
references/caching-strategies.md推荐使用内置Setup Action缓存:
yaml
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm' # 或 'yarn'、'pnpm'支持的环境:Node.js、Python(pip)、Java(maven/gradle)、.NET、Go
以下场景使用手动缓存:
- 需要自定义缓存键
- 缓存构建输出或非标准路径
- 实现多层缓存策略
yaml
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json') }}
restore-keys: ${{ runner.os }}-deps-优化技巧请见。
references/caching-strategies.mdSelf-Hosted vs GitHub-Hosted Runners
自托管运行器 vs GitHub托管运行器
Use GitHub-Hosted Runners when:
- Standard build environments sufficient
- No private network access required
- Within budget or free tier limits
Use Self-Hosted Runners when:
- Need specific hardware (GPU, ARM, high memory)
- Require private network/VPN access
- High usage volume (cost optimization)
- Custom software must be pre-installed
使用GitHub托管运行器的场景:
- 标准构建环境足够满足需求
- 无需私有网络访问
- 在免费额度或预算范围内
使用自托管运行器的场景:
- 需要特定硬件(GPU、ARM、高内存)
- 要求私有网络/VPN访问
- 使用量较大(优化成本)
- 必须预安装自定义软件
Common Patterns
常见模式
Multi-Job Workflow with Dependencies
带依赖的多任务工作流
yaml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- run: npm run build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
test:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v5
with:
name: dist
- run: npm test
deploy:
needs: [build, test]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/download-artifact@v5
- run: ./deploy.shKey Elements:
- creates job dependencies (sequential execution)
needs: - Artifacts pass data between jobs
- enables conditional execution
if: - enables protection rules and environment secrets
environment:
yaml
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- run: npm run build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
test:
needs: build
runs-on: ubuntu-latest
steps:
- uses: actions/download-artifact@v5
with:
name: dist
- run: npm test
deploy:
needs: [build, test]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/download-artifact@v5
- run: ./deploy.sh核心元素:
- 定义任务依赖(顺序执行)
needs: - 制品用于在任务间传递数据
- 实现条件执行
if: - 启用保护规则和环境密钥
environment:
Matrix Builds
矩阵构建
yaml
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: [18, 20, 22]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: npm testResult: 9 jobs (3 OS × 3 Node versions)
For advanced matrix patterns, see .
examples/matrix-build.ymlyaml
jobs:
test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
node: [18, 20, 22]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: npm test执行结果:9个任务(3种操作系统 × 3个Node.js版本)
高级矩阵模式请见。
examples/matrix-build.ymlConcurrency Control
并发控制
yaml
undefinedyaml
undefinedCancel in-progress runs on new push
新推送时取消正在运行的任务
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
Single deployment per environment
每个环境仅允许单个部署任务
jobs:
deploy:
concurrency:
group: production-deployment
cancel-in-progress: false
steps: [...]
undefinedjobs:
deploy:
concurrency:
group: production-deployment
cancel-in-progress: false
steps: [...]
undefinedReusable Workflows
可复用工作流
Defining a Reusable Workflow
定义可复用工作流
File:
.github/workflows/reusable-build.ymlyaml
name: Reusable Build
on:
workflow_call:
inputs:
node-version:
type: string
default: '20'
secrets:
NPM_TOKEN:
required: false
outputs:
artifact-name:
value: ${{ jobs.build.outputs.artifact }}
jobs:
build:
runs-on: ubuntu-latest
outputs:
artifact: build-output
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
- run: npm ci && npm run build
- uses: actions/upload-artifact@v4
with:
name: build-output
path: dist/文件:
.github/workflows/reusable-build.ymlyaml
name: Reusable Build
on:
workflow_call:
inputs:
node-version:
type: string
default: '20'
secrets:
NPM_TOKEN:
required: false
outputs:
artifact-name:
value: ${{ jobs.build.outputs.artifact }}
jobs:
build:
runs-on: ubuntu-latest
outputs:
artifact: build-output
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
- run: npm ci && npm run build
- uses: actions/upload-artifact@v4
with:
name: build-output
path: dist/Calling a Reusable Workflow
调用可复用工作流
yaml
jobs:
build:
uses: ./.github/workflows/reusable-build.yml
with:
node-version: '20'
secrets: inherit # Same org onlyFor complete reusable workflow guide, see .
references/reusable-workflows.mdyaml
jobs:
build:
uses: ./.github/workflows/reusable-build.yml
with:
node-version: '20'
secrets: inherit # 仅同一组织内可用完整可复用工作流指南请见。
references/reusable-workflows.mdComposite Actions
复合操作
Defining a Composite Action
定义复合操作
File:
.github/actions/setup-project/action.ymlyaml
name: 'Setup Project'
description: 'Install dependencies and setup environment'
inputs:
node-version:
description: 'Node.js version'
default: '20'
outputs:
cache-hit:
value: ${{ steps.cache.outputs.cache-hit }}
runs:
using: "composite"
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
cache: 'npm'
- id: cache
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json') }}
- if: steps.cache.outputs.cache-hit != 'true'
shell: bash
run: npm ciKey Requirements:
- marks action type
runs.using: "composite" - required for all
shell:stepsrun - Access inputs via
${{ inputs.name }}
文件:
.github/actions/setup-project/action.ymlyaml
name: 'Setup Project'
description: 'Install dependencies and setup environment'
inputs:
node-version:
description: 'Node.js version'
default: '20'
outputs:
cache-hit:
value: ${{ steps.cache.outputs.cache-hit }}
runs:
using: "composite"
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
cache: 'npm'
- id: cache
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-deps-${{ hashFiles('**/package-lock.json') }}
- if: steps.cache.outputs.cache-hit != 'true'
shell: bash
run: npm ci核心要求:
- 标记操作类型
runs.using: "composite" - 所有步骤必须指定
runshell: - 通过访问输入参数
${{ inputs.name }}
Using a Composite Action
使用复合操作
yaml
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/setup-project
with:
node-version: '20'
- run: npm run buildFor detailed composite action patterns, see .
references/composite-actions.mdyaml
steps:
- uses: actions/checkout@v5
- uses: ./.github/actions/setup-project
with:
node-version: '20'
- run: npm run build详细复合操作模式请见。
references/composite-actions.mdSecurity Best Practices
安全最佳实践
Secrets Management
密钥管理
yaml
jobs:
deploy:
runs-on: ubuntu-latest
environment: production # Uses environment secrets
steps:
- env:
API_KEY: ${{ secrets.API_KEY }}
run: ./deploy.shyaml
jobs:
deploy:
runs-on: ubuntu-latest
environment: production # 使用环境密钥
steps:
- env:
API_KEY: ${{ secrets.API_KEY }}
run: ./deploy.shOIDC Authentication (No Long-Lived Credentials)
OIDC认证(无长期凭证)
yaml
jobs:
deploy:
runs-on: ubuntu-latest
permissions:
id-token: write # Required for OIDC
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsRole
aws-region: us-east-1
- run: aws s3 sync ./dist s3://my-bucketyaml
jobs:
deploy:
runs-on: ubuntu-latest
permissions:
id-token: write # OIDC必需
contents: read
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/GitHubActionsRole
aws-region: us-east-1
- run: aws s3 sync ./dist s3://my-bucketMinimal Permissions
最小权限原则
yaml
undefinedyaml
undefinedWorkflow-level
工作流级权限
permissions:
contents: read
pull-requests: write
permissions:
contents: read
pull-requests: write
Job-level
任务级权限
jobs:
deploy:
permissions:
contents: write
deployments: write
steps: [...]
undefinedjobs:
deploy:
permissions:
contents: write
deployments: write
steps: [...]
undefinedAction Pinning
操作版本固定
yaml
undefinedyaml
undefinedPin to commit SHA (not tags)
固定到提交SHA(而非标签)
- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v5.0.0
**Enable Dependabot:**
File: `.github/dependabot.yml`
```yaml
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"For comprehensive security guide, see .
references/security-practices.md- uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608 # v5.0.0
**启用Dependabot:**
文件:`.github/dependabot.yml`
```yaml
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"完整安全指南请见。
references/security-practices.mdOptimization Techniques
优化技巧
Use built-in caching in setup actions (), run independent jobs in parallel, add conditional execution with , and minimize checkout depth ().
cache: 'npm'if:fetch-depth: 1For detailed optimization strategies, see .
references/caching-strategies.md使用Setup Action中的内置缓存(),并行运行独立任务,通过实现条件执行,并最小化检出深度()。
cache: 'npm'if:fetch-depth: 1详细优化策略请见。
references/caching-strategies.mdContext Variables
上下文变量
Common contexts: , , , ,
github.*secrets.*inputs.*matrix.*runner.*yaml
- run: echo "Branch: ${{ github.ref }}, Event: ${{ github.event_name }}"For complete syntax reference, see .
references/workflow-syntax.md常见上下文:、、、、
github.*secrets.*inputs.*matrix.*runner.*yaml
- run: echo "Branch: ${{ github.ref }}, Event: ${{ github.event_name }}"完整语法参考请见。
references/workflow-syntax.mdProgressive Disclosure
进阶参考
Detailed References
详细文档
For comprehensive coverage of specific topics:
- references/workflow-syntax.md - Complete YAML syntax reference
- references/reusable-workflows.md - Advanced reusable workflow patterns
- references/composite-actions.md - Composite action deep dive
- references/caching-strategies.md - Optimization and caching techniques
- references/security-practices.md - Comprehensive security guide
- references/triggers-events.md - All trigger types and event filters
- references/marketplace-actions.md - Recommended actions catalog
特定主题的完整覆盖:
- references/workflow-syntax.md - 完整YAML语法参考
- references/reusable-workflows.md - 高级可复用工作流模式
- references/composite-actions.md - 复合操作深度解析
- references/caching-strategies.md - 优化与缓存技巧
- references/security-practices.md - 全面安全指南
- references/triggers-events.md - 所有触发器类型与事件过滤器
- references/marketplace-actions.md - 推荐操作目录
Working Examples
可用示例
Complete workflow templates ready to use:
- examples/basic-ci.yml - Simple CI workflow
- examples/matrix-build.yml - Matrix strategy examples
- examples/reusable-deploy.yml - Reusable deployment workflow
- examples/composite-setup/ - Composite action template
- examples/monorepo-workflow.yml - Monorepo with path filters
- examples/security-scan.yml - Security scanning workflow
可直接使用的完整工作流模板:
- examples/basic-ci.yml - 简单CI工作流
- examples/matrix-build.yml - 矩阵策略示例
- examples/reusable-deploy.yml - 可复用部署工作流
- examples/composite-setup/ - 复合操作模板
- examples/monorepo-workflow.yml - 带路径过滤的单体仓库工作流
- examples/security-scan.yml - 安全扫描工作流
Validation Scripts
验证脚本
- scripts/validate-workflow.sh - Validate YAML syntax
- scripts/validate-workflow.sh - 验证YAML语法
Related Skills
相关技能
- - CI/CD pipeline design strategy
building-ci-pipelines - - GitOps deployment patterns
gitops-workflows - - Terraform/Pulumi integration
infrastructure-as-code - - Test frameworks and coverage
testing-strategies - - SAST/DAST tools
security-hardening - - Understanding branches and PRs
git-workflows
- - CI/CD流水线设计策略
building-ci-pipelines - - GitOps部署模式
gitops-workflows - - Terraform/Pulumi集成
infrastructure-as-code - - 测试框架与覆盖率
testing-strategies - - SAST/DAST工具
security-hardening - - 分支与PR管理
git-workflows