推荐采用三段式CI/CD模板(build → test → deploy),并结合缓存加速、并行测试、OIDC安全认证以及多环境部署策略,确保流水线具备可复用性与易维护性,并在生产环境中稳定运行。

在团队协作中,每次新建项目都从零编写YAML、反复处理权限配置、缓存机制、镜像构建和部署逻辑,无疑是许多开发者的现实痛点。下面直接提供一套经过验证的实践方案,帮助你快速搭建可复用且易于维护的CI/CD流水线。
选用基础模板结构奠定流水线基石
从最轻量但具备生产可用性的三段式结构开始:build → test → deploy。该结构覆盖了90%的Web服务场景,后续如需拆分阶段,也能灵活调整。
直接复制以下骨架代码,请勿跳过注释行——它们标注了后续必须替换的关键占位符:
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm run build
- uses: actions/upload-artifact@v4
with:
name: dist
path: dist/
test:
needs: build
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
- run: npm test
deploy:
needs: [build, test]
if: github.event_name == 'push' && github.head_ref == 'main'
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: dist
path: ./dist
- name: Deploy to staging
run: echo "Deploy logic goes here"
注入环境与密钥安全机制
所有敏感字段必须通过GitHub Secrets注入,严禁硬编码或直接提交到仓库。这是安全底线。
方法一:在deploy步骤中引用预设密钥
把 echo "Deploy logic goes here" 替换为真实部署命令,并用 ${{ secrets.STAGING_SSH_KEY }} 注入私钥。注意:SSH密钥需先Base64编码后存入Secrets,解码命令为 echo "${{ secrets.STAGING_SSH_KEY }}" | base64 -d > /tmp/id_rsa。
方法二:使用OIDC访问云服务(推荐用于AWS/Azure/GCP)
在deploy job顶部添加角色声明:
permissions:
id-token: write
contents: read
然后采用最新Action如 aws-actions/configure-aws-credentials@v4 直接获取临时凭证——这比长期AK/SK更安全,无需手动轮换密钥。
加速构建:启用缓存与并行测试
第一步:在build job中加入依赖缓存
在 npm ci 步骤前插入缓存块:
- uses: actions/cache@v4
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
第二步:将test job拆分为单元测试与E2E测试两个并行子任务
- 复制整个test job,重命名为test-unit,把
npm test改为npm run test:unit; - 新增test-e2e job,设置
needs: build,运行npm run test:e2e; - 在deploy的
needs字段里改为[build, test-unit, test-e2e];
这样一来,单元测试失败时E2E不会启动,节省资源;两者都通过才进入部署环节。
第三步:给E2E测试单独分配更高配置的runner
在test-e2e job中把 runs-on: ubuntu-22.04 换成 runs-on: ubuntu-22.04-self-hosted——前提是已部署自建runner并打标。如果尚未搭建自建runner,可先跳过此步。
适配多环境部署策略
方法1:用触发事件区分环境
把deploy job复制两份,分别改名为deploy-staging和deploy-prod;
- deploy-staging的if条件设为:
github.event_name == 'pull_request'; - deploy-prod的if条件设为:
github.event_name == 'push' && github.ref == 'refs/heads/main';
方法2:用workflow_dispatch手动触发指定环境
在on字段下新增:
workflow_dispatch:
inputs:
environment:
description: 'Target environment'
required: true
default: 'staging'
type: choice
options:
- staging
- prod
然后在deploy job中用 ${{ github.event.inputs.environment }} 动态决定执行哪套部署脚本。该方式适合需要手动干预的场景,例如灰度发布前的确认步骤。
