.github/workflows/*.yml 随仓库版本管理迁移前:Jenkins + 自建服务器,维护成本高,构建不稳定。
迁移后:所有流程自动化,PR 自动跑测试,主干自动部署。
现象:pull_request 事件中,从 fork 仓库提交的 PR 无法访问 secrets。
原因:GitHub 出于安全考虑,fork PR 默认不传递 secrets。
解决:使用 pull_request_target 事件(注意安全风险,需谨慎)。
on:
pull_request_target:
branches: [main]
错误做法:每次跑 npm ci 都不缓存。
正确做法:使用 actions/cache 缓存 node_modules。
- name: Cache node_modules
uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
需求:需要在 Node 18、20、22 上分别测试,但每次 push 都跑 3 次,浪费时间。
解决:使用矩阵,但限定只在 push 到 main 或 schedule 时跑多版本,PR 只跑最新版。
strategy:
matrix:
node-version: [18.x, 20.x, 22.x]
# 只在 main 分支跑全部
exclude:
- node-version: 18.x
if: github.ref != 'refs/heads/main'
现象:自定义 action 里读取不到 env 上下文。
解决:通过 with 参数显式传递,或使用 ${{ env.MY_VAR }} 语法。
问题:多个项目共用同一个 workflow,出错时难以定位。
解决:使用可复用 workflow (workflow_call),并增加 workflow_dispatch 手动触发调试。
on:
workflow_call:
inputs:
environment:
required: true
type: string
secrets:
DEPLOY_KEY:
required: true
name: CI/CD
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x, 20.x]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm ci
- run: npm test
deploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Deploy to Vercel
uses: amondnet/vercel-action@v20
with:
vercel-token: ${{ secrets.VERCEL_TOKEN }}
vercel-org-id: ${{ secrets.VERCEL_ORG_ID }}
vercel-project-id: ${{ secrets.VERCEL_PROJECT_ID }}
vercel-args: '--prod'
| 用途 | Action |
|---|---|
| 缓存依赖 | actions/cache@v4 |
| 设置 Node | actions/setup-node@v4 |
| 设置 Python | actions/setup-python@v5 |
| 上传 artifact | actions/upload-artifact@v4 |
| 下载 artifact | actions/download-artifact@v4 |
| 发送 Slack 通知 | slackapi/slack-github-action@v1 |
| 部署到云服务器 | easingthemes/ssh-deploy@main |
建议收藏本文,下次新项目搭建 CI 时直接抄配置。下一篇写 “GitHub Actions 安全最佳实践”。