
GitHub Actions 高级工作流:矩阵策略、自定义操作、缓存优化与 OIDC 认证
GitHub Actions 已远远超越简单的 CI 流水线。到 2026 年,团队使用它来编排复杂的多平台构建、无需长期凭证即可部署到云提供商,并将可复用逻辑打包到自定义操作中。本指南深入探讨四个高级主题,这些主题将初学者工作流与生产级自动化区分开来。
矩阵策略:跨维度测试
matrix 策略允许您使用单个 YAML 块针对多个变量组合运行作业。

基本矩阵
jobs:
test:
strategy:
matrix:
os: [ubuntu-22.04, windows-2022, macos-14]
node: [18, 20, 22]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}
- run: npm ci && npm test
这会自动生成 9 个并行作业(3 个操作系统 × 3 个 Node 版本)。
包含与排除组合
strategy:
matrix:
os: [ubuntu-22.04, windows-2022]
node: [18, 20, 22]
include:
- os: ubuntu-22.04
node: 22
experimental: true
exclude:
- os: windows-2022
node: 18
快速失败与最大并行
strategy:
fail-fast: false
max-parallel: 4
matrix:
shard: [1, 2, 3, 4, 5, 6, 7, 8]
将大型测试套件拆分为分片可显著减少总挂钟时间。
从 JSON 动态生成矩阵
jobs:
generate-matrix:
runs-on: ubuntu-22.04
outputs:
matrix: ${{ steps.set.outputs.matrix }}
steps:
- id: set
run: |
echo 'matrix={"pkg":["api","web","worker"]}' >> $GITHUB_OUTPUT
build:
needs: generate-matrix
strategy:
matrix: ${{ fromJson(needs.generate-matrix.outputs.matrix) }}
runs-on: ubuntu-22.04
steps:
- run: echo "Building ${{ matrix.pkg }}"
自定义操作:复合、JavaScript 和 Docker
复合操作
# .github/actions/setup-project/action.yml
name: 'Setup Project'
description: 'Install deps and restore build cache'
inputs:
node-version:
description: 'Node.js version'
default: '20'
outputs:
cache-hit:
description: 'Whether the cache was restored'
value: ${{ steps.cache.outputs.cache-hit }}
runs:
using: composite
steps:
- uses: actions/setup-node@v4
with:
node-version: ${{ inputs.node-version }}
- id: cache
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- if: steps.cache.outputs.cache-hit != 'true'
run: npm ci
shell: bash

JavaScript 操作
// index.js
const core = require('@actions/core');
const github = require('@actions/github');
async function run() {
try {
const token = core.getInput('github-token', { required: true });
const label = core.getInput('label', { required: true });
const octokit = github.getOctokit(token);
const { context } = github;
if (context.eventName !== 'pull_request') {
core.warning('This action only works on pull_request events');
return;
}
await octokit.rest.issues.addLabels({
...context.repo,
issue_number: context.payload.pull_request.number,
labels: [label],
});
core.setOutput('labeled', 'true');
} catch (err) {
core.setFailed(err.message);
}
}
run();
# action.yml for JS action
name: 'Auto Label PR'
runs:
using: node20
main: index.js
inputs:
github-token:
required: true
label:
required: true
Docker 操作
# Dockerfile
FROM python:3.12-slim
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
#!/bin/bash
set -e
INPUT_THRESHOLD="${INPUT_THRESHOLD:-80}"
echo "coverage-pct=${INPUT_THRESHOLD}" >> $GITHUB_OUTPUT
缓存优化
actions/cache 基础
- uses: actions/cache@v4
id: cache
with:
path: |
~/.npm
node_modules
key: ${{ runner.os }}-npm-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-npm-
语言特定缓存
Go 模块:
- uses: actions/cache@v4
with:
path: |
~/go/pkg/mod
~/.cache/go-build
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
Python pip:
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
Rust cargo:
- uses: actions/cache@v4
with:
path: |
~/.cargo/registry
~/.cargo/git
target/
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}
使用 Buildx 进行 Docker 层缓存
- uses: docker/setup-buildx-action@v3
- uses: docker/build-push-action@v6
with:
context: .
push: true
tags: registry.example.com/app:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
OIDC 认证:无密钥云访问
作为密钥存储的长期服务账户凭证是安全风险。OIDC 让您的工作流无需存储任何密钥即可从云提供商请求短期令牌。
AWS OIDC 设置
aws iam create-open-id-connect-provider \
--url https://token.actions.githubusercontent.com \
--client-id-list sts.amazonaws.com \
--thumbprint-list 6938fd4d98bab03faadb97b34396831e3780aea1
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com"
},
"StringLike": {
"token.actions.githubusercontent.com:sub": "repo:my-org/my-repo:*"
}
}
}]
}
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-22.04
steps:
- uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-deploy
aws-region: us-east-1
- run: aws s3 sync dist/ s3://my-bucket/
GCP 工作负载身份联合
permissions:
id-token: write
contents: read
jobs:
deploy:
runs-on: ubuntu-22.04
steps:
- uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/123/locations/global/workloadIdentityPools/github/providers/github
service_account: deploy@my-project.iam.gserviceaccount.com
- uses: google-github-actions/deploy-cloudrun@v2
with:
service: my-service
region: us-central1
image: gcr.io/my-project/app:${{ github.sha }}
可复用工作流
# .github/workflows/reusable-test.yml
on:
workflow_call:
inputs:
environment:
required: true
type: string
secrets:
npm-token:
required: true
jobs:
test:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- run: npm ci
env:
NPM_TOKEN: ${{ secrets.npm-token }}
- run: npm test
jobs:
run-tests:
uses: ./.github/workflows/reusable-test.yml
with:
environment: staging
secrets:
npm-token: ${{ secrets.NPM_TOKEN }}
并发控制
concurrency:
group: deploy-${{ github.ref }}
cancel-in-progress: true
结论
高级 GitHub Actions 用法将 CI/CD 从简单的测试和部署脚本转变为复杂的自动化平台。矩阵策略消除了冗余的工作流定义。自定义操作促进了跨仓库的复用。积极缓存可将构建时间减少 50-80%。OIDC 消除了长期凭证的安全风险。这些技术共同让小型团队能够以更大组织的规模和安全性水平运作。