Skip to content
Santekno.com | Level Up Your Engineering Skills
ID
📖 0%
26 Nov 2026 · 22 mnt baca ·Artikel 97 / 208
Go

Golang CI/CD Pipeline: GitHub Actions, AI Quality Gates, Auto Deploy

CI/CD pipeline lengkap untuk Santekno Shop. GitHub Actions dengan AI-assisted code review, specify audit gate, golangci-lint, integration tests, automated deployment ke staging.

IH
Ihsan Arif
Penulis di Santekno · Backend Engineer

CI/CD pipeline Golang untuk Santekno Shop bukan sekadar “run tests, deploy”. Di sini kita integrasikan spec audit, AI-assisted code review, architecture validation, dan automated deployment — semua dalam satu workflow GitHub Actions yang fully auditable dan menjaga implementasi tetap selaras dengan spec.


17.01 Pipeline Overview: 5 Stage

Sebelum masuk ke YAML, penting memahami peta besarnya: pipeline dibagi lima stage dengan target waktu masing-masing. Ringkasan berikut menunjukkan urutan dan isi tiap stage.

text
 1Stage 1: VALIDATE (fast, < 3 menit)
 2  ├── go build ./...
 3  ├── golangci-lint run
 4  ├── go vet ./...
 5  └── Architecture guard (depguard)
 6
 7Stage 2: TEST (medium, 5-8 menit)
 8  ├── Unit tests + coverage gate (≥ 80%)
 9  ├── Integration tests (PostgreSQL + Redis)
10  └── Race condition detection
11
12Stage 3: AI QUALITY GATES (2-3 menit)
13  ├── Specify audit → score ≥ 80
14  ├── Security scan (gosec)
15  └── Dependency vulnerability check
16
17Stage 4: BUILD (3-5 menit)
18  ├── Docker multi-stage build
19  ├── Image tagging (sha + semver)
20  └── Push to container registry
21
22Stage 5: DEPLOY (5-10 menit, main branch only)
23  ├── Database migration
24  ├── Rolling update ke staging
25  ├── Smoke test (health check)
26  └── Slack notification

Urutan ini disengaja mahal-di-belakang: stage cepat (validate) memberi feedback dalam hitungan menit, sementara stage lambat (deploy) hanya dijalankan setelah semua gate lolos.


17.02 Main Workflow File

Sekarang kita terjemahkan lima stage tadi menjadi satu file workflow GitHub Actions. File berikut mendefinisikan seluruh pipeline dari validate hingga deploy staging.

yaml
  1# .github/workflows/main.yml
  2
  3name: Santekno Shop CI/CD
  4
  5on:
  6  push:
  7    branches: [main, develop]
  8  pull_request:
  9    branches: [main, develop]
 10
 11env:
 12  GO_VERSION: '1.22'
 13  REGISTRY: ghcr.io
 14  IMAGE_NAME: ${{ github.repository }}/santekno-shop
 15
 16concurrency:
 17  group: ${{ github.workflow }}-${{ github.ref }}
 18  cancel-in-progress: true  # Cancel stale runs on new push
 19
 20jobs:
 21  # ─── STAGE 1: VALIDATE ───────────────────────────────────────
 22  validate:
 23    name: "Validate"
 24    runs-on: ubuntu-latest
 25    steps:
 26      - uses: actions/checkout@v4
 27
 28      - uses: actions/setup-go@v5
 29        with:
 30          go-version: ${{ env.GO_VERSION }}
 31          cache: true
 32
 33      - name: Build
 34        run: go build ./...
 35
 36      - name: Vet
 37        run: go vet ./...
 38
 39      - name: Lint
 40        uses: golangci/golangci-lint-action@v6
 41        with:
 42          version: v1.59
 43          args: --timeout=5m
 44
 45      - name: Generate mocks (verify go:generate is in sync)
 46        run: |
 47          go generate ./...
 48          git diff --exit-code testutil/mock/ || \
 49            (echo "Mocks out of sync. Run 'go generate ./...' and commit." && exit 1)
 50
 51  # ─── STAGE 2: TEST ───────────────────────────────────────────
 52  unit-test:
 53    name: "Unit Test"
 54    needs: validate
 55    runs-on: ubuntu-latest
 56    steps:
 57      - uses: actions/checkout@v4
 58      - uses: actions/setup-go@v5
 59        with: { go-version: '${{ env.GO_VERSION }}', cache: true }
 60
 61      - name: Run unit tests
 62        run: |
 63          go test -race -count=1 -timeout=60s \
 64            -coverprofile=coverage.out -covermode=atomic \
 65            ./internal/domain/... ./internal/usecase/... ./pkg/...
 66
 67      - name: Coverage gate
 68        run: |
 69          COVERAGE=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')
 70          echo "Coverage: $COVERAGE%"
 71          if (( $(echo "$COVERAGE < 80" | bc -l) )); then
 72            echo "❌ Coverage $COVERAGE% < 80% threshold"
 73            exit 1
 74          fi
 75          echo "✅ Coverage $COVERAGE% passes"
 76
 77      - name: Upload coverage
 78        uses: actions/upload-artifact@v4
 79        with:
 80          name: coverage-report
 81          path: coverage.out
 82
 83  integration-test:
 84    name: "Integration Test"
 85    needs: validate
 86    runs-on: ubuntu-latest
 87    services:
 88      postgres:
 89        image: postgres:15-alpine
 90        env:
 91          POSTGRES_DB: santekno_test
 92          POSTGRES_USER: santekno
 93          POSTGRES_PASSWORD: secret
 94        ports: ["5432:5432"]
 95        options: >-
 96          --health-cmd pg_isready
 97          --health-interval 10s
 98          --health-timeout 5s
 99          --health-retries 5
100
101      redis:
102        image: redis:7-alpine
103        ports: ["6379:6379"]
104        options: >-
105          --health-cmd "redis-cli ping"
106          --health-interval 10s
107
108    steps:
109      - uses: actions/checkout@v4
110      - uses: actions/setup-go@v5
111        with: { go-version: '${{ env.GO_VERSION }}', cache: true }
112
113      - name: Install migrate CLI
114        run: |
115          curl -L https://github.com/golang-migrate/migrate/releases/download/v4.18.1/migrate.linux-amd64.tar.gz | tar xvz
116          sudo mv migrate /usr/local/bin/
117
118      - name: Run migrations on test DB
119        run: migrate -path migrations -database "$TEST_DATABASE_URL" up
120        env:
121          TEST_DATABASE_URL: postgres://santekno:secret@localhost:5432/santekno_test?sslmode=disable
122
123      - name: Run integration tests
124        run: |
125          go test -race -tags=integration -count=1 -timeout=120s \
126            ./internal/repository/... ./internal/infrastructure/...
127        env:
128          TEST_DATABASE_URL: postgres://santekno:secret@localhost:5432/santekno_test?sslmode=disable
129          TEST_REDIS_ADDR: localhost:6379
130
131  # ─── STAGE 3: AI QUALITY GATES ────────────────────────────────
132  ai-quality-gates:
133    name: "AI Quality Gates"
134    needs: [unit-test, integration-test]
135    runs-on: ubuntu-latest
136    steps:
137      - uses: actions/checkout@v4
138      - uses: actions/setup-go@v5
139        with: { go-version: '${{ env.GO_VERSION }}', cache: true }
140
141      - name: Install specify CLI
142        run: go install github.com/specifyapp/specify-cli@latest
143
144      - name: Spec audit gate
145        run: |
146          SCORE=$(specify audit --output json | jq '.score')
147          echo "Spec audit score: $SCORE"
148          if [ "$SCORE" -lt 80 ]; then
149            echo "❌ Spec audit score $SCORE < 80 threshold"
150            specify audit --output text
151            exit 1
152          fi
153          echo "✅ Spec audit score $SCORE passes"
154
155      - name: Security scan (gosec)
156        run: |
157          go install github.com/securego/gosec/v2/cmd/gosec@latest
158          gosec -exclude=G204,G304 ./... 2>&1 | tee gosec-report.txt
159          # G204: subprocess (intentional), G304: file path (intentional)
160
161      - name: Dependency vulnerability check
162        run: |
163          go install golang.org/x/vuln/cmd/govulncheck@latest
164          govulncheck ./...
165
166      - name: Architecture check (depguard)
167        run: golangci-lint run --enable=depguard --disable-all
168
169      - name: Upload security report
170        uses: actions/upload-artifact@v4
171        if: always()
172        with:
173          name: security-report
174          path: gosec-report.txt
175
176  # ─── STAGE 4: BUILD ───────────────────────────────────────────
177  build:
178    name: "Build & Push"
179    needs: ai-quality-gates
180    runs-on: ubuntu-latest
181    if: github.ref == 'refs/heads/main' || github.ref == 'refs/heads/develop'
182    outputs:
183      image-tag: ${{ steps.meta.outputs.tags }}
184      image-digest: ${{ steps.build.outputs.digest }}
185
186    steps:
187      - uses: actions/checkout@v4
188
189      - name: Set up Docker Buildx
190        uses: docker/setup-buildx-action@v3
191
192      - name: Login to Container Registry
193        uses: docker/login-action@v3
194        with:
195          registry: ${{ env.REGISTRY }}
196          username: ${{ github.actor }}
197          password: ${{ secrets.GITHUB_TOKEN }}
198
199      - name: Extract metadata
200        id: meta
201        uses: docker/metadata-action@v5
202        with:
203          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
204          tags: |
205            type=sha,prefix=sha-
206            type=semver,pattern={{version}}
207            type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }}
208
209      - name: Build and push image
210        id: build
211        uses: docker/build-push-action@v5
212        with:
213          context: .
214          push: true
215          tags: ${{ steps.meta.outputs.tags }}
216          labels: ${{ steps.meta.outputs.labels }}
217          cache-from: type=gha
218          cache-to: type=gha,mode=max
219          build-args: |
220            BUILD_VERSION=${{ github.sha }}
221            BUILD_TIME=${{ github.event.head_commit.timestamp }}
222
223  # ─── STAGE 5: DEPLOY ──────────────────────────────────────────
224  deploy-staging:
225    name: "Deploy → Staging"
226    needs: build
227    runs-on: ubuntu-latest
228    if: github.ref == 'refs/heads/develop'
229    environment:
230      name: staging
231      url: https://shop-staging.santekno.com
232
233    steps:
234      - uses: actions/checkout@v4
235
236      - name: Run DB migrations on staging
237        run: |
238          migrate -path migrations \
239            -database "$STAGING_DATABASE_URL" up
240        env:
241          STAGING_DATABASE_URL: ${{ secrets.STAGING_DATABASE_URL }}
242
243      - name: Deploy to staging (kubectl rolling update)
244        run: |
245          kubectl set image deployment/santekno-shop \
246            app=${{ needs.build.outputs.image-tag }} \
247            --record
248          kubectl rollout status deployment/santekno-shop --timeout=300s
249        env:
250          KUBECONFIG_DATA: ${{ secrets.STAGING_KUBECONFIG }}
251
252      - name: Smoke test
253        run: |
254          sleep 10
255          STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
256            https://shop-staging.santekno.com/health)
257          if [ "$STATUS" != "200" ]; then
258            echo "❌ Smoke test failed: HTTP $STATUS"
259            exit 1
260          fi
261          echo "✅ Smoke test passed"
262
263      - name: Notify Slack
264        if: always()
265        uses: slackapi/slack-github-action@v1
266        with:
267          payload: |
268            {
269              "text": "${{ job.status == 'success' && '✅' || '❌' }} Staging deploy: ${{ github.event.head_commit.message }}"
270            }
271        env:
272          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}

Perhatikan blok concurrency di atas: push baru otomatis membatalkan run lama pada ref yang sama, mencegah antrean menumpuk saat commit datang beruntun.


17.03 golangci-lint Configuration

Kualitas kode dijaga bukan oleh reviewer manual saja, tapi oleh linter yang menegakkan aturan arsitektur. Konfigurasi .golangci.yml berikut mengaktifkan linter penting plus depguard untuk memaksa batas antar-layer.

yaml
 1# .golangci.yml
 2
 3run:
 4  timeout: 5m
 5  go: '1.22'
 6
 7linters:
 8  enable:
 9    - errcheck          # cek error yang diabaikan
10    - govet             # go vet standard
11    - staticcheck       # static analysis
12    - gosimple          # simplify kode
13    - unused            # detect unused code
14    - gocyclo           # cyclomatic complexity
15    - depguard          # architecture layer enforcement
16    - gosec             # security linter
17    - misspell          # typo detection
18    - noctx             # context propagation check
19    - bodyclose         # HTTP response body close check
20
21linters-settings:
22  gocyclo:
23    min-complexity: 15
24
25  depguard:
26    rules:
27      # Handler tidak boleh import database packages
28      handler-no-db:
29        files:
30          - "**/delivery/http/handler/**"
31        deny:
32          - pkg: "github.com/jackc/pgx"
33            desc: "handlers must not import pgx directly"
34          - pkg: "github.com/redis/go-redis"
35            desc: "handlers must not import redis directly"
36
37      # Domain tidak boleh import framework
38      domain-pure:
39        files:
40          - "**/domain/**"
41        deny:
42          - pkg: "github.com/labstack/echo"
43            desc: "domain must not import echo"
44          - pkg: "github.com/jackc/pgx"
45            desc: "domain must not import pgx"
46          - pkg: "github.com/redis/go-redis"
47            desc: "domain must not import redis"
48
49      # UseCase tidak boleh import HTTP framework
50      usecase-no-http:
51        files:
52          - "**/usecase/**"
53        deny:
54          - pkg: "github.com/labstack/echo"
55            desc: "usecases must not import echo"
56          - pkg: "github.com/jackc/pgx"
57            desc: "usecases must not import pgx"
58
59issues:
60  exclude-rules:
61    - path: "_test.go"
62      linters: [gosec, errcheck]  # relax in test files

Dengan aturan depguard ini, pelanggaran Clean Architecture — misalnya handler yang mengimpor pgx langsung — tertangkap sebagai lint error di CI, bukan baru ketahuan saat kode sudah jalan di production.


17.04 Pre-commit Hooks

Feedback tercepat adalah sebelum kode di-commit. Konfigurasi pre-commit berikut menjalankan build, unit test, lint, dan quick spec check di mesin developer.

yaml
 1# .pre-commit-config.yaml
 2
 3repos:
 4  - repo: local
 5    hooks:
 6      - id: go-build
 7        name: Go Build
 8        entry: bash -c 'go build ./...'
 9        language: system
10        pass_filenames: false
11
12      - id: go-test-unit
13        name: Go Unit Tests
14        entry: bash -c 'go test -race -count=1 ./internal/domain/... ./internal/usecase/... ./pkg/...'
15        language: system
16        pass_filenames: false
17
18      - id: golangci-lint
19        name: golangci-lint
20        entry: golangci-lint run --fix
21        language: system
22        pass_filenames: false
23
24      - id: specify-audit-quick
25        name: Specify Quick Check
26        entry: bash -c 'specify audit --output json | jq -e ".score >= 70" || (echo "Spec score below 70 — fix before commit" && exit 1)'
27        language: system
28        pass_filenames: false
29
30      - id: no-debug-code
31        name: No debug/TODO critical
32        entry: bash -c '! grep -r "fmt.Println\|log.Println\|TODO: CRITICAL\|FIXME:" --include="*.go" internal/'
33        language: system
34        pass_filenames: false
35
36# Install: pre-commit install

Perhatikan threshold specify audit di sini adalah 70 — lebih longgar dari gate CI (80) — sengaja dibuat agar commit lokal tetap lancar sambil tetap mencegat regresi spec yang parah lebih awal.


17.05 AI-Assisted PR Review

Salah satu quality gate paling menarik adalah code review otomatis oleh Claude terhadap aturan di CLAUDE.md. Workflow berikut mengambil file yang berubah, mengirimnya ke Claude API, dan mem-posting hasilnya sebagai komentar PR.

yaml
 1# .github/workflows/ai-review.yml
 2
 3name: AI Code Review
 4
 5on:
 6  pull_request:
 7    types: [opened, synchronize]
 8    branches: [main, develop]
 9
10jobs:
11  ai-review:
12    name: "AI Review"
13    runs-on: ubuntu-latest
14    permissions:
15      pull-requests: write
16      contents: read
17
18    steps:
19      - uses: actions/checkout@v4
20        with:
21          fetch-depth: 0
22
23      - name: Get changed files
24        id: changed-files
25        run: |
26          CHANGED=$(git diff --name-only ${{ github.event.pull_request.base.sha }} HEAD \
27            | grep '\.go$' | head -20 | tr '\n' ' ')
28          echo "files=$CHANGED" >> $GITHUB_OUTPUT
29
30      - name: AI Review with Claude API
31        env:
32          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
33        run: |
34          # Build prompt dari CLAUDE.md + changed files
35          CHANGED_CODE=$(cat ${{ steps.changed-files.outputs.files }})
36          CLAUDE_MD=$(cat CLAUDE.md)
37
38          curl -s https://api.anthropic.com/v1/messages \
39            -H "x-api-key: $ANTHROPIC_API_KEY" \
40            -H "anthropic-version: 2023-06-01" \
41            -H "Content-Type: application/json" \
42            -d "{
43              \"model\": \"claude-sonnet-4-20250514\",
44              \"max_tokens\": 2000,
45              \"messages\": [{
46                \"role\": \"user\",
47                \"content\": \"Review PR based on CLAUDE.md rules:\\n$CLAUDE_MD\\n\\nChanged files:\\n$CHANGED_CODE\\n\\nFocus: architecture violations, error handling, spec coverage, performance issues. Be concise.\"
48              }]
49            }" | jq -r '.content[0].text' > ai-review.txt
50
51      - name: Post review comment
52        uses: actions/github-script@v7
53        with:
54          script: |
55            const fs = require('fs');
56            const review = fs.readFileSync('ai-review.txt', 'utf8');
57            github.rest.issues.createComment({
58              issue_number: context.issue.number,
59              owner: context.repo.owner,
60              repo: context.repo.repo,
61              body: `## 🤖 AI Code Review\n\n${review}\n\n*Powered by Claude + CLAUDE.md*`
62            });

Karena prompt menyertakan isi CLAUDE.md, review AI ini menilai kode dengan aturan proyek yang sama persis seperti reviewer manusia — bukan aturan generik, melainkan konvensi arsitektur Santekno Shop.


17.06 Rollback Strategy

Deploy yang aman butuh jalan pulang yang cepat. Workflow rollback berikut memungkinkan tim mengembalikan deployment ke SHA tertentu lewat workflow_dispatch.

yaml
 1# .github/workflows/rollback.yml
 2
 3name: Rollback
 4
 5on:
 6  workflow_dispatch:
 7    inputs:
 8      target_sha:
 9        description: 'Git SHA to rollback to'
10        required: true
11      environment:
12        description: 'Environment (staging/production)'
13        required: true
14        default: 'staging'
15
16jobs:
17  rollback:
18    name: "Rollback Deployment"
19    runs-on: ubuntu-latest
20    environment: ${{ inputs.environment }}
21
22    steps:
23      - uses: actions/checkout@v4
24        with:
25          ref: ${{ inputs.target_sha }}
26
27      - name: Rollback image
28        run: |
29          IMAGE="${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:sha-${{ inputs.target_sha }}"
30          kubectl set image deployment/santekno-shop app=$IMAGE
31          kubectl rollout status deployment/santekno-shop --timeout=300s
32
33      - name: Verify rollback
34        run: |
35          CURRENT=$(kubectl get deployment santekno-shop \
36            -o jsonpath='{.spec.template.spec.containers[0].image}')
37          echo "Current image: $CURRENT"
38          curl -sf https://shop-${{ inputs.environment }}.santekno.com/health
39
40      - name: Notify rollback
41        uses: slackapi/slack-github-action@v1
42        with:
43          payload: |
44            {"text": "🔄 Rollback executed: ${{ inputs.environment }} → SHA ${{ inputs.target_sha }}"}
45        env:
46          SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}

Rollback bergantung pada image tag berbasis SHA (sha-abc1234), jadi setiap deployment lama selalu bisa dipasang ulang — kunci agar pemulihan insiden berjalan dalam menit, bukan jam.


17.07 Branch Protection Rules

Pipeline hanya berguna jika tidak bisa dilewati. Aturan branch protection berikut memaksa semua status check lulus sebelum merge ke main.

text
 1GitHub Settings → Branches → Add Rule → main
 2
 3✅ Require pull request reviews before merging
 4   - Required approving reviews: 1
 5   - Dismiss stale reviews when new commits are pushed
 6
 7✅ Require status checks before merging
 8   - validate
 9   - unit-test
10   - integration-test
11   - ai-quality-gates
12
13✅ Require branches to be up to date before merging
14
15✅ Do not allow bypassing the above settings
16   (even for admins)
17
18✅ Restrict pushes that create matching branches
19   (prevent direct push to main)

Opsi “Do not allow bypassing … even for admins” penting: tanpanya, gate hanya berlaku untuk sebagian tim, dan disiplin spec-first akan bocor lewat jalur admin.


17.08 Environment Secrets

Deployment butuh kredensial yang tidak boleh masuk ke repo. Daftar berikut merangkum secret GitHub yang dibutuhkan pipeline dan cara menambahkannya via CLI.

bash
 1# GitHub Repository Secrets yang dibutuhkan:
 2
 3# Deployment
 4STAGING_DATABASE_URL      # postgres://... ke staging DB
 5STAGING_KUBECONFIG        # base64-encoded kubeconfig
 6PRODUCTION_DATABASE_URL   # postgres://... ke production DB
 7PRODUCTION_KUBECONFIG     # base64-encoded kubeconfig
 8
 9# AI Review
10ANTHROPIC_API_KEY         # Claude API key for code review
11
12# Notifications
13SLACK_WEBHOOK             # Slack webhook URL
14
15# Registry (otomatis dari GitHub Actions)
16GITHUB_TOKEN              # auto-provided, untuk ghcr.io push
17
18# Tambahkan via GitHub CLI:
19gh secret set ANTHROPIC_API_KEY --body "sk-ant-xxx"
20gh secret set STAGING_DATABASE_URL --body "postgres://..."
21gh secret set SLACK_WEBHOOK --body "https://hooks.slack.com/..."

GITHUB_TOKEN disediakan otomatis oleh Actions untuk push ke ghcr.io — sisanya harus di-set manual, dan wajib dirotasi setiap kali ada perubahan anggota tim.


17.09 Deployment Environments

GitHub Environments memungkinkan aturan proteksi berbeda antara staging dan production. Konfigurasi berikut membuat staging auto-deploy sementara production butuh approval dan wait timer.

yaml
 1# GitHub Environments untuk protection rules
 2
 3# Staging environment:
 4# - Auto-deploy dari branch develop
 5# - No approval required
 6# - URL: shop-staging.santekno.com
 7
 8# Production environment:
 9# - Auto-deploy dari branch main
10# - Required reviewers: 2 approvers
11# - Wait timer: 10 minutes (rollback window)
12# - URL: shop.santekno.com
13
14# Buat via GitHub CLI:
15gh api repos/$OWNER/$REPO/environments/staging \
16  --method PUT \
17  --field deployment_branch_policy='{"protected_branches": false}'
18
19gh api repos/$OWNER/$REPO/environments/production \
20  --method PUT \
21  --field wait_timer=600 \
22  --field reviewers='[{"type":"User","id":123456}]'

Wait timer 10 menit pada production adalah rem darurat: memberi waktu tim membatalkan deploy jika ada sinyal masalah sebelum trafik nyata mengenai versi baru.


17.10 Specify Audit dalam CI

Gate paling khas SDD adalah specify audit yang memverifikasi setiap AC spec sudah terimplementasi. Contoh berikut menunjukkan cara CLI mendeteksi coverage dan format spec.yaml yang dibacanya.

bash
 1# specify audit → check bahwa semua spec ACs ter-implementasi
 2
 3# Cara specify CLI mendeteksi coverage:
 4# 1. Baca spec.yaml (dibuat Artikel 01)
 5# 2. Cari pattern dalam kode: test functions, handler paths, error types
 6# 3. Match test name convention: Test[Feature]_[AC]_[Expected]
 7# 4. Score = (ACs covered / ACs total) * 100
 8
 9# Konfigurasi: spec.yaml
10features:
11  - name: place-order
12    acceptance_criteria:
13      - id: AC1
14        description: "valid order → 201"
15        patterns:
16          - test_name: "TestPlaceOrder_ValidItems"
17          - handler_path: "POST /api/v1/orders"
18          - response_code: 201
19      - id: AC2
20        description: "insufficient stock → 422"
21        patterns:
22          - test_name: "TestPlaceOrder_InsufficientStock"
23          - error_type: "ErrInsufficientStock"
24          - response_code: 422
25
26# CI threshold: score >= 80
27# Artikel 08 akhir: ~80/100 ← threshold pertama kali tercapai
28# Artikel 09 akhir: ~90/100
29# Artikel 10 akhir: ~95/100

Skor yang naik dari artikel ke artikel bukan kebetulan — ia adalah bukti terukur bahwa implementasi makin selaras dengan spec, dan gate 80 memastikan tren itu tidak pernah mundur diam-diam.


17.11 Docker Build Optimization

Build image yang cepat bergantung pada layering yang benar. Dockerfile multi-stage berikut memisahkan download dependency, build, dan image final agar cache CI maksimal.

dockerfile
 1# Dockerfile — optimized untuk CI build cache
 2
 3# Stage 1: download dependencies (layer di-cache jika go.sum tidak berubah)
 4FROM golang:1.22-alpine AS deps
 5WORKDIR /app
 6COPY go.mod go.sum ./
 7RUN go mod download
 8
 9# Stage 2: build (layer di-cache jika source tidak berubah)
10FROM deps AS builder
11COPY . .
12ARG BUILD_VERSION=dev
13ARG BUILD_TIME=unknown
14RUN CGO_ENABLED=0 GOOS=linux go build \
15    -ldflags="-X main.version=${BUILD_VERSION} -X main.buildTime=${BUILD_TIME} -s -w" \
16    -o /app/server ./cmd/server/
17
18# Stage 3: final image (minimal, ~21MB)
19FROM scratch
20COPY --from=builder /app/server /server
21COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
22EXPOSE 8080
23ENTRYPOINT ["/server"]

Agar layer ini benar-benar di-cache antar run, aktifkan cache GitHub Actions di langkah build berikut.

yaml
1# Build cache dalam CI dengan GitHub Actions Cache
2- name: Build and push
3  uses: docker/build-push-action@v5
4  with:
5    cache-from: type=gha           # baca dari GHA cache
6    cache-to: type=gha,mode=max    # tulis ke GHA cache
7    # mode=max: cache semua layer, lebih lambat tapi lebih efektif

Kombinasi stage deps yang terpisah dan cache type=gha membuat build tanpa perubahan kode selesai dalam ~1 menit — hanya berubah drastis saat go.sum ikut berubah.


17.12 Smoke Test setelah Deploy

Deploy sukses secara teknis belum tentu berarti aplikasi sehat. Script smoke test berikut memverifikasi endpoint kritis segera setelah rollout selesai.

bash
 1# scripts/smoke-test.sh
 2#!/bin/bash
 3BASE_URL=$1
 4TIMEOUT=30
 5
 6echo "Running smoke tests against $BASE_URL..."
 7
 8# Test 1: Health check
 9STATUS=$(curl -sf -o /dev/null -w "%{http_code}" --max-time $TIMEOUT "$BASE_URL/health")
10[[ "$STATUS" == "200" ]] || { echo "❌ Health check failed: $STATUS"; exit 1; }
11echo "✅ Health check: $STATUS"
12
13# Test 2: Products endpoint
14STATUS=$(curl -sf -o /dev/null -w "%{http_code}" --max-time $TIMEOUT "$BASE_URL/api/v1/products")
15[[ "$STATUS" == "200" ]] || { echo "❌ Products endpoint failed: $STATUS"; exit 1; }
16echo "✅ Products endpoint: $STATUS"
17
18# Test 3: Auth endpoint exists (tidak register — cukup check 400 untuk invalid req)
19STATUS=$(curl -sf -o /dev/null -w "%{http_code}" -X POST --max-time $TIMEOUT \
20  -H "Content-Type: application/json" -d '{}' "$BASE_URL/api/v1/auth/register")
21[[ "$STATUS" == "400" ]] || { echo "❌ Auth endpoint failed: $STATUS"; exit 1; }
22echo "✅ Auth endpoint: $STATUS"
23
24echo "✅ All smoke tests passed"

Smoke test yang gagal memicu auto-rollback, sehingga versi yang jelas rusak tidak pernah bertahan lama menerima trafik nyata.


17.13 Pipeline Execution Time Target

Pipeline yang lambat akan dihindari developer. Target waktu berikut menjadi acuan agar setiap stage tetap dalam batas yang wajar.

text
 1Pipeline execution time targets:
 2
 3Stage 1 (validate):       2-3 min  ← fast feedback
 4Stage 2 (unit-test):      3-5 min  ← parallel dengan integration
 5Stage 2 (integration):    5-8 min  ← terlama, paralel
 6Stage 3 (ai-gates):       2-3 min  ← after tests
 7Stage 4 (build):          3-5 min  ← hanya di main/develop
 8Stage 5 (deploy):         5-10 min ← hanya di main/develop
 9
10Total PR check:     ~10-15 menit (parallel execution)
11Total main deploy:  ~25-30 menit (end-to-end)
12
13Optimization tips:
14  - go mod download di-cache dengan setup-go cache: true
15  - Docker build di-cache dengan type=gha
16  - Stages dijalankan paralel semaksimal mungkin
17  - Unit test dan integration test berjalan secara paralel

Kunci menjaga PR check di bawah 15 menit adalah paralelisme: unit test dan integration test berjalan bersamaan, bukan berurutan.


17.14 Monitoring Pipeline Health

Pipeline sendiri perlu dipantau agar kegagalan tidak lolos tanpa disadari. Notifikasi Slack berikut memberi tahu tim saat ada stage gagal maupun saat deploy berhasil.

yaml
 1# Slack notification untuk semua pipeline events
 2
 3# Notify on failure (any stage):
 4- name: Notify on failure
 5  if: failure()
 6  uses: slackapi/slack-github-action@v1
 7  with:
 8    payload: |
 9      {
10        "text": "❌ CI Failed: ${{ github.workflow }} on ${{ github.ref_name }}\n${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
11      }
12  env:
13    SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
14
15# Notify on successful deploy:
16- name: Notify success
17  if: success() && github.ref == 'refs/heads/main'
18  uses: slackapi/slack-github-action@v1
19  with:
20    payload: |
21      {
22        "text": "✅ Deploy successful: ${{ github.event.head_commit.message }}\n${{ env.DEPLOY_URL }}"
23      }

Notifikasi kegagalan menyertakan link langsung ke run yang bermasalah, memangkas waktu dari “ada yang merah” ke “ini penyebabnya” jadi satu klik.


17.15 Pipeline Badge di README

Status pipeline sebaiknya terlihat langsung di halaman depan repo. Badge Markdown berikut menampilkan status CI/CD, spec compliance, dan versi Go di README.

markdown
 1<!-- README.md -->
 2
 3# Santekno Shop
 4
 5[![CI/CD](https://github.com/santekno/santekno-shop/actions/workflows/main.yml/badge.svg)](https://github.com/santekno/santekno-shop/actions/workflows/main.yml)
 6[![Go Report Card](https://goreportcard.com/badge/github.com/santekno/santekno-shop)](https://goreportcard.com/report/github.com/santekno/santekno-shop)
 7[![Spec Compliance](https://img.shields.io/badge/spec%20compliance-95%25-brightgreen)](https://github.com/santekno/santekno-shop/actions)
 8[![Go Version](https://img.shields.io/badge/go-1.22-blue)](https://golang.org)
 9
10Build production-grade e-commerce with Spec-Driven Development + Clean Architecture.

Badge spec compliance yang tampil hijau di README menjadikan disiplin SDD sesuatu yang terlihat dan membanggakan — sekaligus sinyal cepat bagi kontributor baru tentang standar proyek.


17.16 Pipeline Metrics

Kesehatan pipeline jangka panjang perlu diukur, bukan dirasakan. Daftar metrik berikut beserta target dan ambang alert-nya menjadi dashboard kesehatan CI/CD.

text
 1Key metrics untuk track pipeline health:
 2
 31. Pipeline success rate
 4   target: > 95%
 5   alert: < 90% dalam 7 hari
 6
 72. Average pipeline duration
 8   target: < 15 menit (PR check)
 9   alert: > 20 menit
10
113. Test failure rate
12   target: < 5% non-flaky failures
13   alert: > 10%
14
154. Coverage trend
16   target: stable atau naik
17   alert: turun > 5% dalam satu PR
18
195. Spec audit score trend
20   target: stable atau naik
21   alert: turun > 10 poin
22
23Track via GitHub Actions API atau Datadog/Grafana integration.

Metrik “test failure rate” khususnya penting untuk mendeteksi test flaky — kegagalan yang bukan karena bug asli akan mengikis kepercayaan tim terhadap gate CI jika dibiarkan.


17.17 Production Deploy Approval Flow

Deploy ke production adalah momen berisiko tertinggi dan butuh alur yang eksplisit. Urutan langkah berikut menggambarkan proses dari merge hingga deploy production, termasuk jalur hotfix darurat.

text
 1Production deploy flow (main branch):
 2
 31. Developer merge PR ke main
 42. CI runs: validate → test → ai-gates
 53. Build + push Docker image
 64. Notify team: "Ready for production deploy"
 75. Required reviewers (2 orang) approve di GitHub Environments
 86. 10-menit wait timer (rollback window jika ada issue)
 97. Deploy: migrate + rolling update + smoke test
108. If smoke test fails → auto rollback ke previous image
119. Notify team: success / failure
12
13Emergency deploy (hotfix):
14  → Branch: hotfix/* → bypass wait timer
15  → Masih butuh 1 approver
16  → Smoke test tetap wajib

Perhatikan bahwa jalur hotfix memangkas wait timer tapi tetap mempertahankan approval dan smoke test — kecepatan darurat tidak boleh mengorbankan verifikasi minimum.


17.18 Dependency Update Automation

Menjaga dependency tetap mutakhir dan aman sebaiknya otomatis. Konfigurasi Dependabot berikut menjadwalkan update mingguan untuk modul Go, image Docker, dan GitHub Actions.

yaml
 1# .github/dependabot.yml
 2
 3version: 2
 4updates:
 5  # Go module updates
 6  - package-ecosystem: gomod
 7    directory: "/"
 8    schedule:
 9      interval: weekly
10      day: monday
11      time: "09:00"
12    open-pull-requests-limit: 5
13    labels: ["dependencies", "go"]
14    commit-message:
15      prefix: "chore(deps)"
16    # Group minor + patch updates together (reduce PR noise)
17    groups:
18      minor-and-patch:
19        update-types:
20          - minor
21          - patch
22
23  # Docker base image updates
24  - package-ecosystem: docker
25    directory: "/"
26    schedule:
27      interval: weekly
28    labels: ["dependencies", "docker"]
29
30  # GitHub Actions updates
31  - package-ecosystem: github-actions
32    directory: "/"
33    schedule:
34      interval: weekly
35    labels: ["dependencies", "github-actions"]

Grouping update minor dan patch dalam satu PR memangkas kebisingan — tim tetap dapat review update major secara terpisah tanpa dibanjiri puluhan PR kecil tiap minggu.


17.19 Full Pipeline Sequence Diagram

Agar seluruh alur mudah dibayangkan, diagram sequence berikut menggambarkan interaksi antara developer, GitHub, CI runner, registry, dan Kubernetes dari push hingga notifikasi.

MERMAID
sequenceDiagram
    participant Dev as Developer
    participant GH as GitHub
    participant CI as CI Runner
    participant Reg as Registry
    participant K8s as Kubernetes

    Dev->>GH: Push / Open PR
    GH->>CI: Trigger workflow

    par Stage 1: Validate
        CI->>CI: go build + lint + vet
    and Stage 2: Test
        CI->>CI: unit tests (parallel)
        CI->>CI: integration tests (parallel)
    end

    CI->>CI: Stage 3: AI Quality Gates
    note over CI: specify audit ≥ 80<br/>gosec scan<br/>govulncheck

    CI->>Reg: Stage 4: Build & Push Docker image

    alt Branch: develop → staging
        CI->>K8s: Run migrations
        CI->>K8s: Rolling update
        CI->>CI: Smoke test
    else Branch: main → production
        CI->>Dev: Wait for approval
        Dev->>GH: Approve deployment
        CI->>K8s: Run migrations
        CI->>K8s: Rolling update
        CI->>CI: Smoke test
    end

    CI-->>Dev: Slack notification

Diagram ini menegaskan satu perbedaan kunci: cabang develop mengalir mulus ke staging, sedangkan cabang main berhenti menunggu approval manusia sebelum menyentuh production.


17.20 Ringkasan: CI/CD Pipeline Santekno Shop

Pipeline Santekno Shop pada dasarnya adalah “spec compliance machine” — setiap push memastikan implementasi tetap sesuai spec, arsitektur tetap clean, dan deployment tetap aman.

5 stages: validate → test → ai-gates → build → deploy, dengan paralelisme dimaksimalkan untuk kecepatan.

AI Quality Gates: specify audit, gosec, govulncheck, dan depguard — semua terotomasi.

Branch protection: tidak ada yang bisa merge ke main tanpa semua gate lulus, bahkan admin.

Deployment safety: smoke test, rollback otomatis, dan production approval flow menjaga deploy buruk tidak pernah bertahan.

Observability: notifikasi Slack untuk setiap event, badge di README, dan metrics tracking membuat kesehatan pipeline selalu terlihat. Setiap merge ke main adalah artefak yang terbukti spec-compliant, sound secara arsitektur, dan sudah di-scan keamanannya.

Artikel Terkait

💬 Komentar