搭建 CI/CD 流水线

适用场景

从代码提交到构建、测试、安全扫描、制品发布和部署的自动化。以 GitHub Actions 为例,思路适用于 GitLab CI 等。

前置条件

步骤

  1. 定义流水线阶段:
lint → test → build → scan → package → deploy-staging → approve → deploy-prod
  1. 编写 workflow:
name: ci-cd
on:
  push:
    branches: [main]
  pull_request:
permissions:
  contents: read
  packages: write
concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: true
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci
      - run: npm test
  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: docker build -t app:${{ github.sha }} .
      - run: docker push registry.example.com/app:${{ github.sha }}
  1. 加入安全扫描:
- uses: aquasecurity/trivy-action@...
  with:
    image-ref: registry.example.com/app:${{ github.sha }}
    exit-code: '1'
  1. 部署到 staging,跑冒烟测试。

  2. 生产部署加 environment 审批和 OIDC 凭据。

  3. 配置回滚:保留上一个镜像 tag,部署失败自动回滚。

验证

回滚

常见坑

相关命令

读完自测

合上页面,先回答,再展开对照。

  1. 为什么不能用 pull_request_target 执行 fork PR 的不可信代码?
  2. 镜像扫描失败要阻断发布,配置上靠什么实现?
  3. 回滚方案应包含哪些内容?
答案
  1. 会造成 Secrets 泄露和 fork PR 安全问题,不可信代码不应在 pull_request_target 下执行。
  2. 在扫描步骤设置 exit-code: '1',扫描失败即可阻断发布。
  3. 重新部署上一个已知良好的镜像 tag,数据库变更准备向下兼容/回滚脚本,并保留构建日志和制品。