从零到成熟模块详解

CI/CD 流水线 · 第 8 / 11 章

8一份完整的生产级流水线

name: release

on:
  push:
    branches: [main]
    paths-ignore:            # 文档改动不触发完整流程
      - '**.md'
      - 'docs/**'
  workflow_dispatch:
    inputs:
      image_tag:
        description: '要部署的镜像 tag(留空则部署最新构建)'
        required: false

# 同一时间只允许一个发布,新的排队不取消(发布的取消很危险)
concurrency:
  group: release-${{ github.ref }}
  cancel-in-progress: false

env:
  REGISTRY: registry.example.com
  IMAGE: registry.example.com/sre/orders-api
  SERVICE: orders-api

permissions:
  contents: read
  id-token: write            # OIDC
  packages: write

jobs:
  # ---------------- ① 静态检查 ----------------
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: '1.22', cache: true }
      - run: go vet ./...
      - run: golangci-lint run --timeout 5m ./...
      - name: 检查是否有密钥被提交
        uses: gitleaks/gitleaks-action@v2

  # ---------------- ② 测试 ----------------
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
        ports: ['5432:5432']
        options: >-
          --health-cmd pg_isready --health-interval 5s
          --health-timeout 3s --health-retries 10
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with: { go-version: '1.22', cache: true }
      - run: go test -race -coverprofile=cover.out ./...
      - run: go tool cover -func=cover.out | tail -1
      - uses: actions/upload-artifact@v4
        if: always()
        with: { name: coverage, path: cover.out }

  # ---------------- ③ 构建镜像 ----------------
  build:
    needs: [lint, test]
    runs-on: ubuntu-latest
    outputs:
      digest: ${{ steps.push.outputs.digest }}
      tag: ${{ steps.meta.outputs.tag }}
    steps:
      - uses: actions/checkout@v4

      - name: 计算镜像标签
        id: meta
        run: |
          TAG="$(date -u +%Y%m%d-%H%M)-${GITHUB_SHA::7}"
          echo "tag=$TAG" >> "$GITHUB_OUTPUT"
          echo "构建版本:$TAG"

      - uses: docker/setup-buildx-action@v3
      - uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: 构建并推送
        id: push
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ env.IMAGE }}:${{ steps.meta.outputs.tag }}
          build-args: |
            VERSION=${{ steps.meta.outputs.tag }}
            COMMIT=${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          provenance: true          # 生成构建来源证明(供应链安全)
          sbom: true                # 生成 SBOM

  # ---------------- ④ 扫描 ----------------
  scan:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - name: 镜像漏洞扫描
        run: |
          curl -sfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh \
            | sh -s -- -b /usr/local/bin
          trivy image --exit-code 1 --severity CRITICAL --ignore-unfixed \
            ${{ env.IMAGE }}@${{ needs.build.outputs.digest }}

  # ---------------- ⑤ 部署 staging ----------------
  deploy-staging:
    needs: [build, scan]
    runs-on: ubuntu-latest
    environment:
      name: staging
      url: https://staging.example.com
    steps:
      - uses: actions/checkout@v4
      - name: 部署到 staging
        run: |
          ./scripts/deploy.sh \
            --env staging \
            --image "${{ env.IMAGE }}@${{ needs.build.outputs.digest }}"
      - name: 冒烟测试
        run: ./scripts/smoke-test.sh https://staging.example.com

  # ---------------- ⑥ 部署生产(需审批)----------------
  deploy-prod:
    needs: deploy-staging
    runs-on: ubuntu-latest
    environment:
      name: production          # ← 这个 environment 上配置了 Required reviewers
      url: https://api.example.com
    steps:
      - uses: actions/checkout@v4

      - name: 发布前记录
        run: |
          echo "发布人:${{ github.actor }}"
          echo "制品:${{ env.IMAGE }}@${{ needs.build.outputs.digest }}"
          echo "提交:${{ github.sha }}"

      - name: 灰度发布 5%
        id: canary
        run: |
          ./scripts/deploy.sh --env prod --weight 5 \
            --image "${{ env.IMAGE }}@${{ needs.build.outputs.digest }}"

      - name: 观察 5 分钟
        run: ./scripts/check-metrics.sh --window 5m --error-rate-max 0.01 --p99-max 500ms

      - name: 全量发布
        run: |
          ./scripts/deploy.sh --env prod --weight 100 \
            --image "${{ env.IMAGE }}@${{ needs.build.outputs.digest }}"

      - name: 发布后验证
        run: ./scripts/smoke-test.sh https://api.example.com

      - name: 失败则回滚
        if: failure()
        run: ./scripts/deploy.sh --env prod --rollback

      - name: 记录发布
        if: always()
        run: |
          ./scripts/record-release.sh \
            --service "${{ env.SERVICE }}" \
            --digest "${{ needs.build.outputs.digest }}" \
            --commit "${{ github.sha }}" \
            --status "${{ job.status }}" \
            --pipeline "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
这份配置里六个值得学的设计
  1. concurrency 且 cancel-in-progress: false:发布的取消比排队危险得多, 半完成的状态最难处理。
  2. paths-ignore:文档改动不跑完整流程,省下大量等待。
  3. build.outputs.digest:后续所有环节都用同一个 digest, 保证「验证的制品」和「部署的制品」严格相同。
  4. environment: production:审批、密钥、OIDC 信任策略三者绑定在一起, 审批记录自动留痕。
  5. 灰度 + 观察 + 回滚写在流水线里,而不是写在一份文档里等人执行。
  6. record-release.sh 用 if: always():无论成功失败都记录, 失败记录同样重要(用于统计变更失败率)。

CI/CD 流水线 · 第 8 章 一份完整的生产级流水线
模块目录 · 返回学习路径