深色模式
GitHub Actions 入门:写 workflow
摘要:GitHub Actions 的配置文件放在仓库
.github/workflows/下,一个文件一条流水线。本文从触发条件讲到 job 依赖、矩阵构建、密钥注入与环境门禁。
适用环境
- 一个 GitHub 仓库
- 仓库 Settings 中 Actions 已启用(默认开启)
- 项目有可执行的构建/测试命令
操作步骤
1. 创建第一个 workflow
bash
mkdir -p .github/workflows
cat > .github/workflows/ci.yml <<'EOF'
name: CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Show files
run: ls -la
EOF
git add .github/workflows/ci.yml && git commit -m "add ci" && git push1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
推送后到仓库 Actions 标签页查看运行记录。
2. job 依赖与矩阵构建
yaml
jobs:
test:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python-version }}
- run: python -m pytest
build:
needs: test # test 成功后才运行
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: make build1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
3. 缓存、密钥与环境门禁
yaml
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
deploy:
needs: build
runs-on: ubuntu-latest
environment: production # Settings → Environments 配审批人
steps:
- env:
DEPLOY_TOKEN: ${{ secrets.DEPLOY_TOKEN }}
run: ./deploy.sh1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
Secret 在 Settings → Secrets and variables → Actions 中添加,日志中自动打码。
4. 上传制品
yaml
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
retention-days: 71
2
3
4
5
2
3
4
5
危险
在 pull_request_target 触发的 workflow 中检出并执行 PR 代码,等于让外部贡献者在你仓库跑任意代码。
验证
bash
python -c "import yaml; yaml.safe_load(open('.github/workflows/ci.yml')); print('yaml ok')"1
- [ ] push 后 Actions 页面出现运行记录
- [ ]
needs生效:test 失败时 build 不执行 - [ ]
environment: production的 job 会等待审批
常见坑
action 版本没固定到 commit SHA
@v4 这类浮动标签上游可被改写。安全要求高的场景应固定完整 commit SHA。
secrets 在 fork PR 中不可用
外部贡献者的 PR 默认拿不到 secrets,job 会拿到空值。
run 多行写法的默认行为
默认 shell 是 bash -e,中间某行失败即停止。必要时显式指定 shell: bash {0}。