推荐采用三段式CI/CD模板(build→test→deploy),集成缓存、并行测试、OIDC安全认证及多环境部署策略,确保可复用、易维护且生产可用。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

你需要快速搭建一个可复用、易维护的CI/CD流水线脚本,避免每次新建项目都从零写YAML、重复处理权限、缓存、镜像构建和部署逻辑。
选择基础模板结构
从最轻量但生产可用的三段式结构开始:build → test → deploy。这种结构覆盖90%的Web服务场景,且便于后续按需拆分阶段。
直接复制以下骨架,不要跳过注释行——它们标记了后续必须替换的关键占位符:
```yaml
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顶部添加角色声明:
```yaml
permissions:
id-token: write
contents: read
```
然后用官方Action如 aws-actions/configure-aws-credentials@v4 直接获取临时凭证——这比长期AK/SK更安全,【无需手动轮换密钥】。
加速构建:启用缓存与并行测试
第一步:在build job中加入依赖缓存
在 npm ci 步骤前插入缓存块:
```yaml
- 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并打标;否则跳过此步。
适配多环境部署策略
方法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字段下新增:
```yaml
workflow_dispatch:
inputs:
environment:
description: 'Target environment'
required: true
default: 'staging'
type: choice
options:
- staging
- prod
```
然后在deploy job中用 ${{ github.event.inputs.environment }} 动态决定执行哪套部署脚本。


















