Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 3

Lab: a staged pipeline with approval and smoke tests

Construct a multi-environment staged delivery pipeline featuring immutable artifact promotion, automated post-deploy smoke tests, and protected environment approval gates.

Contentsand lesson path

What you will learn

  • Build a delivery pipeline that promotes one artifact from staging to production with environment protection, approval and smoke tests.

Prerequisites: Cloud Basics, Continuous Integration

01. Staged Pipeline Architecture: From Build to Production Promotion

A core principle of continuous delivery is that an application artifact is built and packaged once, then promoted unchanged from one environment to the next. In weaker delivery systems, pipelines compile code separately for each deployment tier: a "staging build" runs, followed hours later by a "production build". Then what you tested is not what you ship: upstream dependency updates, compiler patch variations, or environment variable leaks can cause the production artifact to differ subtly from the binary validated in staging.

A staged pipeline promotes one artifact through these stages (staged environment promotion):

  • Build and Package Stage: Code committed to the mainline branch triggers automated linting, unit testing, and compilation. The pipeline builds a container image, pushes it to a registry and records its digest, the SHA-256 hash of the image manifest that identifies exactly these bytes (ghcr.io/org/web-service:v2.4.0@sha256:d8b2e5a...). A tag can be moved to another image later; a digest cannot.

  • Staging Deployment: The pipeline deploys the exact immutable image digest to the staging environment, injecting staging-specific configuration variables (staging database connection strings, third-party sandbox API credentials) at runtime.

  • Automated Smoke Testing: As soon as staging instances report ready, an automated test suite executes targeted synthetic transactions against live staging endpoints.

  • Protected Approval Gate: Once staging verification succeeds, the pipeline halts at an environment approval gate. Only designated release managers or operations leads can approve promotion to production.

  • Production Rollout: Upon approval, the pipeline pulls the exact same image digest tested in staging and deploys it to the production cluster. The bytes are identical; configuration, data and load still differ, which is why production gets its own smoke test.

Staging-to-production parity depends on a Twelve-Factor App principle: configuration is kept separate from code. The image is identical in every environment. What differs is the configuration given to the container when it starts, such as environment variables from a Kubernetes ConfigMap or database credentials from a secret store. If an artifact needs its own build flags or code changes to run in staging, production no longer runs what staging tested.

02. Designing Honest Post-Deploy Smoke Tests

After a deployment, how does the pipeline know that it worked before users or the next stage depend on it? A Pod marked "Running" is not enough: the process can start and still fail to reach its database or serve a broken TLS certificate.

The usual answer is a smoke test: a short set of checks that runs right after each deployment and tries what a user would notice first. It is end-to-end, because it goes through the real network path to the real service and its dependencies, and shallow, because it covers only the main paths, not every feature. A good smoke test has three parts:

  1. Deep Health Checks (/healthz/deep or similar): Unlike a shallow liveness probe that only asserts the web server process is accepting connections, a deep check called by the smoke test runs real dependency checks (querying PostgreSQL SELECT 1, pinging the Redis cache, and checking object storage access). Keep such checks out of the Kubernetes readiness probe: a short database outage would then mark every replica unready at once.

  2. Synthetic Authentication and Critical Path Execution: The smoke test runner logs in using an automated service account, performs a critical business transaction (such as fetching user profile data or creating an ephemeral test cart), and asserts that the HTTP response code is 200 with valid JSON schema payloads.

  3. Fast Execution Window: A smoke test suite should finish in about a minute. It is not an exhaustive regression or load testing suite; slow test suites delay emergency rollbacks and lead developers to bypass verification gates.

The lab below builds this pipeline for real.

03. Lab: Build Once, Stage, Approve and Promote

You will build a pipeline that builds a container image once, deploys that exact digest to a staging environment, smoke-tests it, waits for a person to approve, deploys the same digest to production, smoke-tests again and rolls back automatically if production fails.

What you need. A public GitHub repository (call it web-delivery): on GitHub Free, Pro and Team plans, required reviewers on environments work only for public repositories. Locally you need Python 3.11 or later and curl to test the smoke script; Docker is not needed on your machine. To keep the lab self-contained, each "environment" is a container started on the job's runner by scripts/deploy.sh; against a real cluster that script would run kubectl set image instead, and the rest of the pipeline stays the same.

Layout: app.py, Dockerfile, scripts/smoke-test.sh, scripts/deploy.sh, .github/workflows/delivery.yml.

  1. Write the service. It has a health endpoint and one read endpoint. APP_BROKEN=1 makes the read endpoint fail, which you will use to simulate a bad release.
Python · app.py
"""Tiny web service for the staged-delivery lab (standard library only)."""
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

VERSION = os.environ.get("APP_VERSION", "dev")
BROKEN = os.environ.get("APP_BROKEN") == "1"  # simulates a bad config or release


class Handler(BaseHTTPRequestHandler):
    def _send(self, status, body):
        data = json.dumps(body).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/healthz":
            self._send(200, {"status": "ok", "version": VERSION})
        elif self.path == "/api/items" and not BROKEN:
            self._send(200, {"items": [{"id": 1, "name": "widget"}]})
        elif self.path == "/api/items":
            self._send(500, {"error": "database unavailable"})
        else:
            self._send(404, {"error": "not found"})

    def log_message(self, *args):  # keep the job log quiet
        pass


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "8080"))
    ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()
  1. Write the Dockerfile. The base image is pinned by digest, so rebuilding later cannot silently pick up a different base.
Dockerfile · Dockerfile
# python:3.13-slim, pinned by digest (resolved 2026-10-30)
ARG BASE_DIGEST=sha256:2d44738ebf4ce5f63b9d9ea871e9c7cfdc0426f7b0c97cac915fd88ded1d86bb
FROM python:3.13-slim@${BASE_DIGEST}
WORKDIR /app
COPY app.py .
ARG APP_VERSION=dev
ENV APP_VERSION=${APP_VERSION} PORT=8080
USER nobody
EXPOSE 8080
CMD ["python", "app.py"]
  1. Write the smoke test. It waits up to 60 seconds for /healthz, then exercises a critical read path. A health check alone is not enough: in step 4 the broken service still answers /healthz.
Bash · scripts/smoke-test.sh
#!/usr/bin/env bash
# Usage: smoke-test.sh <base-url>. Exits non-zero unless the service works.
set -euo pipefail
BASE_URL="${1:?usage: smoke-test.sh <base-url>}"
DEADLINE=$((SECONDS + 60))

# 1. Wait up to 60 s for the health endpoint
until curl -fsS --max-time 2 "${BASE_URL}/healthz" > /dev/null 2>&1; do
  if (( SECONDS >= DEADLINE )); then
    echo "SMOKE FAIL: ${BASE_URL}/healthz not healthy after 60 s" >&2
    exit 1
  fi
  sleep 2
done
echo "SMOKE OK: /healthz -> $(curl -fsS --max-time 2 "${BASE_URL}/healthz")"

# 2. Exercise a critical read path, not only the health check
if ! BODY=$(curl -fsS --max-time 5 "${BASE_URL}/api/items" 2>&1); then
  echo "SMOKE FAIL: GET /api/items: ${BODY}" >&2
  exit 1
fi
if ! grep -q '"items"' <<< "${BODY}"; then
  echo "SMOKE FAIL: unexpected body: ${BODY}" >&2
  exit 1
fi
echo "SMOKE OK: /api/items -> ${BODY}"
  1. Test the smoke script locally, once against a healthy service and once against a broken one. Run chmod +x scripts/*.sh first.
Bash · Step 4: smoke test, healthy and broken
PORT=8080 python3 app.py & GOOD=$!
./scripts/smoke-test.sh http://localhost:8080
kill "$GOOD"
APP_BROKEN=1 PORT=8081 python3 app.py & BAD=$!
./scripts/smoke-test.sh http://localhost:8081; echo "exit: $?"
kill "$BAD"
Expected output
SMOKE OK: /healthz -> {"status": "ok", "version": "dev"}
SMOKE OK: /api/items -> {"items": [{"id": 1, "name": "widget"}]}
SMOKE OK: /healthz -> {"status": "ok", "version": "dev"}
SMOKE FAIL: GET /api/items: curl: (22) The requested URL returned error: 500
exit: 1
  1. Write the deploy script. It replaces the container for one environment with the given image reference.
Bash · scripts/deploy.sh
#!/usr/bin/env bash
# Usage: deploy.sh <environment> <host-port> <image-ref>
# Stand-in for a real deployment: runs the image as a container on the job's
# runner. Against a cluster you would run, for example:
#   kubectl set image deployment/web web="<image-ref>"
set -euo pipefail
ENV_NAME="$1"; PORT="$2"; IMAGE="$3"
docker rm -f "web-${ENV_NAME}" > /dev/null 2>&1 || true
docker run -d --name "web-${ENV_NAME}" -p "${PORT}:8080" \
  -e APP_BROKEN="${APP_BROKEN:-0}" "${IMAGE}" > /dev/null
echo "Deployed ${IMAGE} to ${ENV_NAME} on port ${PORT}"
  1. Write the workflow. The build job pushes the image once and passes its digest to later jobs through a job output. Both deploy jobs check out the repository (so the scripts exist), log in to GHCR with the job's GITHUB_TOKEN, and deploy image@digest, never a tag. After a successful production smoke test, the workflow moves the :production tag to the new digest; that tag is the last known-good release, and the rollback step redeploys it when the production smoke test fails. Every action is pinned to a commit SHA with its release tag as a comment. docker/setup-buildx-action is optional for a single-platform build, so it is left out.
YAML · .github/workflows/delivery.yml
name: staged-delivery

on:
  push:
    branches: [main]

permissions:
  contents: read

env:
  IMAGE: ghcr.io/${{ github.repository }}  # must be lower case

jobs:
  build:
    runs-on: ubuntu-24.04
    permissions:
      contents: read
      packages: write
    outputs:
      digest: ${{ steps.build.outputs.digest }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Build and push once; the digest is the release identity
        id: build
        uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
        with:
          context: .
          push: true
          tags: ${{ env.IMAGE }}:${{ github.sha }}
          build-args: APP_VERSION=${{ github.sha }}

  deploy_staging:
    needs: build
    runs-on: ubuntu-24.04
    environment: staging
    permissions:
      contents: read
      packages: read
    env:
      DIGEST: ${{ needs.build.outputs.digest }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Deploy the built digest to staging
        run: ./scripts/deploy.sh staging 8080 "${IMAGE}@${DIGEST}"
      - name: Smoke test staging
        run: ./scripts/smoke-test.sh http://localhost:8080

  deploy_production:
    needs: [build, deploy_staging]
    runs-on: ubuntu-24.04
    environment: production  # required reviewers: the job waits for approval
    permissions:
      contents: read
      packages: write  # to move the :production tag
    env:
      DIGEST: ${{ needs.build.outputs.digest }}
    steps:
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Deploy the same digest to production
        env:
          APP_BROKEN: ${{ vars.BREAK_PRODUCTION }}  # drill switch, normally unset
        run: ./scripts/deploy.sh production 8081 "${IMAGE}@${DIGEST}"
      - name: Smoke test production
        id: smoke
        run: ./scripts/smoke-test.sh http://localhost:8081
      - name: Mark this digest as the last known-good release
        run: >-
          docker buildx imagetools create
          -t "${IMAGE}:production" "${IMAGE}@${DIGEST}"
      - name: Roll back to the last known-good release
        if: failure() && steps.smoke.outcome == 'failure'
        run: |
          ./scripts/deploy.sh production 8081 "${IMAGE}:production"
          ./scripts/smoke-test.sh http://localhost:8081
  1. Create the environments, then push. In the repository, open Settings → Environments → New environment and create staging with no rules. Create production, tick Required reviewers, add yourself and save. (Tick Prevent self-review only if a second person will approve.) Commit all files to main and push.

  2. Watch the run under Actions. You should see build and deploy_staging finish, with the two SMOKE OK lines from step 4 in the staging smoke-test log (the version is the commit SHA). deploy_production then shows Waiting for review; nothing runs and no production secrets are available to it until you click Review deployments and approve. Secrets stored in an environment reach only jobs that name that environment, and only after approval. As the only reviewer you approve your own runs, so the gate gives you a pause to check staging, not a second opinion; for that, add a second reviewer and tick Prevent self-review. After approval, the production smoke test passes and the package page for web-delivery shows a production tag on the same digest that staging tested.

  3. Rollback drill. Only after one successful run (so :production exists), add a repository variable BREAK_PRODUCTION with value 1 under Settings → Secrets and variables → Actions → Variables. It stands in for a release whose bug only shows in production. Push an empty commit (git commit --allow-empty -m drill && git push) and approve again. The production smoke test fails, the rollback step redeploys :production and its smoke test passes, and the run still ends red so someone looks at it. Delete the variable afterwards.

Illustrative output · deploy_production job log during the drill (your digests and SHAs differ)
Deployed ghcr.io/<owner>/web-delivery@sha256:<new digest> to production on port 8081
SMOKE OK: /healthz -> {"status": "ok", "version": "<new commit sha>"}
SMOKE FAIL: GET /api/items: curl: (22) The requested URL returned error: 500
Error: Process completed with exit code 1.
Deployed ghcr.io/<owner>/web-delivery:production to production on port 8081
SMOKE OK: /healthz -> {"status": "ok", "version": "<previous commit sha>"}
SMOKE OK: /api/items -> {"items": [{"id": 1, "name": "widget"}]}

04. Check your understanding

Practice check · 3 questions

Digest hand-off, the production tag and reviewers

Three questions on the lab workflow.

Q1. In the lab workflow, how does the production job know which image to deploy?
Q2. Why does the lab move the `:production` tag only after the production smoke test has passed?
Q3. In the lab you are the only required reviewer of `production`, you push every commit yourself, and **Prevent self-review** is off. What does the approval step give you?
Practice only: not graded, not saved, not evidence.

05. Apply it

Make the smoke test check which build it is talking to, and watch a staging failure stop the pipeline. This takes about 30 minutes with the web-delivery repository from the lab.

  1. Give scripts/smoke-test.sh an optional second argument, the expected version. When it is set, the script prints SMOKE FAIL: version is <actual>, expected <expected> and exits 1 unless /healthz reports that version. Test it locally first: start app.py with APP_VERSION=abc, then run the script once with abc and once with xyz.
  2. In both deploy jobs, pass "${GITHUB_SHA}" as the second argument; the image was built with APP_VERSION=${{ github.sha }}, so the versions should match. Leave the rollback step's smoke test without it, because :production holds an older commit.
  3. Add a repository variable BREAK_STAGING and pass it to the staging deploy step as APP_BROKEN, the same way the drill does for production. Set it to 1, push an empty commit and check the run: deploy_staging fails, deploy_production is skipped without asking for a review, and the production tag on the package page has not moved. Delete the variable afterwards.

Produce: the changes to the two files and the links to the two runs, plus one sentence on what the version check catches that /healthz alone does not (for example, an old container that is still answering on the same port).

06. Review prompt

Explain why rebuilding binaries between staging and production means production no longer runs what staging tested. Outline the essential design requirements of an automated post-deployment smoke test suite, and describe how protected environment approval rules enforce secure credential isolation in modern CI/CD pipelines.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check