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
On this page
- Staged Pipeline Architecture: From Build to Production Promotion
- Designing Honest Post-Deploy Smoke Tests
- Lab: Build Once, Stage, Approve and Promote
- Check your understanding
- Apply it
- Review prompt
Lessons of CD Strategies
- Delivery, deployment and rollout strategies: how each one fails Concept · 25 min
- Lab: a staged pipeline with approval and smoke tests Lab · 30 min
- Lab: a TLS-terminating reverse proxy in front of the service Lab · 30 min
- Lab: blue-green cutover and rollback behind the proxy Lab · 25 min
- Schema changes, feature flags, GitOps, traffic splitting and service meshes Concept · 30 min
- Check: choose and defend a release plan Knowledge check · 10 questions
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:
-
Deep Health Checks (
/healthz/deepor 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 PostgreSQLSELECT 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. -
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.
-
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.
- Write the service. It has a health endpoint and one read endpoint.
APP_BROKEN=1makes the read endpoint fail, which you will use to simulate a bad release.
"""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()- Write the Dockerfile. The base image is pinned by digest, so rebuilding later cannot silently pick up a different base.
# 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"]- 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.
#!/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}"- Test the smoke script locally, once against a healthy service and once against a broken one. Run
chmod +x scripts/*.shfirst.
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"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- Write the deploy script. It replaces the container for one environment with the given image reference.
#!/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}"- Write the workflow. The
buildjob 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'sGITHUB_TOKEN, and deployimage@digest, never a tag. After a successful production smoke test, the workflow moves the:productiontag 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-actionis optional for a single-platform build, so it is left out.
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-
Create the environments, then push. In the repository, open Settings → Environments → New environment and create
stagingwith no rules. Createproduction, tick Required reviewers, add yourself and save. (Tick Prevent self-review only if a second person will approve.) Commit all files tomainand push. -
Watch the run under Actions. You should see
buildanddeploy_stagingfinish, with the twoSMOKE OKlines from step 4 in the staging smoke-test log (the version is the commit SHA).deploy_productionthen 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 forweb-deliveryshows aproductiontag on the same digest that staging tested. -
Rollback drill. Only after one successful run (so
:productionexists), add a repository variableBREAK_PRODUCTIONwith value1under 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:productionand its smoke test passes, and the run still ends red so someone looks at it. Delete the variable afterwards.
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
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.
- Give
scripts/smoke-test.shan optional second argument, the expected version. When it is set, the script printsSMOKE FAIL: version is <actual>, expected <expected>and exits 1 unless/healthzreports that version. Test it locally first: startapp.pywithAPP_VERSION=abc, then run the script once withabcand once withxyz. - In both deploy jobs, pass
"${GITHUB_SHA}"as the second argument; the image was built withAPP_VERSION=${{ github.sha }}, so the versions should match. Leave the rollback step's smoke test without it, because:productionholds an older commit. - Add a repository variable
BREAK_STAGINGand pass it to the staging deploy step asAPP_BROKEN, the same way the drill does for production. Set it to1, push an empty commit and check the run:deploy_stagingfails,deploy_productionis skipped without asking for a review, and theproductiontag 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.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.