聊天讨论 从本地到生产:迁移到 GitHub Actions 自动化 CI/CD,总结了这 5 个坑

193577746(kyriewen) · June 15, 2026 · 12 hits

一、为什么迁移到 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_modules
  uses: actions/cache@v4
  with:
    path: ~/.npm
    key: ${{ 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.x
        if: 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: true
        type: string
    secrets:
      DEPLOY_KEY:
        required: true

三、完整 workflow 模板(可直接复制)

示例:Node.js 项目 CI + 自动部署到 Vercel

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'

四、常用 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 安全最佳实践”。

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.