github-actions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

GitHub Actions

GitHub Actions

Overview

概述

GitHub Actions is a CI/CD platform that automates build, test, and deployment pipelines directly from GitHub repositories. Workflows are YAML files in
.github/workflows/
triggered by events like pushes, pull requests, schedules, or manual dispatch. Each workflow contains one or more jobs that run on GitHub-hosted or self-hosted runners.
When to use: Automated testing, continuous deployment, release automation, scheduled tasks, multi-platform builds, dependency updates, container publishing, code quality checks, security scanning.
When NOT to use: Long-running services (use a proper hosting platform), heavy compute tasks exceeding runner limits (6-hour job timeout), tasks requiring persistent state between runs (use external storage), real-time event processing (use webhooks with a server).
GitHub Actions 是一款CI/CD平台,可直接从GitHub仓库中自动化构建、测试和部署流水线。工作流是存储在
.github/workflows/
目录下的YAML文件,由推送、拉取请求、定时任务或手动触发等事件触发。每个工作流包含一个或多个在GitHub托管或自托管运行器上执行的任务。
适用场景: 自动化测试、持续部署、发布自动化、定时任务、多平台构建、依赖更新、容器发布、代码质量检查、安全扫描。
不适用场景: 长时间运行的服务(请使用专业托管平台)、超过运行器限制的重计算任务(任务超时时间为6小时)、需要在多次运行间保持持久状态的任务(请使用外部存储)、实时事件处理(请搭配服务器使用webhook)。

Quick Reference

快速参考

PatternSyntax / ActionKey Points
Push trigger
on: push: branches: [main]
Filter by branch, path, or tag
PR trigger
on: pull_request: types: [opened, synchronize]
Defaults to opened, synchronize, reopened
Scheduled trigger
on: schedule: - cron: '0 6 * * 1'
UTC only, minimum 5-minute interval
Manual trigger
on: workflow_dispatch: inputs:
Define typed inputs for manual runs
Job dependencies
needs: [build, test]
Run jobs in sequence or parallel
Conditional job
if: github.ref == 'refs/heads/main'
Expression-based job/step filtering
Matrix strategy
strategy: matrix: node: [18, 20, 22]
Generates jobs for each combination
Dependency cache
actions/cache@v4
Hash-based keys with restore-keys fallback
Setup with cache
actions/setup-node@v4
with
cache: 'pnpm'
Built-in caching for package managers
Upload artifact
actions/upload-artifact@v4
Share data between jobs or preserve outputs
Download artifact
actions/download-artifact@v4
Retrieve artifacts from earlier jobs
Reusable workflow
uses: ./.github/workflows/reusable.yml
Called with
workflow_call
trigger
Composite action
action.yml
with
using: composite
Bundle multiple steps into one action
Concurrency
concurrency: group: ${{ github.ref }}
Cancel or queue duplicate runs
Environment secrets
${{ secrets.API_KEY }}
Scoped to repo, org, or environment
OIDC authentication
permissions: id-token: write
Short-lived tokens for cloud providers
Step outputs
echo "key=value" >> "$GITHUB_OUTPUT"
Pass data between steps and jobs
Service containers
services: postgres: image: postgres:16
Sidecar containers for integration tests
Timeout
timeout-minutes: 30
Fail fast on hung jobs or steps
Attestations
actions/attest-build-provenance@v3
SLSA build provenance for supply chain
模式语法 / 动作核心要点
推送触发器
on: push: branches: [main]
按分支、路径或标签筛选
PR触发器
on: pull_request: types: [opened, synchronize]
默认触发条件为开启、同步、重新开启
定时触发器
on: schedule: - cron: '0 6 * * 1'
仅支持UTC时区,最小间隔为5分钟
手动触发器
on: workflow_dispatch: inputs:
为手动运行定义类型化输入
任务依赖
needs: [build, test]
按顺序或并行运行任务
条件任务
if: github.ref == 'refs/heads/main'
基于表达式的任务/步骤筛选
矩阵策略
strategy: matrix: node: [18, 20, 22]
为每个组合生成任务
依赖缓存
actions/cache@v4
基于哈希的缓存键,支持restore-keys回退
带缓存的环境配置
actions/setup-node@v4
with
cache: 'pnpm'
包管理器内置缓存支持
上传制品
actions/upload-artifact@v4
在任务间共享数据或保存输出
下载制品
actions/download-artifact@v4
从之前的任务中获取制品
可复用工作流
uses: ./.github/workflows/reusable.yml
通过
workflow_call
触发器调用
复合动作
action.yml
with
using: composite
将多个步骤打包为单个动作
并发控制
concurrency: group: ${{ github.ref }}
取消或排队重复运行
环境密钥
${{ secrets.API_KEY }}
作用域覆盖仓库、组织或环境
OIDC认证
permissions: id-token: write
用于云服务商的短期令牌
步骤输出
echo "key=value" >> "$GITHUB_OUTPUT"
在步骤和任务间传递数据
服务容器
services: postgres: image: postgres:16
用于集成测试的边车容器
超时设置
timeout-minutes: 30
针对挂起的任务或步骤快速失败
构建证明
actions/attest-build-provenance@v3
用于供应链的SLSA构建证明

Expressions and Contexts

表达式与上下文

ContextExampleDescription
github
github.ref_name
,
github.sha
Event metadata, repo info, actor
env
env.NODE_ENV
Environment variables at current scope
secrets
secrets.API_KEY
Encrypted secrets (masked in logs)
inputs
inputs.environment
Workflow dispatch or reusable inputs
matrix
matrix.node
Current matrix combination values
steps
steps.build.outputs.version
Outputs from previous steps
needs
needs.prepare.outputs.tag
Outputs from dependent jobs
runner
runner.os
,
runner.arch
Runner environment info
vars
vars.DEPLOY_URL
Repository or org configuration variables
上下文示例说明
github
github.ref_name
,
github.sha
事件元数据、仓库信息、执行者
env
env.NODE_ENV
当前作用域下的环境变量
secrets
secrets.API_KEY
加密密钥(在日志中会被掩码处理)
inputs
inputs.environment
工作流触发或可复用工作流的输入参数
matrix
matrix.node
当前矩阵组合的值
steps
steps.build.outputs.version
之前步骤的输出
needs
needs.prepare.outputs.tag
依赖任务的输出
runner
runner.os
,
runner.arch
运行器环境信息
vars
vars.DEPLOY_URL
仓库或组织的配置变量

Common Mistakes

常见错误

MistakeCorrect Pattern
Using
actions/checkout@v4
or older tags
Pin to current major version (
@v6
) or commit SHA
Missing
persist-credentials: false
Set on checkout when using custom tokens or OIDC
Broad
permissions
at workflow level
Set
permissions: {}
at workflow level, grant per-job
Cache key without dependency file hashInclude
hashFiles('**/pnpm-lock.yaml')
in cache key
Secrets in
if:
conditions
Secrets cannot be used in
if:
expressions directly
Using
pull_request_target
carelessly
Never run PR code with write permissions from
pull_request_target
Not cancelling stale runsUse
concurrency
with
cancel-in-progress: true
Storing structured data as a single secretCreate individual secrets per value for proper log redaction
Referencing action tags without SHA pinningPin third-party actions to full commit SHA for supply chain safety
Hardcoding runner OS in scriptsUse
runner.os
context for cross-platform compatibility
Using
actions/cache
without
restore-keys
Always provide restore-keys for partial cache matches
Interpolating user input in
run:
blocks
Pass untrusted values through
env:
to prevent script injection
No
timeout-minutes
on jobs
Set explicit timeouts to fail fast on hung processes
Using
always()
without scoping
Combine with status checks:
if: always() && steps.x.outcome == 'success'
错误做法正确方式
使用
actions/checkout@v4
或更旧的标签
固定到当前主版本(
@v6
)或提交SHA
缺少
persist-credentials: false
当使用自定义令牌或OIDC时,在checkout步骤中设置该参数
在工作流级别设置宽泛的
permissions
在工作流级别设置
permissions: {}
,然后按任务授予权限
缓存密钥中不包含依赖文件哈希在缓存密钥中包含
hashFiles('**/pnpm-lock.yaml')
if:
条件中使用密钥
密钥不能直接在
if:
表达式中使用
随意使用
pull_request_target
永远不要使用
pull_request_target
的写入权限运行PR代码
未取消过时的运行使用
concurrency
并设置
cancel-in-progress: true
将结构化数据存储为单个密钥为每个值创建单独的密钥,以确保日志正确脱敏
引用动作标签但未固定SHA为供应链安全,将第三方动作固定到完整的提交SHA
在脚本中硬编码运行器OS使用
runner.os
上下文实现跨平台兼容
使用
actions/cache
但未设置
restore-keys
始终提供restore-keys以支持部分缓存匹配
run:
块中直接插入用户输入
通过
env:
传递不可信值以防止脚本注入
未为任务设置
timeout-minutes
设置明确的超时时间,以便挂起的进程快速失败
未限定范围使用
always()
结合状态检查使用:
if: always() && steps.x.outcome == 'success'

Delegation

任务委托

  • Workflow debugging: Use
    Explore
    agent to inspect workflow run logs
  • Security auditing: Use
    Task
    agent to review permissions and secret usage
  • Code review: Delegate to
    code-reviewer
    agent for workflow PR reviews
  • 工作流调试:使用
    Explore
    工具查看工作流运行日志
  • 安全审计:使用
    Task
    工具审查权限和密钥使用情况
  • 代码审查:将工作流PR审查任务委托给
    code-reviewer
    工具

References

参考资料

  • Workflow syntax, triggers, jobs, steps, and concurrency
  • Caching strategies and artifact management
  • Matrix strategies, reusable workflows, and composite actions
  • Security, secrets, OIDC, and permissions hardening
  • 工作流语法、触发器、任务、步骤及并发控制
  • 缓存策略与制品管理
  • 矩阵策略、可复用工作流与复合动作
  • 安全、密钥、OIDC及权限加固