从本地到生产:迁移到 GitHub Actions 自动化 CI/CD,总结了这 5 个坑
一、为什么迁移到 GitHub Actions?
- 无需额外服务器:GitHub 原生集成,免费额度充足(2000 分钟/月)
- 矩阵构建:一次 push 测试多个 Node 版本、多个操作系统
- 生态丰富:官方 marketplace 有上万 actions
- 配置即代码:
.github/workflows/*.yml随仓库版本管理
迁移前:Jenkins + 自建服务器,维护成本高,构建不稳定。
迁移后:所有流程自动化,PR 自动跑测试,主干自动部署。
二、5 个踩过的坑与解决方案
坑 1:权限不足导致 actions 无法触发
现象:pull_request事件中,从 fork 仓库提交的 PR 无法访问 secrets。
原因:GitHub 出于安全考虑,fork PR 默认不传递 secrets。
解决:使用pull_request_target事件(注意安全风险,需谨慎)。
on:pull_request_target:branches:[main]坑 2:缓存失效,每次依赖安装 3 分钟
错误做法:每次跑npm ci都不缓存。
正确做法:使用actions/cache缓存node_modules。
-name:Cache node_modulesuses:actions/cache@v4with:path:~/.npmkey:${{runner.os}}-node-${{hashFiles('package-lock.json')}}restore-keys:|${{ runner.os }}-node-坑 3:矩阵策略导致重复构建
需求:需要在 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.xif:github.ref!='refs/heads/main'坑 4:环境变量在 composite action 中不生效
现象:自定义 action 里读取不到env上下文。
解决:通过with参数显式传递,或使用${{ env.MY_VAR }}语法。
坑 5:workflow 复用导致调试困难
问题:多个项目共用同一个 workflow,出错时难以定位。
解决:使用可复用 workflow (workflow_call),并增加workflow_dispatch手动触发调试。
on:workflow_call:inputs:environment:required:truetype:stringsecrets:DEPLOY_KEY:required:true三、完整 workflow 模板(可直接复制)
示例:Node.js 项目 CI + 自动部署到 Vercel
name:CI/CDon:push:branches:[main,develop]pull_request:branches:[main]jobs:test:runs-on:ubuntu-lateststrategy:matrix:node-version:[18.x,20.x]steps:-uses:actions/checkout@v4-uses:actions/setup-node@v4with:node-version:${{matrix.node-version}}cache:'npm'-run:npm ci-run:npm testdeploy:needs:testif:github.ref == 'refs/heads/main'runs-on:ubuntu-lateststeps:-uses:actions/checkout@v4-name:Deploy to Verceluses:amondnet/vercel-action@v20with:vercel-token:${{secrets.VERCEL_TOKEN}}vercel-org-id:${{secrets.VERCEL_ORG_ID}}vercel-project-id:${{secrets.VERCEL_PROJECT_ID}}vercel-args:'--prod'四、常用 actions 清单
| 用途 | 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 |
五、总结
- GitHub Actions 完全取代 Jenkins 等传统 CI,配置即代码,免费额度足够中小项目。
- 重点注意:缓存策略、权限处理、矩阵优化、workflow 复用。
- 文中的所有 workflow 代码均可直接复制使用,根据项目调整即可。
建议收藏本文,下次新项目搭建 CI 时直接抄配置。下一篇写“GitHub Actions 安全最佳实践”。