DevOps, CI/CD and IaCVol. 8 · Part VIII
0 / 0

Shelves / DevOps, CI/CD and IaC

DL·93

CI/CD

Continuous integration, delivery and deployment from first principles: why they work (small batches, fast feedback, DORA metrics), every pipeline stage from lint to observe with concrete commands for Java, Go, Rust, Python, TypeScript, C/C++ and Zig, then the tools: GitHub Actions in depth (workflows, matrices, reusable workflows, artifacts, caches, environments, secrets, OIDC, approvals, concurrency, hardening), GitLab CI, Jenkins and TeamCity, plus pipeline speed, flaky tests, monorepos and supply-chain security of the pipeline itself.

29 topics · ~21 min read · 31-question quiz
Updated Suggest a correction

Start here: a pipeline as code

From a script to a workflow

The Start Here chapter's pipeline was a shell script on one machine. A CI system turns it into a pipeline definition stored in the repository and run on every push or pull request, in clean, disposable environments, with results attached to the commit. In GitHub Actions it's a YAML workflow of jobs (each on its own runner) made of steps:

YAML
name: ci
on: [push]
defaults:
  run:
    shell: sh          # the local runner image (Alpine) has no bash
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: vet
        run: cd $GITHUB_WORKSPACE && go vet ./...
      - name: unit tests
        run: cd $GITHUB_WORKSPACE && go test ./...
  build:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - name: compile
        run: cd $GITHUB_WORKSPACE && CGO_ENABLED=0 go build -o /tmp/tiffin . && ls -la /tmp/tiffin
Text
[ci/test] 🚀  Start image=golang:1.24-alpine
[ci/test] ⭐ Run Main vet
[ci/test]   ✅  Success - Main vet [19.269935349s]
[ci/test] ⭐ Run Main unit tests
[ci/test]   | ok  	tiffin	0.003s
[ci/test]   ✅  Success - Main unit tests [4.614809884s]
[ci/test] 🏁  Job succeeded
[ci/build] 🚀  Start image=golang:1.24-alpine
[ci/build] ⭐ Run Main compile
[ci/build]   | -rwxrwxrwx    1 root     root       8567792 Oct 30 05:33 /tmp/tiffin
[ci/build]   ✅  Success - Main compile [17.053872859s]
[ci/build] 🏁  Job succeeded

build ran only because test succeeded (needs: test). Each job started from a fresh container, which is why vet took 19 seconds: the Go toolchain compiled the standard library from scratch. That clean start is a feature (no leftovers from earlier runs, so results are reproducible) and a cost (everything is rebuilt unless you cache it; the lab measures it).

The vocabulary

Concept GitHub Actions GitLab CI Jenkins
Pipeline definition .github/workflows/*.yml .gitlab-ci.yml Jenkinsfile
Unit of parallel work job job stage / parallel branch
Ordering needs: stages: and needs: stage order
Where it runs runner (hosted or self-hosted) runner agent
Reusable pieces actions, reusable workflows include:, components shared libraries
Secrets repository/environment secrets, OIDC CI/CD variables, OIDC credentials store
Outputs passed on artifacts, caches, outputs artifacts, caches stash/archive

Continuous integration, delivery and deployment

  • Continuous integration (CI): everyone merges small changes to the main branch often (at least daily), and every change is built and tested automatically. It keeps integration problems small.
  • Continuous delivery: every change that passes the pipeline produces an artifact that could be deployed to production at the push of a button.
  • Continuous deployment: every passing change is deployed to production automatically, no button.

The pipeline's job is to give fast, trustworthy feedback: a red build should mean a real problem, found within minutes. Slow or flaky pipelines teach people to ignore them, which is worse than having none.

How deep to go in CI/CD

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain CI, continuous delivery and deployment, pipelines, jobs, runners and artifacts
L2 Write pipelines that test, build, publish and deploy, with caches and secrets
L3 Explain runner isolation, caching, artifact promotion, matrices, and pipeline security (OIDC, permissions)
L4 Diagnose slow, flaky or insecure pipelines and wrong deployments
L5 Design CI/CD for many teams: templates, environments, approvals, supply-chain controls
L6 Operate a delivery platform at scale with fleet runners, cost control and DORA metrics

Integration, delivery and deployment

Definitions

  • Continuous integration (CI): every developer integrates their work into the shared mainline at least daily, and every integration is verified by an automated build and test. The point is to find integration problems while they're small (Martin Fowler; Kent Beck's Extreme Programming).
  • Continuous delivery (CD): every change that passes the pipeline is releasable; deploying to production is a business decision taken with a button, not a project.
  • Continuous deployment: every change that passes the pipeline is deployed to production automatically, with no human gate.

The underlying insight is about batch size: small, frequent changes are easier to review, test, diagnose and roll back than large, rare ones. Releasing often makes releases boring.

Measuring delivery: DORA

The DORA research programme (DevOps Research and Assessment, now at Google; Accelerate by Forsgren, Humble and Kim) found that a few metrics predict both delivery performance and organisational outcomes:

Metric Measures Elite-performer ballpark
Deployment frequency How often you deploy to production On demand, multiple times per day
Change lead time Commit → running in production Less than a day
Change failure rate % of deployments causing a failure needing remediation Low (around 5–15%)
Failed deployment recovery time (formerly MTTR) Time to restore service after a failed change Less than an hour
Rework rate (added in recent reports) Unplanned deployments to fix user-facing issues Low

The striking finding: speed and stability go together. Teams that deploy more often also fail less and recover faster, because small changes and automation reduce risk. Capabilities that drive these metrics include trunk-based development, test automation, deployment automation, loosely coupled architecture, and fast feedback.

The pipeline

Stages

The roadmap's pipeline, with the reason for each stage's position (cheapest, fastest checks first: fail fast):

commit lint typecheck unit tests build security scan integration E2E artifactdigest, signed deploy staging smoke test deploy prodcanary → 100% smoke observe SLO breach → auto rollback seconds–minutesminutespromote same artefact
A CI/CD pipeline. Cheap, fast checks run first so most failures surface in seconds; expensive tests run later and in parallel; a single immutable artefact is built once, then promoted through environments; deployment is followed by smoke tests and observation, with automatic rollback on failure.
Stage Purpose Typical tools
Commit Trigger: push, pull request, merge queue, tag, schedule Branch protection, required checks
Lint / format Style and simple bug patterns, in seconds Spotless/Checkstyle/PMD/Error Prone, gofmt/golangci-lint, rustfmt/clippy, ruff, ESLint/Biome/Prettier, clang-format/clang-tidy, zig fmt --check
Typecheck Type errors (dynamic languages, or separate step) tsc --noEmit, mypy/pyright; compilers do this in Java, Go, Rust, C++, Zig
Unit tests Fast, isolated logic tests with coverage JUnit, go test, cargo test/nextest, pytest, Vitest/Jest, GoogleTest/Catch2, zig build test
Build Compile and package once: JAR, binary, wheel, container image Maven/Gradle, go build, Cargo, uv/build, npm/pnpm, CMake/Ninja, zig build, Docker BuildKit
Security scan SAST, dependency (SCA), secrets, licences, IaC misconfig, container image CodeQL, Semgrep, Dependabot/Renovate, OSV-Scanner, Trivy, Grype, gitleaks, Checkov
Integration Real dependencies in containers (databases, brokers) Testcontainers (all major languages), Docker Compose services
E2E User journeys through the deployed system Playwright, Cypress, API test suites (Vol. 11)
Artifact Publish immutable, versioned, signed outputs with SBOM and provenance Container registries, Maven Central/Artifactory/Nexus, PyPI, npm, crates.io, GitHub Releases
Deploy Promote the same artefact through environments GitOps (chapter 95), Helm, CDK/Terraform, cloud deploy actions
Smoke test Minimal checks right after deploy: health, a key journey curl/k6/Playwright smoke subset
Observe Watch SLOs and error rates; automatic rollback or promotion Argo Rollouts analysis, CloudWatch alarms, Datadog monitors

Principles:

  • Build once, deploy many: never rebuild per environment (Vol. 6 ch. 84).
  • The pipeline is the only path to production: no manual uploads, no console changes.
  • Keep the main branch green: a failing main is everyone's top priority. Merge queues (GitHub, GitLab merge trains, Mergify, Aviator) test each PR against the latest main plus PRs ahead of it before merging, preventing "green PR, red main" races.
  • Fast feedback: target under ~10 minutes for the PR pipeline. Run slow suites in parallel, on merge, or nightly.

Per-language CI commands

# Java (Maven): verify runs compile, unit tests (Surefire), integration tests (Failsafe) and checks
./mvnw -B -ntp spotless:check verify            # -B batch mode, -ntp no transfer progress
# Gradle:  ./gradlew check build --scan

GitHub Actions in depth

Concepts

  • Workflow: a YAML file in .github/workflows/, triggered by events (push, pull_request, merge_group, workflow_dispatch (manual), schedule (cron), release, workflow_call, repository_dispatch).
  • Job: a set of steps on one runner; jobs run in parallel unless linked with needs:.
  • Step: a shell command (run:) or an action (uses: owner/repo@ref): reusable units written in JavaScript, Docker, or as composite actions.
  • Runner: GitHub-hosted (Ubuntu, Windows, macOS, ARM, larger and GPU runners) or self-hosted (your machines, or autoscaled with Actions Runner Controller on Kubernetes).
  • Matrix: run a job across combinations (os × version).
  • Contexts and expressions: ${{ github.sha }}, ${{ secrets.X }}, ${{ needs.build.outputs.digest }}, if: github.ref == 'refs/heads/main'.

A complete workflow

YAML
# .github/workflows/ci.yml
name: ci
on:
  pull_request:
  merge_group:                         # merge queue runs
  push:
    branches: [main]
    tags: ["v*"]

permissions:
  contents: read                       # least privilege by default for GITHUB_TOKEN

concurrency:
  group: ci-${{ github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}   # cancel superseded PR runs

jobs:
  test:
    runs-on: ubuntu-24.04
    strategy:
      fail-fast: false
      matrix:
        java: [21, 25]
    steps:
      - uses: actions/checkout@<commit-sha>   # v4
      - uses: actions/setup-java@<commit-sha>   # v4
        with: { distribution: temurin, java-version: "${{ matrix.java }}", cache: maven }
      - run: ./mvnw -B -ntp verify
      - uses: actions/upload-artifact@<commit-sha>   # v4
        if: failure()
        with: { name: test-reports-${{ matrix.java }}, path: "**/target/surefire-reports/", retention-days: 7 }

  image:
    needs: test
    if: github.event_name != 'pull_request'
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      packages: write                  # push to GHCR
      id-token: write                  # OIDC for keyless signing / cloud auth
      attestations: write              # build provenance
    outputs:
      digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@<commit-sha>
      - uses: docker/setup-buildx-action@<commit-sha>
      - uses: docker/login-action@<commit-sha>
        with: { registry: ghcr.io, username: "${{ github.actor }}", password: "${{ secrets.GITHUB_TOKEN }}" }
      - id: build
        uses: docker/build-push-action@<commit-sha>
        with:
          push: true
          tags: ghcr.io/${{ github.repository }}:sha-${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          sbom: true
          provenance: mode=max
      - uses: actions/attest-build-provenance@<commit-sha>
        with:
          subject-name: ghcr.io/${{ github.repository }}
          subject-digest: ${{ steps.build.outputs.digest }}
          push-to-registry: true

  deploy-staging:
    needs: image
    if: github.ref == 'refs/heads/main'
    uses: ./.github/workflows/deploy.yml          # reusable workflow
    with: { environment: staging, digest: "${{ needs.image.outputs.digest }}" }
    secrets: inherit

  deploy-prod:
    needs: [image, deploy-staging]
    if: startsWith(github.ref, 'refs/tags/v')
    uses: ./.github/workflows/deploy.yml
    with: { environment: production, digest: "${{ needs.image.outputs.digest }}" }
    secrets: inherit

(<commit-sha> stands for the full 40-character commit SHA of the release you choose; Dependabot and Renovate keep these pins updated and annotate the version in a comment.)

Reusable workflows and composite actions

  • Reusable workflows (on: workflow_call with typed inputs, secrets, outputs) define whole pipelines once (e.g. "deploy service to environment") and are called from many repositories: uses: acme/platform/.github/workflows/deploy.yml@v3. Nesting is limited (a few levels), and called workflows run as separate jobs.
  • Composite actions bundle steps into one reusable action (runs: using: composite), e.g. "set up our toolchain with cache".
  • Starter workflows and organisation rulesets (required workflows) roll out standards across repositories.
YAML
# .github/workflows/deploy.yml: reusable deploy with environment protection and OIDC to AWS
on:
  workflow_call:
    inputs:
      environment: { type: string, required: true }
      digest:      { type: string, required: true }
jobs:
  deploy:
    runs-on: ubuntu-24.04
    environment: ${{ inputs.environment }}         # protection rules, approvals, env secrets apply here
    permissions: { id-token: write, contents: read }
    steps:
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ vars.DEPLOY_ROLE_ARN }}   # environment-level variable
          aws-region: ap-south-1
      - run: ./scripts/deploy.sh "${{ inputs.environment }}" "${{ inputs.digest }}"
      - run: ./scripts/smoke.sh "${{ inputs.environment }}"

Artifacts and caches

They solve different problems:

Artifacts Cache
Purpose Pass outputs between jobs or keep them for people (test reports, binaries, coverage) Speed up inputs that are expensive to recreate (dependency downloads, compiler caches)
Correctness Required for the pipeline to work Optional: a cache miss must only make the build slower, never wrong
Keyed by Name, per run Key (usually a hash of the lockfile + OS), with restore-key prefixes as fallbacks
Retention Configurable days Evicted by size limits and age
YAML
- uses: actions/cache@v4
  with:
    path: |
      ~/.cache/go-build
      ~/go/pkg/mod
    key: go-${{ runner.os }}-${{ hashFiles('**/go.sum') }}
    restore-keys: go-${{ runner.os }}-

setup-* actions (setup-java, setup-node, setup-python, setup-go) have built-in dependency caching; Docker layer caching uses type=gha or a registry cache; remote build caches (Gradle build cache, Bazel remote cache, sccache for Rust/C++, Turborepo/Nx remote cache) share compiled outputs across runners and developers.

Environments, secrets and approvals

  • Environments (staging, production) carry protection rules: required reviewers (manual approval), wait timers, allowed branches/tags, and custom deployment protection rules (e.g. a change-management or monitoring check).
  • Secrets exist at organisation, repository and environment scope. Environment secrets are only available to jobs targeting that environment, after approval. Secrets are masked in logs, but masking isn't a security boundary (transformations of a secret aren't masked).
  • Prefer OIDC federation (id-token: write) to cloud providers over stored cloud keys (Vol. 7 ch. 89); scope trust policies to the repository and environment.
  • GITHUB_TOKEN: an automatically created, per-run token. Set default workflow permissions to read-only and grant per job.

Hardening GitHub Actions

CI systems hold the keys to production, so they're prime targets (the 2025 tj-actions/changed-files compromise leaked secrets from thousands of repositories through a tampered tag):

  • Pin third-party actions to full commit SHAs, not tags (tags can be moved); update via Dependabot/Renovate.
  • Least-privilege permissions: at workflow and job level.
  • Be careful with untrusted input: pull_request workflows from forks run without secrets; pull_request_target and workflow_run run with secrets in the base repository context, so never check out and execute PR code in them. Never interpolate attacker-controlled strings (${{ github.event.pull_request.title }}) directly into run: scripts (script injection); pass them through environment variables.
  • Restrict which actions can run (allow-lists at organisation level), require approval for first-time contributors' workflows.
  • Self-hosted runners: don't use them for public repositories; use ephemeral, single-use runners (ARC, autoscaled VMs) so one job can't poison the next.
  • Audit: tools like zizmor and OpenSSF Scorecard flag risky workflow patterns.

GitLab CI

GitLab CI is configured in .gitlab-ci.yml, with pipelines tightly integrated into merge requests, environments and the container registry:

YAML
# .gitlab-ci.yml
stages: [check, build, test, publish, deploy]

default:
  image: golang:1.25
  cache:
    key: { files: [go.sum] }
    paths: [.cache/go-mod]

variables:
  GOMODCACHE: $CI_PROJECT_DIR/.cache/go-mod

lint:
  stage: check
  script: [golangci-lint run]

unit:
  stage: check
  script: [go test -race -coverprofile=cover.out ./...]
  coverage: '/total:\s+\(statements\)\s+(\d+.\d+)%/'
  artifacts:
    reports: { junit: report.xml }

build-image:
  stage: build
  needs: [lint, unit]                     # DAG: start as soon as these finish
  image: docker:28
  services: [docker:28-dind]
  script:
    - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

deploy-prod:
  stage: deploy
  environment: { name: production, url: https://shop.example.com }
  when: manual                            # approval gate (plus protected environments)
  id_tokens:
    AWS_ID_TOKEN: { aud: sts.amazonaws.com }   # OIDC to the cloud
  script: [./deploy.sh production $CI_COMMIT_SHA]
  rules:
    - if: $CI_COMMIT_TAG

Key concepts:

  • stages (ordered groups) and needs (a DAG that skips waiting for whole stages);
  • rules (when a job runs);
  • include and CI/CD components (a catalog of reusable pipeline pieces);
  • protected branches and variables, environments with deployment approvals;
  • merge trains;
  • GitLab Runners (shared or self-hosted, Docker/Kubernetes executors);
  • built-in security scanning templates (SAST, dependency, container, secret detection) on higher tiers.

Jenkins

Jenkins (2011, from Hudson) is the long-standing self-hosted automation server, extended by thousands of plugins:

  • Pipelines as code in a Jenkinsfile (declarative syntax, preferred, or scripted Groovy).
  • Agents run builds: static nodes, Docker containers, or ephemeral Kubernetes pods (Kubernetes plugin).
  • Shared libraries provide reusable pipeline steps across repositories.
  • Multibranch pipelines and organisation folders discover branches and PRs automatically.
  • Strengths: extremely flexible, self-hosted, huge plugin ecosystem. Costs: you operate it (upgrades, plugin compatibility, security patches, controller backups), and plugin sprawl is a security and stability risk. Configuration as Code (JCasC) keeps the controller reproducible.
Groovy
// Jenkinsfile (declarative)
pipeline {
  agent { kubernetes { yamlFile 'ci/pod.yaml' } }       // ephemeral pod with maven + docker containers
  options { timeout(time: 30, unit: 'MINUTES'); disableConcurrentBuilds() }
  stages {
    stage('Verify') {
      steps { container('maven') { sh './mvnw -B -ntp verify' } }
      post { always { junit '**/target/surefire-reports/*.xml' } }
    }
    stage('Image') {
      when { branch 'main' }
      steps { container('kaniko') { sh '/kaniko/executor --destination=registry.acme.dev/orders:${GIT_COMMIT}' } }
    }
    stage('Deploy prod') {
      when { tag 'v*' }
      input { message 'Deploy to production?'; submitter 'release-managers' }
      steps { withCredentials([string(credentialsId: 'argocd-token', variable: 'TOKEN')]) {
        sh './deploy.sh production ${GIT_COMMIT}'
      } }
    }
  }
}

TeamCity

TeamCity (JetBrains) is a CI/CD server (self-hosted or TeamCity Cloud) popular in JVM and .NET shops:

  • Build configurations grouped into projects; build chains with snapshot dependencies (all builds in a chain use the same source revision) and artifact dependencies.
  • Kotlin DSL for versioned settings (type-safe, refactorable pipelines stored in the repo), and newer YAML-like pipelines.
  • Strong test reporting: flaky test detection, test history, re-running failed tests, build failure conditions.
  • Build agents (cloud profiles for autoscaling), personal builds (run CI on uncommitted changes), and remote run from the IDE.
Kotlin
// .teamcity/settings.kts (Kotlin DSL)
object Build : BuildType({
    name = "Verify"
    vcs { root(DslContext.settingsRoot) }
    steps {
        maven { goals = "verify"; runnerArgs = "-B -ntp" }
    }
    triggers { vcs { } }
    features {
        perfmon { }
        pullRequests { provider = github { authType = vcsRoot() } }
    }
    failureConditions { testFailure = true; executionTimeoutMin = 30 }
})

Other systems

Buildkite (hosted control plane, your agents), CircleCI, Azure Pipelines, AWS CodePipeline/CodeBuild, Google Cloud Build, Tekton (Kubernetes-native pipeline CRDs), Dagger (pipelines as code in Go/Python/TypeScript running in containers, portable across CI systems), Bazel-based remote execution (BuildBuddy, EngFlow). The concepts transfer: triggers, jobs/stages, runners, caching, artefacts, secrets, environments.

Making pipelines fast and reliable

Speed

  • Parallelise: independent jobs, test sharding (go test packages, pytest -n auto, Gradle/Maven parallel forks, Playwright shards), matrix splits.
  • Cache dependencies and build outputs; use incremental and remote-cached builds (Gradle, Bazel, Nx, Turborepo).
  • Test impact analysis / affected targets: in monorepos, build and test only what changed and its dependants (Bazel, Nx affected, Turborepo filters, path filters in workflow triggers).
  • Bigger or ARM runners for CPU-bound builds; keep images pre-baked with toolchains.
  • Move slow suites (full E2E, performance) to post-merge or nightly, keeping a fast PR gate.

Flaky tests

A flaky test passes and fails on the same code. Flakiness destroys trust ("just re-run it"), hides real failures and slows everyone down.

  • Detect: track per-test pass rates across runs (TeamCity, GitLab, Buildkite Test Analytics, Trunk, Datadog CI Visibility); re-run failures automatically only to classify them, not to hide them.
  • Quarantine flaky tests (still running, not blocking), with an owner and deadline to fix.
  • Fix the causes: time and timezone dependence, ordering and shared state between tests, real network calls, race conditions and fixed sleeps (use polling/awaitility), random data without seeds, resource exhaustion on shared runners.

Securing the pipeline

The pipeline is part of your software supply chain (Vol. 10):

  • Source integrity: branch protection, required reviews, signed commits, CODEOWNERS.
  • Build integrity: ephemeral isolated runners, pinned actions and base images, hermetic builds where possible, no secrets in build steps that run untrusted code.
  • Provenance: generate SLSA build provenance attestations (GitHub artifact attestations, slsa-github-generator, GitLab provenance) and sign artefacts (cosign keyless).
  • Dependency hygiene: lockfiles, automated updates (Renovate/Dependabot) with CI, vulnerability and licence scanning, and OpenSSF Scorecard for your repository's practices.
  • Least-privilege credentials: OIDC to clouds, per-environment roles, no long-lived tokens; separate deploy permissions from build permissions.
  • Audit logs of who triggered and approved deployments.

Lab: what makes pipelines fast, trustworthy and safe

GitHub Actions workflows run locally with act 0.2.90 on the volume's 2-CPU VM, each job in a fresh golang:1.24-alpine container; a small Go module with a deliberately flaky test. Hosted runners have their own CPUs per job, so parallel speed-ups there are larger than on this shared machine.

Experiment 1: parallel jobs on a busy machine

Three jobs (vet, test, build), each from a clean container with no cache:

Text
sequential (needs:):  64.353 s
parallel (no needs):  62.202 s

Running independent jobs in parallel barely helped here, because all three compiled the Go standard library at once on two CPUs: parallelism only shortens a pipeline when there's spare capacity (separate hosted runners, a large self-hosted fleet). The deeper lesson is that each job was repeating the same expensive work, which experiment 2 fixes.

Experiment 2: caching

The same parallel workflow with a persistent Go build cache mounted into every job (what actions/cache, GitLab's cache: or a runner cache volume provides):

Text
first run (cache empty):  38.272 s
second run (cache warm):  2.388 s
cache size: 101M

Sixteen times faster with a warm cache. Every ecosystem has an equivalent: ~/.m2 or Gradle's build cache, ~/.npm, pip's cache, Docker layer caches (BuildKit --cache-from/--cache-to). Key caches by the dependency lock file so they invalidate when dependencies change, and remember caches are shared across branches and runs: never cache anything that could carry secrets or that untrusted pull requests could poison for trusted builds.

Experiment 3: flaky tests

A test that assumes an asynchronous confirmation arrives within 10 ms, and a fixed version that waits for the event with a generous deadline. 400 runs each:

Text
TestConfirmFlaky: failed 5 of 400 runs
TestConfirmFixed: failed 0 of 400 runs

1.25% sounds harmless, but a suite of 40 tests each that flaky passes only 0.9875⁴⁰ ≈ 60% of the time: four in ten pipelines would go red for no reason, and people would learn to click "re-run". Automatic retries make the pipeline green again (one retry per test raises the pass rate to about 99.4%) but hide real race conditions too. The durable fixes: wait for conditions instead of sleeping, control time and randomness in tests, isolate shared state, and quarantine known-flaky tests with an owner and a deadline while tracking flakiness per test.

Experiment 4: secrets in logs

A job prints a secret passed as ${{ secrets.DEPLOY_TOKEN }} and its length:

Text
| token is ***
| length 16

The runner masked the secret's exact value in logs, but anything derived from it (its length here; a base64 encoding, a URL containing it, a substring) isn't recognised. Masking is a last line of defence, not a control. Better: give jobs no long-lived secrets at all (OIDC federation to the cloud, chapter 89), scope permissions: of the built-in token to the minimum, require approval for environments that hold secrets, and never expose secrets to workflows triggered by pull requests from forks (pull_request_target combined with checking out the fork's code is a well-known way to leak them).

Try it yourself

  1. Add a strategy.matrix that runs the tests on two Go versions and two GOARCH values; how many jobs run?
  2. Use actions/cache keyed on hashFiles('**/go.sum') in a real GitHub repository and compare run times.
  3. Split the pipeline so pull requests run only lint and tests, and main also builds, signs and pushes the image.
  4. Pin every third-party action to a full commit SHA and add a policy check that rejects tags like @v4.

Revision sheet: CI/CD

Key ideas

  • CI / continuous delivery / continuous deployment and trunk-based development.
  • Pipeline stages: checkout, lint, test (unit, integration, contract), build, scan (SAST, dependencies, images, secrets), package and sign, publish, deploy per environment, verify, release.
  • GitHub Actions: workflows, triggers (push, pull_request, workflow_dispatch, schedules), jobs, steps, runners, matrices, needs, outputs, artifacts, caches, environments with protection rules, reusable workflows, composite actions, permissions, OIDC.
  • GitLab CI: stages, needs (DAG), rules, includes and components, runners and executors, environments.
  • Jenkins: declarative pipelines, agents, shared libraries, plugins (and their risk).
  • TeamCity: build chains, snapshot dependencies, Kotlin DSL.
  • Fast and reliable: caching, parallelism, test selection, incremental builds, remote build caches (Bazel, Gradle), flaky-test management, small pipelines.
  • Securing pipelines: least-privilege tokens, OIDC instead of secrets, pinned actions, isolated runners for untrusted code, provenance and signing (SLSA), branch protection and required reviews.

Numbers to remember

  • Lab: a clean-container pipeline took 64 s; a warm build cache took a run from 38 s to 2.4 s; a 1.25% flaky test makes a 40-test suite pass only ~60% of runs; masking hid a secret but not its length.

Pitfalls

  • Pipelines nobody trusts (flaky, slow).
  • Caches without keys, or shared with untrusted builds.
  • Long-lived cloud keys in CI secrets.
  • pull_request_target checking out fork code with secrets available.
  • Unpinned third-party actions and plugins.
  • Rebuilding artifacts per environment instead of promoting one.

Glossary

  • Runner / agent: machine executing CI jobs.
  • Matrix: generating jobs from combinations of parameters.
  • Artifact: a file produced by a job and stored or passed on.
  • Cache: reusable files (dependencies, build outputs) across runs.
  • Environment protection: approvals and rules before jobs using an environment run.
  • SLSA: supply-chain framework for build provenance levels.