Docker Hour 5: Image CI, Supply Chain and Release
- Draw a complete image release chain (build → test → push candidate → scan → sign/attest → promote and deploy → verify), say which class of incident each step prevents, and which foundation each of the first four hours laid.
- Choose the right BuildKit cache backend for CI (registry / gha / local), understand
mode=max, scopes and theimage-manifest=truethat ECR requires, and use a Bake file to declare a single-platform test build and a multi-platform release build. - Write a platform-neutral image CI: Bake + Makefile hold all the logic, GitHub Actions only triggers and logs in to ACR / ECR with OIDC; be able to move the same logic to GitLab CI, Azure Pipelines and Jenkins.
- Design a tagging and promotion strategy: the roles of git sha / semver / digest, ACR locking vs ECR immutable tags, promoting the same digest across environments and registries, and retention/cleanup policies that never delete images in production.
- Generate and read SBOM and provenance (buildx attestations), run a scan gate with pinned versions of Trivy / Grype / Docker Scout (without mounting docker.sock), and manage the vulnerability baseline with VEX and exceptions that expire.
- Sign digests with cosign (keyless and KMS keys) and Notation (Azure Key Vault / AWS Signer, ECR managed signing), verify before deployment and deploy by digest.
- Implement safe release and automatic rollback in the pipeline: Container Apps multiple revisions 0% → smoke test → 10% → 100%; ECS native blue/green / rolling + circuit breaker + CloudWatch alarm rollback; know that configuration changes do not roll back with the image.
1-hour schedule
| # | Time | Module | Core content | Animation / interaction | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: registries in two clouds & a repo | Reuse rg-docker-hour3 (ACR, ACA) from hour 3 and ca-central-1 (ECR, ECS) from hour 4; install the buildx plugin, cosign and ORAS; create the GitHub repo docker-hour5-myapp | Environment self-check list | Tool and login self-check |
| 1 | 00–06 | From manual release to pipeline: the big picture | Seven steps and the defense each provides, recap of the first four hours, "build once, promote everywhere", release record (commit ↔ digest ↔ revision) | One release through seven gates (five failures) | Run the release chain by hand and record the digest |
| 2 | 06–14 | BuildKit & buildx in depth | Builder drivers, cache backends registry / gha / local, mode=min|max, ECR cache parameters, multi-platform (QEMU / native / cross-compile), Bake files and --print | Cache hit simulator (backend × change × runner) | Write docker-bake.hcl, compare cold/warm cache |
| 3 | 14–22 | Platform-neutral image CI ⭐ | Makefile target contract, minimal GitHub Actions OIDC login to ACR / ECR, build-once-push-twice, GitLab CI / Azure Pipelines / Jenkins comparison | OIDC token exchange (Azure / AWS, four failures) | Build on push: one digest appears in both ACR and ECR |
| 4 | 22–29 | Tags, versions and promotion | sha / semver / digest, ACR locking vs ECR immutability (with exclusions), environment manifests pinned to digests, cross-registry copy, retention and cleanup | Promotion simulator: the same digest through dev → staging → prod | Promote v1.5.0 and verify the digest is unchanged |
| 5 | 29–37 | SBOM, provenance and vulnerability scanning | buildx attestations, SPDX, SLSA provenance, Trivy / Grype / Scout (pinned versions, no docker.sock), severity gate, VEX and expiring exceptions | Scan gate: how to handle five outcomes | Extract the SBOM from the image and scan the SBOM |
| 6 | 37–43 | Signing and verification | cosign keyless (Fulcio / Rekor) and KMS keys, Notation + Key Vault / AWS Signer, ECR managed signing, deploy by digest, where the verification gate sits | Sign → verify → deploy (five failures) | Keyless signing and verification before deployment |
| 7 | 43–51 | Release and rollback | ACA multi-revision traffic split and label URLs, ECS native blue/green / rolling + circuit breaker + alarm rollback, smoke tests, the minimal set of release signals | Traffic shift and automatic rollback (two clouds × four outcomes) | Pipeline-driven canary and rollback drill |
| 8 | 51–60 | Five-hour recap, self-test and cleanup | Knowledge map of the five hours, ten common mistakes, interactive troubleshooting tree, cleaning up all cloud resources from Hours 3–5 | Five-hour flashcards + interactive troubleshooting tree | Clean up Azure / AWS / GitHub resources |
| — | After class | Cheat sheet · Capstone lab | myapp 1.5.0: one commit → same digest in both registries → scan → sign → staging → prod canary → rollback drill → cleanup | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / objects | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Release chain and defenses | ✓ | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | --metadata-file, release record | M1 lab |
| BuildKit cache and multi-platform | · | ✓ | ✓ | · | · | · | · | ✓ | --cache-to type=registry|gha|local, --platform | M2 lab |
| Declarative builds with Bake | · | ✓ | ✓ | ✓ | ✓ | · | · | ✓ | docker buildx bake --print, target/group | M2 / M3 lab |
| Secretless CI login to registries | · | · | ✓ | · | · | ✓ | ✓ | ✓ | azure/login, configure-aws-credentials, id-token: write | M3 lab |
| Tags, immutability and promotion | ✓ | · | ✓ | ✓ | · | ✓ | ✓ | ✓ | imagetools create, --write-enabled false, IMMUTABLE_WITH_EXCLUSION | M4 lab |
| SBOM / provenance | · | ✓ | · | · | ✓ | ✓ | · | ✓ | --sbom, --provenance=mode=max, imagetools inspect --format | M5 lab |
| Vulnerability scanning and exceptions | ✓ | · | ✓ | · | ✓ | · | · | ✓ | trivy image --exit-code 1, grype sbom:, .trivyignore.yaml | M5 lab |
| Signing and verification | ✓ | · | · | ✓ | · | ✓ | ✓ | ✓ | cosign sign/verify, notation sign/verify, put-signing-configuration | M6 lab |
| Release and rollback | ✓ | · | · | ✓ | · | · | ✓ | ✓ | az containerapp ingress traffic set, ECS deploymentConfiguration | M7 lab |
What this hour leaves out (and where to learn it)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| GitHub Actions syntax, OIDC trust-chain details (subject format, immutable subject, environment approvals, deployment protection rules) | This hour only gives a "minimal working" OIDC login snippet for image CI | GitHub hour 3 · OIDC → Entra ID (Chinese) · Hour 4 · OIDC → IAM (Chinese) · environments and approvals (Chinese) |
| Managing ACR, ACA, ECR and ECS with Bicep / Terraform | That is infrastructure as code; this hour only fills in a few resources with the CLI | Terraform in 8 hours (Chinese) · GitHub hour 3 · IaC pipeline (Chinese) |
| Metrics, log queries, alert rules, SLOs and dashboards (KQL / Application Insights / CloudWatch / Prometheus) | This hour only defines "the minimal signals a release decision needs" | Prometheus & Grafana in 8 hours (Chinese) (hour 3 Azure, hour 4 AWS); for cloud troubleshooting see this course's Hour 3 Module 6 / Hour 4 Module 6 |
| Kubernetes admission control (Ratify, Kyverno, Sigstore policy-controller, ValidatingAdmissionPolicy) | This hour only shows where the "cluster-side verification point" is | Kubernetes hour 5 · Admission control (Chinese) |
Remote / cloud builders, reproducible builds (SOURCE_DATE_EPOCH), Bake matrices | That is "build at scale"; this hour only uses cache and multi-platform | Hour 7 Module 5: Build at scale |
| Writing Dockerfiles, tag generators, why Actions are pinned by SHA, runtime hardening | Covered in hour 2; used directly here | Hour 2 Module 6 · Module 7 |
| Database migrations and multi-service release orchestration | That is application architecture | Hour 6 Module 5 |
How to use this courseware
Concepts · Diagram · Animation · Commands · Lab · In Production · Troubleshooting · Quiz · Audio · Video. Every animation includes "failure branches": pick a failure scenario first to see at which gate the pipeline stops, then go to the "Troubleshooting" tab to compare with the real error.
A quiz score ≥ 70% or clicking "Mark this module complete" counts toward progress. It is saved in this browser (shared with the course index under one progress key; if local storage is blocked it is cleared on refresh).
The "Audio" tab reads the scripts aloud with the browser's built-in Web Speech API (en-US); without an English voice the scripts can still be read or fed to a TTS tool.
Module 0 · Setup: registries in two clouds & a repo (before class)
- You have completed Hour 2 (myapp's production-grade Dockerfile: multi-stage, non-root,
HEALTHCHECK, Flask listening on 5000, serving/and/healthz, readingAPP_VERSION). - Azure track: the Hour 3 file
~/hour3.env(RG=rg-docker-hour3,LOC=canadacentral,ACR,ENV=cae-docker-lab,APP=myapp,KV,FQDN). - AWS track: the Hour 4 file
~/hour4-aws.env(AWS_PROFILE=docker-lab,AWS_REGION=ca-central-1,ECR,REPO=myapp,CLUSTER=ecs-docker-lab,SVC=myapp, ALB and target group variables). - Lab machine: the Ubuntu VM from hour 1 (or any Linux with Docker Engine 29.x), with Azure CLI / AWS CLI v2,
jq,gh,gitandmakeinstalled.
Step 1: Check the Docker, buildx and BuildKit versions
docker version --format 'engine={{.Server.Version}} client={{.Client.Version}}'
docker buildx version
docker buildx ls
docker info --format 'storage-driver={{.Driver}}'
engine=29.10.0 client=29.10.0 github.com/docker/buildx v0.39.0 1f7c… NAME/NODE DRIVER/ENDPOINT STATUS BUILDKIT PLATFORMS default* docker \_ default \_ default running v0.35.0 linux/amd64, linux/amd64/v2, linux/386 storage-driver=overlayfs
Starting with Docker Engine 29, fresh installs use the containerd image store by default (the storage driver shows as overlayfs), so you can --load multi-platform images and attestations directly; older installs that were upgraded may still use overlay2 (the classic store). The differences are covered in Module 2.
Step 2: Install the CLIs used in this hour (pinned versions)
set -euo pipefail
mkdir -p ~/bin ~/tmp/dl && cd ~/tmp/dl
COSIGN_VERSION=v3.1.4 ORAS_VERSION=1.4.0
curl -fsSLO "https://github.com/sigstore/cosign/releases/download/${COSIGN_VERSION}/cosign-linux-amd64"
curl -fsSLO "https://github.com/sigstore/cosign/releases/download/${COSIGN_VERSION}/cosign_checksums.txt"
grep ' cosign-linux-amd64$' cosign_checksums.txt | sha256sum -c -
install -m 0755 cosign-linux-amd64 ~/bin/cosign
curl -fsSLO "https://github.com/oras-project/oras/releases/download/v${ORAS_VERSION}/oras_${ORAS_VERSION}_linux_amd64.tar.gz"
curl -fsSLO "https://github.com/oras-project/oras/releases/download/v${ORAS_VERSION}/oras_${ORAS_VERSION}_checksums.txt"
grep " oras_${ORAS_VERSION}_linux_amd64.tar.gz$" "oras_${ORAS_VERSION}_checksums.txt" | sha256sum -c -
tar -xzf "oras_${ORAS_VERSION}_linux_amd64.tar.gz" -C ~/bin oras
export PATH="$HOME/bin:$PATH"; cosign version | grep GitVersion; oras version | head -1
cosign-linux-amd64: OK oras_1.4.0_linux_amd64.tar.gz: OK GitVersion: v3.1.4 Version: 1.4.0
The scanners (Trivy 0.76.2, Grype 0.122.0, Syft 1.57.2, Docker Scout 1.29.0) run in Module 5 as container images with pinned versions, so there is nothing to install. Notation 1.3.2 is needed only on the Notation track in Module 6, and the install steps are given there.
Step 3: The variables file ~/hour5.env
cat > ~/hour5.env <<'EOF'
# hour 5: collects the variables from hour 3 (Azure) and hour 4 (AWS); a cloud you did not use is skipped
[ -f ~/hour3.env ] && source ~/hour3.env
[ -f ~/hour4-aws.env ] && source ~/hour4-aws.env
export PATH="$HOME/bin:$PATH"
export GH_REPO_NAME=docker-hour5-myapp
export ID_CI=id-github-ci # Azure: user-assigned managed identity dedicated to CI
export AWS_CI_ROLE=docker-hour5-gha # AWS: IAM role dedicated to CI
[ -n "${ACR:-}" ] && export ACR_LOGIN=${ACR}.azurecr.io
EOF
source ~/hour5.env
echo "ACR_LOGIN=${ACR_LOGIN:-(Azure not used)} ECR=${ECR:-(AWS not used)}"
Step 4: Confirm (or minimally rebuild) the registries and runtime environments
Azure (Hour 3)
source ~/hour5.env az group show -n $RG --query properties.provisioningState -o tsv az acr show -n $ACR --query loginServer -o tsv az containerapp show -g $RG -n $APP --query properties.latestRevisionName -o tsv # Deleted? Minimal rebuild (about 5 minutes; Redis is not rebuilt, the page shows hits=N/A) # az group create -n $RG -l $LOC # az acr create -g $RG -n $ACR --sku Standard # az containerapp env create -g $RG -n $ENV -l $LOC # Then rebuild id-myapp (AcrPull) and the myapp app following hour 3 Module 3
AWS (Hour 4)
source ~/hour5.env aws sts get-caller-identity --query Account --output text aws ecr describe-repositories --repository-names $REPO \ --query 'repositories[0].[repositoryUri,imageTagMutability]' --output text aws ecs describe-services --cluster $CLUSTER --services $SVC \ --query 'services[0].[status,deploymentController.type]' --output text # Deleted? The ECR repo is one command; rebuild the ECS service following hour 4 Module 3 (needed in Module 7) # aws ecr create-repository --repository-name $REPO \ # --image-tag-mutability IMMUTABLE --tags $TAG_KV
Succeeded acrhour312345.azurecr.io myapp--v13 111122223333 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp IMMUTABLE ACTIVE ECS
Step 5: Create a GitHub repo (a copy of myapp)
source ~/hour5.env; cd ~/myapp git init -q 2>/dev/null || true; git branch -M main printf '.env\nsecrets/\n__pycache__/\n*.tar\nbuild-meta*.json\nsbom*.json\n' >> .gitignore git add -A && git commit -qm "myapp for hour 5" || true gh repo create "$GH_REPO_NAME" --private --source . --push export GH_REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner) echo "export GH_REPO=$GH_REPO" >> ~/hour5.env; echo "$GH_REPO"
If you create the repo after July 15, 2026, GitHub by default uses an "immutable subject" in the OIDC token that includes the owner ID and repository ID. In Module 3 this hour reads the actual format with gh api; the reasoning is in GitHub hour 3 Module 2 (Chinese).
Warm-up: answer from memory (30 seconds)
Hour 2: What is the difference between an image tag and a digest? Why should deployments prefer the digest?
A tag is a mutable pointer to a manifest; the same myapp:1.4 can be pushed again. A digest (sha256:…) is the hash of the manifest content and stays the same as long as the content does. Only by referencing the digest at deploy time can you guarantee that what was "tested, scanned and signed" is the same bytes as what is "running". Modules 4 and 6 of this hour build on this.
Hour 3: On Container Apps, how do you keep a new version from receiving traffic at first?
Switch the revision mode to multiple, deploy the new revision, give it 0% weight with az containerapp ingress traffic set, and add a label to it so you can test it on its own via the label URL. Module 7 puts these steps into the pipeline.
Hour 4: What does the ECS deployment circuit breaker do?
During a rolling deployment, if new tasks keep failing to start or fail health checks, the circuit breaker marks the deployment FAILED and, with rollback=true, returns to the last successful (COMPLETED) deployment. Module 7 adds rollback triggered by CloudWatch alarms.
Module 1 · From manual release to pipeline: the big picture
- Name the seven steps of an image release in order: build → test → push candidate → scan → sign/attest → promote and deploy → verify, and the type of incident each one stops.
- Explain why a pipeline should build only once and have every environment reference the same digest afterwards, and why "push a candidate first, then scan and sign" is more reliable than "scan locally first".
- Place the commands from Hours 1–4 at the right point in this chain, and write a traceable release record for a release (commit ↔ digest ↔ revision / task definition).
What: what an image release chain is made of
In the first four hours, a release was "a human typing commands": docker build → docker push → az containerapp update or aws ecs update-service. It works, but it cannot answer the four questions production cares about most: where did this image come from (which commit, which build system), what is inside it (dependencies and vulnerabilities), has it been swapped (tag overwritten, registry tampered with), and how do we back out if it breaks (roll back to which exact version). An image release pipeline turns these four questions into gates a machine can check.
| # | Step | Artifact / check | Incident it stops | Where in this hour · prerequisites |
|---|---|---|---|---|
| 1 | Build | BuildKit produces the image + build metadata (--metadata-file) | "Works on my machine", slow builds leading people to bypass the process | Module 2 · Hour 1 Module 4, Hour 2 Module 3 |
| 2 | Test | Container-level smoke test (/healthz, non-root, port) | Images that build but don't start | Module 3 · Hour 2 Module 8 review script |
| 3 | Push candidate | Immutable sha-<short commit> tag → yields the digest | Overwritten tags, what was scanned differs from what runs | Modules 3, 4 · Hour 3 ACR, Hour 4 ECR |
| 4 | Scan | SBOM + vulnerability report, gated by severity | Going live with known high-severity vulnerabilities | Module 5 · Hour 2 Module 7 |
| 5 | Sign / attest | Signature over the digest, provenance (who built it, where) | Images of unknown origin, an impersonated build system | Modules 5, 6 |
| 6 | Promote and deploy | Environment manifests pin the digest; deploy after verifying the signature | What staging tested is not what prod runs | Modules 4, 7 · Hour 3 Module 5, Hour 4 Module 5 |
| 7 | Verify | Smoke tests, progressive traffic shift, automatic rollback | A bad version hitting every user | Module 7 |
Why: why "build once, promote by digest"
If each environment builds on its own, the results can differ even with the same Dockerfile and commit: the base image tag was updated between the two builds, pip install pulled a new minor version, a build timestamp was written into a file. The image staging tested and the image prod runs are then not the same bytes, and the test results no longer hold. The approach: the pipeline builds once, pushes the result as an immutable candidate tag and obtains the digest; from then on scanning, signing and deploying to every environment all reference that digest. What gets "promoted" between environments is only the metadata that points to it (environment manifests, semantic version tags), not a rebuild.
How: the data flow of one release
- A developer merges a PR; CI exchanges OIDC for short-lived cloud credentials (Module 3), with no long-lived passwords.
docker buildx bakebuilds a single-platform test image with the shared cache,--loads it, and runs a container-level smoke test (Modules 2, 3).- The same Bake file builds the multi-platform release image with SBOM and provenance, pushes it to
sha-3f9a2c1in ACR / ECR, writesbuild-meta.json, and the digest is read from it (Modules 2, 5). - The scanner pulls by digest from the registry and scans; above the threshold it fails. Once it passes, the digest is signed (Modules 5, 6).
- The deploy job first runs
cosign verify/notation verify, then writesmyapp@sha256:…into the environment manifest and deploys to staging; once that passes, the same digest is promoted to prod (Modules 4, 7). - prod ramps 0% → 10% → 100%; if signals turn bad it automatically rolls back to the digest in the previous release record (Module 7).
When: when it's worth doing all of it
As soon as an image goes into a shared environment (even just the team's dev), do at least steps 1–3 and 6: build once, push immutable tags, deploy by digest — the cost is almost zero. Scanning and signing must be in place before an image enters staging / prod; for external customers, regulated industries, or when Kubernetes admission policies are involved, provenance and signature verification are hard requirements.
:latest or :prod is more convenient" — when Container Apps scales out, new replicas resolve the tag again, so after the tag is overwritten one revision may run two versions of the code (since 2024 ECS resolves tags to digests at deploy time, but the tag itself is still not auditable). ③ "Signing finds vulnerabilities" — a signature only proves "who vouched for which digest", not that the content is safe; you need both scanning and signing. ④ "The more complex the pipeline, the safer" — every gate needs a clear failure handling and exception process, otherwise the team will find ways around it.Architecture: seven steps and two clouds
Comparison: manual release vs pipeline release
Interactive simulator: one release through seven gates
Pick a scenario and press play. The success scenario passes all seven gates; failure scenarios stop at the corresponding gate, and the terminal below shows that gate's real command and typical output (example).
Commands in this module (all from the first four hours, used differently)
| Command | Purpose | Position in the chain |
|---|---|---|
docker buildx build --metadata-file meta.json … | Writes the digest, build ref and other metadata (JSON) when the build finishes | ① / ③: no more guessing the digest with docker inspect |
jq -r '."containerimage.digest"' meta.json | Extracts the digest after the push | Input from ③ → ④⑤⑥ |
docker buildx imagetools inspect REF | Shows the index, per-platform manifests and attestations in the registry | ③ verify the push result |
git rev-parse --short=7 HEAD / git describe --tags | Candidate tag and version number | ③ / ⑥ |
az containerapp show … --query "properties.template.containers[0].image" | The image reference Container Apps is currently running | ⑦ release record |
aws ecs describe-tasks … --query 'tasks[].containers[].imageDigest' | The digest ECS tasks are actually running | ⑦ release record |
Turning a manual release into a release "with evidence"
source ~/hour5.env; cd ~/myapp
SHA=$(git rev-parse --short=7 HEAD)
REG=${ACR_LOGIN:-$ECR} # pick either cloud
docker buildx build --platform linux/amd64 \
--build-arg APP_VERSION="sha-$SHA" \
--label org.opencontainers.image.revision="$(git rev-parse HEAD)" \
--label org.opencontainers.image.source="https://github.com/$GH_REPO" \
-t "$REG/myapp:sha-$SHA" --metadata-file build-meta.json --push .
DIGEST=$(jq -r '."containerimage.digest"' build-meta.json); echo "$DIGEST"
docker buildx imagetools inspect "$REG/myapp@$DIGEST"
sha256:9c1e4b7a2f…d81
Name: acrhour312345.azurecr.io/myapp@sha256:9c1e4b7a2f…d81
MediaType: application/vnd.oci.image.index.v1+json
Digest: sha256:9c1e4b7a2f…d81
Manifests:
Name: acrhour312345.azurecr.io/myapp@sha256:51a0…
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: linux/amd64
Name: acrhour312345.azurecr.io/myapp@sha256:e7d2…
MediaType: application/vnd.oci.image.manifest.v1+json
Platform: unknown/unknown
Annotations:
vnd.docker.reference.type: attestation-manifest
Why an index rather than a single manifest: when buildx pushes, it attaches minimal provenance by default (mode=min), which lives in the same index as an attestation manifest with platform unknown/unknown, so the top-level digest is the index's digest. Deployments just reference this top-level digest; the runtime picks the manifest by platform. Common mistake: using the digest of the linux/amd64 child manifest as the release digest, after which signing and verification won't match (Module 6).
Release record: one line of JSON, the only thing you look at when rolling back
jq -n --arg c "$(git rev-parse HEAD)" --arg d "$DIGEST" --arg v "sha-$SHA" \
--arg t "$(date -u +%FT%TZ)" '{commit:$c, digest:$d, version:$v, built_at:$t}' \
| tee -a ~/releases.jsonl
{"commit":"3f9a2c1e…","digest":"sha256:9c1e4b7a2f…d81","version":"sha-3f9a2c1","built_at":"2026-11-17T14:02:11Z"}
Production use: a real pipeline writes this record into the deployment tool (GitHub Deployments, Azure Pipelines environments, ECS deployment history) or into environment manifests in Git; this hour simulates it with ~/releases.jsonl. How to verify: at any time, imagetools inspect REG/myapp@DIGEST retrieves exactly the same content.
Lab 1: Walk the release chain by hand and record the digest (about 5 minutes)
DIGEST. If the ECR repo from hour 4 is IMMUTABLE, running it again with the same sha-$SHA will be rejected — which is exactly what we want (run git commit --allow-empty -m bump first to get a new commit).docker run -d --rm --name smoke -p 5000:5000 -e APP_VERSION="sha-$SHA" "$REG/myapp@$DIGEST" for i in $(seq 20); do curl -fsS localhost:5000/healthz && break; sleep 1; done; echo docker exec smoke id -u; docker stop smoke
ok 10001
# ACA: reference the digest, use the short commit as the revision suffix az containerapp update -g $RG -n $APP --image "$ACR_LOGIN/myapp@$DIGEST" \ --set-env-vars APP_VERSION="sha-$SHA" --revision-suffix "g$SHA" -o none az containerapp show -g $RG -n $APP --query "properties.template.containers[0].image" -o tsv
# ECS: create a new revision from the current task definition, replacing only the image
TD=$(aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].taskDefinition' --output text)
aws ecs describe-task-definition --task-definition "$TD" --query taskDefinition \
| jq --arg img "$ECR/myapp@$DIGEST" '.containerDefinitions[0].image=$img
| del(.taskDefinitionArn,.revision,.status,.requiresAttributes,.compatibilities,.registeredAt,.registeredBy)' > td.json
NEW_TD=$(aws ecs register-task-definition --cli-input-json file://td.json --query taskDefinition.taskDefinitionArn --output text)
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition "$NEW_TD" --query service.taskDefinition --output text
If the ECS service from hour 4 was already switched to native blue/green, this deployment follows the blue/green flow (taking about the bake time in minutes); Module 7 looks at it in detail.
aws ecs describe-tasks --cluster $CLUSTER --tasks $(aws ecs list-tasks --cluster $CLUSTER --service-name $SVC --query 'taskArns[0]' --output text) \
--query 'tasks[0].containers[0].imageDigest' --output text 2>/dev/null || true
curl -s "https://${FQDN:-$ALB_DNS}/" ; echo
jq -n --arg c "$(git rev-parse HEAD)" --arg d "$DIGEST" '{commit:$c,digest:$d,manual:true}' >> ~/releases.jsonl
sha256:9c1e4b7a2f…d81 [sha-3f9a2c1] Hello from myapp--g3f9a2c1-7d9c…, hits=N/A
Cleanup: this lab creates no new resources. The extra task definition revisions in ECS cost nothing; Module 8 deregisters them all.
Case 1: staging passes, prod crashes — the two builds were not the same
Problem: a team's pipeline ran docker build separately in the staging and prod stages. Between the two builds, python:3.13-slim released a new patch whose OpenSSL change made an old client library fail its handshake. Staging was fine; prod crashed completely. Fix: build once, push a sha- candidate, and have prod reference the same digest staging verified; pin the base image by digest and let Dependabot / Renovate open PRs to upgrade it. Limitation: when environments need different configuration, it must be injected via environment variables / secrets, not build arguments.
Case 2: new code that "slipped in" during scale-out
Problem: a Container Apps app referenced myapp:prod; someone re-pushed that tag for a hotfix but didn't deploy. Hours later rising traffic triggered a scale-out, the new replicas pulled the new image, and one revision ran two versions of the code at once, making the issue very hard to reproduce. Fix: every deployment references a digest; deployed tags in ACR are locked (Hour 3 Module 2). Limitation: digests are hard to read, so a release record is needed to map digests back to version numbers.
Case 3: a rollback without a release record
Problem: during a late-night incident, the on-call engineer needed to roll back but only knew "the version from last Friday". He guessed a tag from the ECR push times and ended up on a candidate image that had never passed scanning. Fix: every successful deployment writes a release record (commit, digest, version, environment, time), and the rollback script only accepts digests from the record. Limitation: the record itself must be protected (kept in an audited system or in Git).
Common errors and fixes
jq: error … null (null) has no keys / DIGEST is empty
Cause: --push was missing (a cache-only build has no containerimage.digest), or --load was used (the metadata keys differ with the classic store), or Bake's metadata file groups by target name (."myapp"."containerimage.digest").
jq 'keys' build-meta.json
Fix: read the digest from a push; for Bake use jq -r '.myapp."containerimage.digest"'.
ImageTagAlreadyExistsException: The image tag 'sha-3f9a2c1' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable.
Cause: Hour 4 set the ECR repo to IMMUTABLE, and the same candidate tag was pushed again for the same commit.
Fix: this is expected behavior. When rerunning the pipeline, first check whether the digest already exists (aws ecr describe-images --image-ids imageTag=sha-…); if it does, skip the build and reuse it; if you really need a rebuild, use a new commit.
no matching manifest for linux/amd64 in the manifest list entries
Cause: only arm64 was built on Apple Silicon or an arm64 runner; or the deployment references a child manifest digest.
docker buildx imagetools inspect "$REG/myapp@$DIGEST" | grep Platform
Fix: set --platform linux/amd64,linux/arm64 explicitly (Module 2); deploy the top-level index digest.
The ACA revision shows Running, but the page still shows the old version
Cause: in multiple-revision mode the new revision has 0% traffic (hour 3 Module 5), or the browser is hitting the old revision's label URL.
az containerapp ingress traffic show -g $RG -n $APP -o table
Fix: shift traffic following the Module 7 flow, or temporarily switch back to single mode.
1. Without pulling the image, list the platform and digest of every manifest in the index $REG/myapp@$DIGEST.
docker buildx imagetools inspect "$REG/myapp@$DIGEST" --raw \ | jq -r '.manifests[] | "\(.platform.os)/\(.platform.architecture)\t\(.digest)\t\(.annotations["vnd.docker.reference.type"] // "image")"'
2. Get the digest from the second-to-last record in ~/releases.jsonl (the rollback target).
tail -n 2 ~/releases.jsonl | head -n 1 | jq -r .digest
The team says: "Our image is small and builds in 2 minutes; rebuilding once per environment is simpler." How do you convince them?
The issue is not time but verifiability: ① two builds can differ (base image tag, dependency minor versions, timestamps), so staging's test results can't be carried over to prod; ② scanning and signing target the digest, so a rebuild means rescanning and re-signing, otherwise prod runs an unsigned image; ③ a rollback needs a definite "previous version", and with per-environment rebuilds that "previous version" never existed in prod. Recommendation: build once + immutable candidate tags + environment manifests pinned to digests; the cost is just one imagetools create or one manifest commit.
Verified teaching videos
Official documentation
- Docker Docs: Continuous integration with Docker · Build attestations
- SLSA v1.1 specification (a common language for build provenance and levels)
- Amazon ECS: deployments and image digest resolution
Video storyboard (about 75 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.
Visual: an engineer types build, push, update in a terminal; question-mark bubbles pop up one by one: "Who built it? What's inside? Was it swapped? How do we back out?"
Narration: Manual releases work, but they can't answer the four questions production cares about most.
Visual: seven gates line up along a conveyor belt; an image box labeled with a digest passes through them in turn: build, test, push candidate, scan, sign, deploy, verify; at each gate the box gets another stamp.
Narration: The pipeline builds only once; after that, every gate checks and every environment deploys the same digest.
Visual: the box goes through two doors, Azure and AWS, behind which are Container Apps and ECS; finally a "release record" book appears, and turning back one page rolls back.
Narration: In the next seven modules, we build each of these gates one by one.
Module 2 · BuildKit and buildx in Depth: Cache Backends, Multi-Platform and Bake
- Explain BuildKit's cache key (a hash of the instruction + its input content) and why ephemeral CI runners must export/import cache; compare the four backends
registry,gha,localandinline, andmode=min|max. - Write correct registry cache parameters for ACR and ECR (
image-manifest=true,oci-mediatypes=true), and know that theghabackend needs the Actions runtime token and when the default docker driver cannot export cache. - Choose a multi-platform build approach (QEMU emulation / native arm64 runner / cross-compilation), declare a "test build" and a "release build" target in one
docker-bake.hcl, and review the final parameters with--print.
What: what does the BuildKit cache actually cache?
BuildKit parses the Dockerfile into an LLB directed graph, and every node (FROM, COPY, RUN…) has a cache key: the instruction itself + the parent node's key + a checksum of its inputs (file contents for COPY, ARG values, the base image digest). On a key hit, the node's result (a filesystem snapshot layer) is reused directly; on a miss it runs, and everything downstream is invalidated. Your dev machine "builds in seconds" because those results stay in the local BuildKit state; but GitHub-hosted runners, GitLab SaaS runners and Jenkins agents on ECS are brand-new machines every time - cache that isn't exported is no cache at all.
Why: the four cache backends
| Backend | Where it lives | Good for | Watch out |
|---|---|---|---|
registry | A separate cache image in the registry (e.g. myapp:buildcache) | The platform-agnostic first choice: works in GitHub, GitLab, Azure Pipelines and Jenkins, and ACR / ECR sit in the same region | ECR needs image-manifest=true,oci-mediatypes=true; the cache tag must not be blocked by immutability (use a separate repository or an exclusion rule, Module 4) |
gha | GitHub Actions cache service | Only in GitHub Actions, when you don't want to write cache to a registry | Needs the Actions runtime URL and token (build-push-action / bake-action inject them automatically, run: docker buildx … does not); total repository cache is capped and old entries are evicted; separate branches/targets with scope= |
local | A directory on the runner disk | Self-hosted runners with persistent disks (Jenkins agents, self-hosted GitLab runners) | The directory only grows; rotate it regularly (write to a new directory, then swap) |
inline | Written into the image config itself | The simplest cases | Only supports mode=min; intermediate stages of multi-stage builds are not cached |
mode=min exports only the layers in the final image; mode=max exports every layer of every stage (including compilation and dependency installation in the builder stage). Multi-stage builds almost always need mode=max, at the cost of a larger cache.
How: the driver and image store decide what you can use
- The default
dockerdriver (BuildKit built into dockerd): with the containerd image store it supports inline, local, registry and gha cache plus multi-platform--load; with the classicoverlay2store only inline works, and exporting other cache fails withCache export is not supported for the docker driver. - The
docker-containerdriver: runs a standalone BuildKit in a container (docker buildx create --driver docker-container --use;setup-buildx-actionuses it by default), supports all cache types and multi-platform, but--loadhas to export the result back into Docker. - Three ways to go multi-platform: QEMU emulation (simplest;
pip/ compilation on arm64 is 5-20x slower), native runners (e.g. GitHub's hosted arm64 runners or self-hosted Graviton / Ampere; fastest, but you must merge both platforms' results into one index), cross-compilation (FROM --platform=$BUILDPLATFORM+TARGETARCH, suits Go / Rust; myapp is Python and doesn't need it).
When: when to use Bake
When one repository needs several kinds of builds (single-platform --load for tests, multi-platform --push + attestations for releases), or the same parameters must stay consistent across local, GitHub, GitLab and Jenkins, put the parameters in docker-bake.hcl. CI only calls docker buildx bake TARGET and parameter changes go through code review; docker buildx bake --print outputs the final JSON and is the first step for review and troubleshooting.
--cache-from makes the cache work" - without --cache-to, nobody ever writes the cache. ② "mode=max is always better" - when the final stage is small and intermediate stages are huge (e.g. node_modules only in the builder stage), max can make uploading/downloading cache slower than rebuilding; measure it. ③ "Cache makes images insecure" - cache only affects speed; but a cached RUN apt-get upgrade won't pick up new patches, so rebuild periodically with --no-cache or --pull (the weekly rebuild in Module 5). ④ "arm64 images built under QEMU are broken" - the output is a real arm64 binary, the build is just slow; problems usually come from dependencies without arm64 wheels.Architecture: CI runner, BuildKit and cache backends
Workflow: the two Bake targets
Interactive simulator: how cache hits happen in CI
Pick a cache backend, the change in this commit and the runner type, then play one CI build and watch whether each layer is a "cache hit" or "re-executed", along with the log lines BuildKit actually prints (examples).
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
docker buildx create --name ci --driver docker-container --use --bootstrap | Create a standalone BuildKit builder | Needed for cache export and multi-platform push with the classic store |
--cache-to type=registry,ref=REG/myapp-cache:main,mode=max,image-manifest=true,oci-mediatypes=true | Export registry cache | The last two are required for ECR and harmless for ACR |
--cache-from type=registry,ref=REG/myapp-cache:main | Import cache | Can be repeated: this branch first, then main as fallback |
--cache-to type=gha,scope=myapp-main,mode=max | GitHub Actions cache | scope separates branches/targets, otherwise they overwrite each other |
--cache-to type=local,dest=/cache/new,mode=max | Local directory cache | Write a new directory then replace the old one, to prevent unbounded growth |
docker run --privileged --rm tonistiigi/binfmt --install arm64 | Register QEMU so amd64 can build arm64 | On GitHub use docker/setup-qemu-action |
docker buildx bake --print release | Print the resolved final build parameters (no build) | First step for review and troubleshooting |
docker buildx bake release --set release.platform=linux/amd64 | Temporarily override one attribute | Build a single platform when debugging locally |
docker buildx du --verbose / docker buildx prune --keep-storage 20GB | Inspect / prune build cache | Disk management on self-hosted runners |
This lesson's Bake file: docker-bake.hcl
// Single source of truth for myapp builds: called by local, GitHub, GitLab, Azure Pipelines and Jenkins
variable "REGISTRY" { default = "local" } // acrhour3NNNNN.azurecr.io or 1111….dkr.ecr.ca-central-1.amazonaws.com
variable "VERSION" { default = "dev" } // v1.5.0 or sha-3f9a2c1
variable "GIT_SHA" { default = "0000000" } // 7-character short commit
variable "CACHE_REF" { default = "" } // e.g. ${REGISTRY}/myapp-cache:main; empty = no remote cache
function "cfrom" {
params = [ref]
result = ref == "" ? [] : ["type=registry,ref=${ref}"]
}
function "cto" {
params = [ref]
result = ref == "" ? [] : ["type=registry,ref=${ref},mode=max,image-manifest=true,oci-mediatypes=true"]
}
group "default" { targets = ["test"] }
target "_base" {
context = "."
dockerfile = "Dockerfile"
args = { APP_VERSION = VERSION }
labels = {
"org.opencontainers.image.version" = VERSION
"org.opencontainers.image.revision" = GIT_SHA
}
cache-from = cfrom(CACHE_REF)
}
// Test build: single platform, loaded into local Docker, read-only cache
target "test" {
inherits = ["_base"]
platforms = ["linux/amd64"]
tags = ["myapp:ci"]
output = ["type=docker"]
}
// Release build: multi-platform + SBOM + full provenance, pushes an immutable candidate tag, writes cache back
target "release" {
inherits = ["_base"]
platforms = ["linux/amd64", "linux/arm64"]
tags = ["${REGISTRY}/myapp:sha-${GIT_SHA}"]
attest = ["type=sbom", "type=provenance,mode=max"]
cache-to = cto(CACHE_REF)
output = ["type=registry"]
}
Why it's written this way: only release writes the cache (so the test and release builds don't overwrite the same cache tag); attest is only on the release target (local --load doesn't need it); the only tag is the immutable sha- candidate, and semantic version tags are added at promotion time (Module 4). How to verify: REGISTRY=$ACR_LOGIN GIT_SHA=abc1234 docker buildx bake --print release | jq '.target.release'. Common mistake: variables are overridden by environment variables of the same name, and a spelling mismatch silently falls back to the default - --print before you build.
REGISTRY=$ACR_LOGIN GIT_SHA=3f9a2c1 CACHE_REF=$ACR_LOGIN/myapp-cache:main \
docker buildx bake --print release | jq '.target.release | {platforms, tags, attest, "cache-to"}'
{
"platforms": ["linux/amd64", "linux/arm64"],
"tags": ["acrhour312345.azurecr.io/myapp:sha-3f9a2c1"],
"attest": [{"type": "provenance", "mode": "max"}, {"type": "sbom"}],
"cache-to": [{"type": "registry", "ref": "acrhour312345.azurecr.io/myapp-cache:main", "mode": "max", "image-manifest": "true", "oci-mediatypes": "true"}]
}
In buildx 0.39, --print outputs attest and cache-to as arrays of objects; field order may differ from the above.
Lab 2: cold vs warm cache, single-platform test vs multi-platform release (about 7 minutes)
source ~/hour5.env; cd ~/myapp docker buildx create --name ci --driver docker-container --use --bootstrap docker run --privileged --rm tonistiigi/binfmt --install arm64 docker buildx inspect ci | grep -E 'Driver|Platforms'
Driver: docker-container Platforms: linux/amd64, linux/amd64/v2, linux/arm64, linux/386
In production, tonistiigi/binfmt should also be pinned by digest; on GitHub just use docker/setup-qemu-action (v4.4.0).
docker-bake.hcl from the "Commands" tab into ~/myapp, then:
REG=${ACR_LOGIN:-$ECR}
export REGISTRY=$REG GIT_SHA=$(git rev-parse --short=7 HEAD) VERSION=sha-$(git rev-parse --short=7 HEAD)
export CACHE_REF=$REG/myapp-cache:main
docker buildx bake --print release | jq -c '.target.release.tags'
AWS path: the cache lives in a separate mutable repository myapp-cache; create it first: aws ecr create-repository --repository-name myapp-cache --image-tag-mutability MUTABLE --tags $TAG_KV. The Azure path doesn't need this (ACR creates repositories automatically).
az acr login -n "$ACR" 2>/dev/null || aws ecr get-login-password | docker login --username AWS --password-stdin "$ECR" docker buildx prune -af --builder ci >/dev/null time docker buildx bake release --metadata-file build-meta.json jq -r '.release."containerimage.digest"' build-meta.json
#12 [linux/arm64 builder 4/5] RUN pip install --no-cache-dir -r requirements.txt #12 DONE 41.7s #18 exporting cache to registry #18 DONE 3.9s real 1m52.304s sha256:9c1e4b7a2f…d81
app.py:
docker buildx prune -af --builder ci >/dev/null # empty local state = new runner git commit --allow-empty -qm "ci: warm cache test"; export GIT_SHA=$(git rev-parse --short=7 HEAD) VERSION=sha-$(git rev-parse --short=7 HEAD) time docker buildx bake release --metadata-file build-meta.json 2>&1 | grep -E 'CACHED|importing cache|real' | head
#5 importing cache manifest from acrhour312345.azurecr.io/myapp-cache:main #11 [linux/arm64 builder 4/5] RUN pip install --no-cache-dir -r requirements.txt #11 CACHED #13 [linux/amd64 builder 4/5] RUN pip install --no-cache-dir -r requirements.txt #13 CACHED real 0m24.880s
Even with nothing local, the dependency layers hit the registry cache. The empty commit didn't change app.py, but VERSION changed as a build argument - if the Dockerfile declares ARG APP_VERSION in an early stage, every layer after it is invalidated. Put the ARG at the end of the last stage (the principle from hour 2 Module 2).
docker buildx bake test --builder ci docker run -d --rm --name t -p 5000:5000 myapp:ci; sleep 3; curl -fsS localhost:5000/healthz; echo; docker stop t
Cleanup: docker buildx rm ci removes the builder container; the myapp-cache and candidate tags in the registry are left for the retention policy in Module 4.
Case 1: gha cache that "works sometimes"
Problem: a repository had 6 images sharing type=gha with no scope; each target overwrote the others' index when writing cache, so the hit rate swung wildly; the repository cache quota filled up fast and old entries were evicted. Fix: give each target scope=<image>-<branch>, and let PRs only read main's cache (two cache-from entries: this branch, main); the two largest images switched to ACR registry cache. Limitation: registry cache incurs storage costs and must be covered by the retention policy.
Case 2: a 40-minute arm64 build
Problem: to run ECS on Graviton (about 20% cheaper), the team turned on multi-platform builds, and installing arm64 dependencies under QEMU took 40 minutes. Fix: build each platform on a native runner and push by digest, then merge them into one index with docker buildx imagetools create; or simply use hosted arm64 runners. Limitation: the merge step must handle attestations (each platform has its own provenance), making the pipeline more complex; the remote native builders in hour 7 Module 5 are another option.
Case 3: cache "locking out" security patches
Problem: the RUN apt-get update && apt-get install -y libxml2 layer in the Dockerfile had been cached for 5 months; the scanner kept reporting high-severity vulnerabilities in the old version, and developers were confused because "we build every day". Fix: a weekly scheduled job rebuilds with --pull --no-cache (Bake: --set *.no-cache=true --pull) and refreshes the cache; the base image is pinned by digest and a dependency-update bot opens PRs. Limitation: uncached rebuilds are slower, so run them outside working hours.
Common errors and fixes
ERROR: Cache export is not supported for the docker driver.
Cause: the default docker driver + classic image store only supports inline cache.
docker info --format '{{.Driver}}'; docker buildx ls
Fix: docker buildx create --driver docker-container --use, or enable the containerd image store. On GitHub, setup-buildx-action creates a docker-container builder by default.
ERROR: failed to solve: error writing manifest blob: … 400 Bad Request (exporting cache to ECR)
Cause: ECR does not accept BuildKit's default cache manifest format.
Fix: add image-manifest=true,oci-mediatypes=true to --cache-to; also make sure the cache repository is not IMMUTABLE (the cache tag is overwritten every time), or allow that tag in an exclusion rule.
ERROR: failed to solve: … missing github token / ACTIONS_RUNTIME_TOKEN (type=gha)
Cause: docker buildx was called directly in a run: step, so the Actions runtime URL and token weren't exposed to BuildKit.
Fix: use docker/build-push-action or docker/bake-action (they inject them automatically); or just use registry cache so the same make command runs in every CI (the Module 3 approach).
exec /usr/local/bin/python: exec format error (while building the arm64 stage)
Cause: QEMU binfmt is not registered.
ls /proc/sys/fs/binfmt_misc/ | grep -i aarch64 || echo "no arm64 emulator"
Fix: docker run --privileged --rm tonistiigi/binfmt --install arm64, or docker/setup-qemu-action on GitHub; or switch to a native arm64 runner.
docker buildx bake: target "release" not found / variables have no effect
Cause: the current directory contains both compose.yaml and docker-bake.hcl, and Bake reads and merges them by default; or the environment variable name differs in case from the variable name.
Fix: pass -f docker-bake.hcl explicitly, and check final values with --print first (the same symptom appears in hour 7 Module 5).
1. Write one command that builds only the linux/amd64 platform of the release target, without pushing, loading the result into local Docker, to debug an amd64-specific issue.
docker buildx bake -f docker-bake.hcl release \ --set release.platform=linux/amd64 --set release.output=type=docker
2. In GitHub Actions, PR builds should only read main's gha cache while main builds read and write their own cache. How do you write the build-push-action inputs?
cache-from: |
type=gha,scope=myapp-${{ github.head_ref || github.ref_name }}
type=gha,scope=myapp-main
cache-to: ${{ github.ref == 'refs/heads/main' && 'type=gha,scope=myapp-main,mode=max' || '' }}A team uses both GitHub Actions (main repository) and Jenkins (legacy services), and pushes images to ECR. Which cache backend would you choose, and why?
Choose ECR registry cache: both CI platforms can read and write it, the cache sits in the same region as the images so pulls are fast, and the parameters live in the Bake file shared by both. Key points: ① image-manifest=true,oci-mediatypes=true; ② keep the cache in a separate mutable repository myapp-cache while the release repository stays IMMUTABLE; ③ add a lifecycle rule to the cache repository (e.g. keep only the last 10 tags); ④ Jenkins' long-lived agents can additionally use local cache, but registry cache is the source of truth. gha only works in GitHub and doesn't fit a mixed environment.
About teaching videos
Official documentation
- Cache storage backends · Registry cache · GitHub Actions cache
- Multi-platform builds · Bake · Bake file reference
- AWS: remote cache support in ECR for BuildKit clients
- Further reading: Hour 7 Module 5: Building at Scale (remote builders, reproducible builds, Bake matrices)
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.
Visual: a CI runner appears from the cloud, builds, and vanishes; the next time it's another brand-new runner and the progress bar starts from zero.
Narration: CI runners are disposable, and any build cache left on the machine disappears with them.
Visual: BuildKit packs the layer cache into a "cache image" and pushes it to ACR and ECR; the next runner pulls the cache first, every dependency layer turns green showing CACHED, and only the code layer turns orange and rebuilds.
Narration: export the cache to a registry and any CI platform can reuse it; ECR needs the image-manifest option turned on.
Visual: one docker-bake.hcl file forks into two paths: the test target loads locally to run a smoke test, and the release target builds amd64 and arm64 together and attaches an SBOM and provenance.
Narration: put the build parameters in a Bake file, and your machine and every CI platform call the same definition.
Module 3 · Platform-Neutral Image CI: Bake + Makefile + Minimal OIDC ⭐
- Design a Makefile target contract (
test/release/copy/scan/sign/verify) so that your laptop and every CI platform run exactly the same commands. - Use GitHub Actions OIDC (
id-token: write) to log in, without secrets, to both ACR (user-assigned managed identity + federated credential + AcrPush) and ECR (IAM OIDC provider + role), and understand least privilege and why PRs must never get cloud credentials. - Implement build once, push twice: build once against ACR, copy by digest to ECR, and get the same digest on both sides.
- Drop the same Makefile into GitLab CI (
id_tokens), Azure Pipelines (workload identity federation service connection) and Jenkins (managed identity / instance role), and know which course covers each in depth.
docker-bake.hcl from Module 2; GitHub Actions basics. The OIDC trust chain, subject formats and environment approvals are covered fully in GitHub hour 3, Module 2 (Chinese) and Hour 4, Module 2 (Chinese); this module uses only the minimal configuration. Importance: ★★★★★What: what "platform-neutral" means
The business logic of image CI (how to build, how to test, where to push, how to scan and sign) lives in the repo, in docker-bake.hcl, the Makefile and ci/*.sh. The CI platform's YAML does only three platform-specific things: when to trigger (branch, tag, PR), under which identity (OIDC exchanged for short-lived cloud credentials) and where to run (hosted / self-hosted runner). The payoff: a local make release behaves the same as CI; moving to another CI platform means changing a few dozen lines of YAML; reviewers see all build logic in one place.
| Make target | What it does | Permissions needed | Completed in module |
|---|---|---|---|
make test | bake the test target (single platform, --load) + ci/smoke.sh | None (also runs on PRs) | This module |
make release | bake release (multi-platform + attestations), push the sha- candidate, write .digest | Push to the primary registry | This module |
make copy MIRROR=… | Copy by digest to the second registry (including attestations) | Push on both sides | This module / Module 4 |
make scan | Scan by digest; non-zero exit above the threshold | Pull from the primary registry | Module 5 |
make sign / make verify | Sign / verify the digest | OIDC (keyless) or KMS | Module 6 |
make promote ENV=… | Write the digest into the environment manifest, add a version tag | Repo write | Module 4 |
Why: why it has to be OIDC
Once a long-lived secret (service principal password, IAM access key, ACR admin account) is stored as a CI secret, it can be read by a malicious dependency, a poisoned third-party Action or a log leak, and it stays valid for a long time. With OIDC, CI asks its own identity provider (GitHub, GitLab, Azure DevOps) for a signed JWT on every job; the cloud verifies the issuer, audience and subject (which repo, which branch or environment) and then issues an access token valid for minutes to an hour. The repo stores only identifiers that are not passwords: client ID, tenant ID, role ARN.
How: the trust objects in the two clouds
| Azure (ACR) | AWS (ECR) | |
|---|---|---|
| Cloud identity | User-assigned managed identity id-github-ci | IAM role docker-hour5-gha |
| Trust configuration | Federated credential: issuer https://token.actions.githubusercontent.com, audience api://AzureADTokenExchange, exact subject match | IAM OIDC provider token.actions.githubusercontent.com + role trust policy: aud = sts.amazonaws.com, sub with StringLike |
| Push permission | AcrPush (scope: this ACR); registries with ABAC repository permissions enabled use Container Registry Repository Writer instead | ecr:GetAuthorizationToken (*) + upload and PutImage on myapp, myapp-cache |
| Login in CI | azure/login → az acr login -n $ACR | configure-aws-credentials → aws ecr get-login-password | docker login |
| Token lifetime | Entra access token about 1 hour; ACR refresh token about 3 hours | Role session 1 hour by default; ECR login token 12 hours |
When: which jobs get cloud credentials
Only the release job, running on the protected branch (main) and version tags (v*), needs id-token: write. PR jobs only run make test, and no federated credential or trust condition is configured for PRs, so a PR from a fork cannot exchange anything for a cloud token. Deployment jobs that need manual approval go into a GitHub environment; their subject then becomes …:environment:production and needs its own federated credential (see the GitHub course, hour 3, Module 3).
repo:octo-org@123456/octo-repo@456789:ref:refs/heads/main; older repositories keep the classic format repo:octo-org/octo-repo:ref:refs/heads/main. This lab creates one trust rule for each format so you don't have to guess; in production keep only the one you actually use.repo:org/* is convenient" - any repo and any branch (including pushes to PR branches) could then use the identity; Azure federated credentials don't support wildcards, and AWS StringLike should be narrowed down to the branch or environment. ③ "Giving CI Contributor on the resource group is easiest" - image CI only needs push; deployment permissions belong to a separate deployment job / identity (Module 7). ④ "Using @v4 on an Action pins the version" - tags can be rewritten (the tj-actions incident in 2025, the Trivy incident in 2026); pin to the 40-character commit SHA and upgrade with a dependency update bot.Architecture: one job, two token exchanges, two registries
Workflow: PRs, main and tags take different paths
Interactive simulator: OIDC token exchange (Azure / AWS)
Choose a cloud and a scenario, then press play. Each step shows the real participants (GitHub OIDC provider, Entra ID, STS, registry) and the output that would appear in the job log (example).
Makefile: the single entry point for every CI platform
.RECIPEPREFIX = >
SHELL := /bin/bash
.SHELLFLAGS := -euo pipefail -c
GIT_SHA ?= $(shell git rev-parse --short=7 HEAD)
VERSION ?= sha-$(GIT_SHA)
REGISTRY ?= local
CACHE_REF ?= $(if $(filter local,$(REGISTRY)),,$(REGISTRY)/myapp-cache:main)
export GIT_SHA VERSION REGISTRY CACHE_REF
.PHONY: test release copy
test: ## single-platform build + container smoke test (also runs on PRs, no cloud credentials)
> docker buildx bake -f docker-bake.hcl test
> ./ci/smoke.sh myapp:ci
release: ## multi-platform + SBOM/provenance, push the sha- candidate, write the digest to .digest
> docker buildx bake -f docker-bake.hcl release --metadata-file build-meta.json
> jq -re '.release."containerimage.digest"' build-meta.json > .digest
> echo "pushed $(REGISTRY)/myapp:sha-$(GIT_SHA) @ $$(cat .digest)"
copy: ## copy by digest to the second registry: make copy MIRROR=<registry>
> test -n "$(MIRROR)"
> docker buildx imagetools create -t "$(MIRROR)/myapp:sha-$(GIT_SHA)" "$(REGISTRY)/myapp@$$(cat .digest)"
> docker buildx imagetools inspect "$(MIRROR)/myapp:sha-$(GIT_SHA)" --format '{{json .Manifest.Digest}}'
.RECIPEPREFIX = > uses > instead of a tab as the recipe prefix, so copy-pasting can't produce "missing separator" from mixed spaces/tabs (supported since GNU make 3.82). The scan, sign, verify and promote targets are added in Modules 4-6.
#!/usr/bin/env bash
# usage: ci/smoke.sh IMAGE - start the container, wait for /healthz, check non-root; print logs on failure
set -euo pipefail
img=${1:?usage: smoke.sh IMAGE}
cid=$(docker run -d -p 127.0.0.1::5000 -e APP_VERSION=smoke "$img")
trap 'docker rm -f "$cid" >/dev/null' EXIT
port=$(docker port "$cid" 5000/tcp | head -1 | cut -d: -f2)
for i in $(seq 30); do
if curl -fsS "http://127.0.0.1:$port/healthz" >/dev/null; then break; fi
[[ $i == 30 ]] && { docker logs "$cid" >&2; echo "smoke: /healthz not ready" >&2; exit 1; }
sleep 1
done
uid=$(docker exec "$cid" id -u)
[[ $uid != 0 ]] || { echo "smoke: container runs as root" >&2; exit 1; }
echo "smoke: ok (uid=$uid, port=$port)"
GitHub Actions: .github/workflows/image-ci.yml (minimal OIDC)
name: image-ci
on:
push:
branches: [main]
pull_request:
permissions:
contents: read # least privilege by default
concurrency:
group: image-ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
test:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- run: make test
release:
if: github.event_name == 'push'
needs: test
runs-on: ubuntu-24.04
permissions:
contents: read
id-token: write # only this job can request an OIDC token
outputs:
digest: ${{ steps.push.outputs.digest }}
env:
ACR: ${{ vars.ACR }} # acrhour3NNNNN
ECR: ${{ vars.ECR }} # 111122223333.dkr.ecr.ca-central-1.amazonaws.com
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
- name: Azure login (OIDC)
uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ vars.AZURE_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- run: az acr login -n "$ACR"
- name: AWS login (OIDC)
uses: aws-actions/configure-aws-credentials@e1253824e5c10ff9df46874f81ed3ec929e19cfd # v6.3.0
with:
role-to-assume: ${{ vars.AWS_ROLE_ARN }}
aws-region: ca-central-1
- run: aws ecr get-login-password | docker login --username AWS --password-stdin "$ECR"
- id: push
run: |
make release REGISTRY="$ACR.azurecr.io"
make copy REGISTRY="$ACR.azurecr.io" MIRROR="$ECR"
echo "digest=$(cat .digest)" >> "$GITHUB_OUTPUT"
Why it is written this way: workflow-level permissions grants only contents: read, and id-token: write is enabled only in the release job; every Action is pinned to a 40-character SHA (the comment names the version so Dependabot can recognize it); cloud identifiers go in vars rather than secrets (they aren't passwords, and as variables they make log troubleshooting easier). If you use only one cloud, delete the other cloud's two steps and make copy. Common mistake: logging in to ACR with docker/login-action needs a username/password; in the OIDC scenario az acr login is simpler.
Equivalent snippets for other CI platforms (all logic stays in make)
GitLab CI (id_tokens)
image-release:
image: $CI_REGISTRY/platform/ci-tools:2026.11 # includes docker CLI + buildx, az, aws, make, jq
services: [docker:29.10.0-dind]
rules: [{ if: '$CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' }]
id_tokens:
AZURE_JWT: { aud: api://AzureADTokenExchange }
AWS_JWT: { aud: sts.amazonaws.com }
script:
- az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$AZURE_JWT" --allow-no-subscriptions
- az acr login -n "$ACR"
- echo "$AWS_JWT" > /tmp/aws.jwt
- export AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE=/tmp/aws.jwt AWS_REGION=ca-central-1
- aws ecr get-login-password | docker login -u AWS --password-stdin "$ECR"
- make release copy REGISTRY="$ACR.azurecr.io" MIRROR="$ECR"
A GitLab subject looks like project_path:group/proj:ref_type:branch:ref:main, and the issuer is your GitLab instance URL. Details in GitLab hour 3, Module 2 (Chinese) · Hour 4, Module 2 (Chinese).
Azure Pipelines (workload identity federation)
trigger: { branches: { include: [main] } }
pool: { vmImage: ubuntu-24.04 }
steps:
- script: make test
displayName: test
- task: AzureCLI@2
displayName: release (ACR)
inputs:
azureSubscription: sc-docker-hour5 # WIF service connection, no secret
scriptType: bash
scriptLocation: inlineScript
inlineScript: |
az acr login -n "$(ACR)"
make release REGISTRY="$(ACR).azurecr.io"
To push to ECR with an AWS service connection (including the OIDC setup), see Azure DevOps hour 4, Module 2 (Chinese); WIF service connections are covered in Hour 3, Module 2 (Chinese).
Jenkins (the agent carries its own cloud identity)
pipeline {
agent { label 'docker-buildx' } // agent on an Azure VM (managed identity) or EC2 (instance profile)
options { timestamps() }
stages {
stage('test') { steps { sh 'make test' } }
stage('release') {
when { branch 'main' }
steps {
sh '''
az login --identity --client-id "$CI_IDENTITY_CLIENT_ID" >/dev/null && az acr login -n "$ACR"
aws ecr get-login-password | docker login -u AWS --password-stdin "$ECR" # credentials come from the instance role
make release copy REGISTRY="$ACR.azurecr.io" MIRROR="$ECR"
'''
}
}
}
}
Jenkins has no built-in per-job OIDC issuer. Usually the agent inherits the cloud identity of its host (managed identity / instance profile / EKS Pod Identity), and folders plus credential scopes restrict which jobs may run on such agents. Details in Jenkins hour 3, Module 2 (Chinese) · Hour 4, Module 2 (Chinese).
Lab 3: build on push, one digest in both ACR and ECR (about 8 minutes)
source ~/hour5.env
az identity create -g $RG -n $ID_CI -o none
CI_CLIENT_ID=$(az identity show -g $RG -n $ID_CI --query clientId -o tsv)
CI_PRINCIPAL=$(az identity show -g $RG -n $ID_CI --query principalId -o tsv)
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment create --assignee-object-id $CI_PRINCIPAL --assignee-principal-type ServicePrincipal \
--role AcrPush --scope $ACR_ID -o none
read OID RID < <(gh api repos/$GH_REPO --jq '"\(.owner.id) \(.id)"')
OWNER=${GH_REPO%/*}; NAME=${GH_REPO#*/}
for s in "repo:$GH_REPO:ref:refs/heads/main" "repo:$OWNER@$OID/$NAME@$RID:ref:refs/heads/main"; do
az identity federated-credential create -g $RG --identity-name $ID_CI --name "gh-main-$(echo -n "$s" | md5sum | cut -c1-8)" \
--issuer https://token.actions.githubusercontent.com --subject "$s" --audiences api://AzureADTokenExchange -o none
done
az identity federated-credential list -g $RG --identity-name $ID_CI --query "[].subject" -o tsv
repo:andy-lab/docker-hour5-myapp:ref:refs/heads/main repo:andy-lab@1234567/docker-hour5-myapp@987654321:ref:refs/heads/main
source ~/hour5.env
aws iam create-open-id-connect-provider --url https://token.actions.githubusercontent.com \
--client-id-list sts.amazonaws.com 2>/dev/null || echo "provider exists"
cat > trust.json <<EOF
{ "Version": "2012-10-17", "Statement": [{
"Effect": "Allow",
"Principal": { "Federated": "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/token.actions.githubusercontent.com" },
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": { "token.actions.githubusercontent.com:aud": "sts.amazonaws.com" },
"StringLike": { "token.actions.githubusercontent.com:sub": [
"repo:${GH_REPO}:ref:refs/heads/main",
"repo:${GH_REPO%/*}@*/${GH_REPO#*/}@*:ref:refs/heads/main" ] } } }] }
EOF
cat > push.json <<EOF
{ "Version": "2012-10-17", "Statement": [
{ "Effect": "Allow", "Action": "ecr:GetAuthorizationToken", "Resource": "*" },
{ "Effect": "Allow", "Action": ["ecr:BatchCheckLayerAvailability","ecr:InitiateLayerUpload","ecr:UploadLayerPart",
"ecr:CompleteLayerUpload","ecr:PutImage","ecr:BatchGetImage","ecr:GetDownloadUrlForLayer","ecr:DescribeImages"],
"Resource": ["arn:aws:ecr:${AWS_REGION}:${ACCOUNT_ID}:repository/myapp","arn:aws:ecr:${AWS_REGION}:${ACCOUNT_ID}:repository/myapp-cache"] } ] }
EOF
aws iam create-role --role-name $AWS_CI_ROLE --assume-role-policy-document file://trust.json \
--tags Key=course,Value=docker-hour5 --query Role.Arn --output text
aws iam put-role-policy --role-name $AWS_CI_ROLE --policy-name ecr-push --policy-document file://push.json
arn:aws:iam::111122223333:role/docker-hour5-gha
The immutable-format line wildcards the IDs with @*, because looking them up again via the API is awkward inside an IAM condition; in production replace them with the real IDs. BatchGetImage / GetDownloadUrlForLayer are needed to read the cache and for imagetools create.
cd ~/myapp
gh variable set ACR --body "$ACR"; gh variable set ECR --body "$ECR"
gh variable set AZURE_CLIENT_ID --body "$CI_CLIENT_ID"
gh variable set AZURE_TENANT_ID --body "$(az account show --query tenantId -o tsv)"
gh variable set AZURE_SUBSCRIPTION_ID --body "$(az account show --query id -o tsv)"
gh variable set AWS_ROLE_ARN --body "arn:aws:iam::${ACCOUNT_ID}:role/${AWS_CI_ROLE}"
mkdir -p ci .github/workflows # paste the Makefile, ci/smoke.sh and image-ci.yml from the "Commands" tab
chmod +x ci/smoke.sh && make test
git add -A && git commit -qm "ci: platform-neutral image pipeline" && git push
gh run watch --exit-status
smoke: ok (uid=10001, port=32771) ✓ main image-ci · 1234567890 ✓ test in 41s ✓ release in 2m13s
SHA=$(git rev-parse --short=7 HEAD)
docker buildx imagetools inspect "$ACR_LOGIN/myapp:sha-$SHA" --format '{{json .Manifest.Digest}}'
docker buildx imagetools inspect "$ECR/myapp:sha-$SHA" --format '{{json .Manifest.Digest}}'
gh run view --log --job release | grep -E 'Login Succeeded|pushed' | head
"sha256:9c1e4b7a2f…d81" "sha256:9c1e4b7a2f…d81" Login Succeeded pushed acrhour312345.azurecr.io/myapp:sha-3f9a2c1 @ sha256:9c1e4b7a2f…d81
Cleanup: the CI identity, federated credentials, IAM role and OIDC provider are all deleted together in Module 8.
Case 1: moving from Jenkins to GitHub Actions by changing only 40 lines
Problem: a legacy Jenkinsfile held 300 lines of Groovy: assembling tags, calling docker build, reading credentials, pushing. During the migration the team found lots of implicit behavior (one plugin silently added latest). Approach: first extract the logic into Makefile + Bake while still inside Jenkins, run it for two weeks to confirm identical results (compare digests and tags), then write a GitHub workflow that calls the same make targets. Limits: platform-specific features (approvals, matrices, artifact retention) still have to be configured on each platform.
Case 2: an attempt to steal credentials through a fork PR is blocked
Problem: an open-source repo received a PR that modified the workflow and tried to print cloud credentials in pull_request_target. Approach: the repo never uses pull_request_target to run untrusted code; PR jobs don't have id-token: write; the federated credentials and IAM trust conditions only accept refs/heads/main. Even with a modified workflow, no token can be obtained. Limits: main branch protection (required reviews, no force pushes) is a precondition of this model.
Case 3: Action tags rewritten overnight
Problem: in the March 2026 Trivy incident, most version tags of trivy-action were force-rewritten to point at malicious commits (official Aqua advisory); pipelines that referenced the Action by tag ran secret-stealing code on their runners. Approach: pin every Action by SHA, make workflows read-only by default, use OIDC and short-lived tokens for the cloud, and run scanners from pinned image versions (Module 5). Limits: once pinned by SHA, you need a dependency bot to open upgrade PRs regularly, otherwise you stay stuck on old vulnerable versions.
Common errors and fixes
Error: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable
Cause: the job lacks id-token: write (job-level permissions override workflow-level ones), or it is running in a PR from a fork.
Fix: add id-token: write to the release job's permissions; PRs should not need it.
AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:andy-lab@1234567/docker-hour5-myapp@987654321:ref:refs/heads/main'
Cause: subject mismatch: the repo uses the immutable format, the job uses environment:, the branch differs, or the repo was renamed/transferred.
az identity federated-credential list -g $RG --identity-name $ID_CI --query "[].subject" -o tsv
Fix: add or update a federated credential using the subject shown in the error message (that message is the most authoritative source for the subject).
Could not assume role with OIDC: Not authorized to perform sts:AssumeRoleWithWebIdentity
Cause: the aud / sub conditions in the trust policy don't match, or the OIDC provider ARN has the wrong account.
aws iam get-role --role-name $AWS_CI_ROLE --query Role.AssumeRolePolicyDocument
Fix: temporarily print the token claims in the job (never the token itself): curl -sH "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=sts.amazonaws.com" | jq -r .value | cut -d. -f2 | base64 -d 2>/dev/null | jq '{sub,aud}', then correct the conditions to the actual values.
unauthorized: authentication required / denied: requested access to the resource is denied (pushing to ACR)
Cause: the role assignment hasn't taken effect yet (usually a few minutes), or the registry has ABAC repository permissions enabled, so AcrPush no longer applies.
az role assignment list --assignee $CI_PRINCIPAL --scope $ACR_ID -o table
Check the registry's "role assignment permissions mode" (whether ABAC repository permissions are enabled) under the registry's "Properties" in the portal.
Fix: wait, or switch to Container Registry Repository Writer (ABAC mode).
Makefile:12: *** missing separator. Stop.
Cause: a recipe line starts with spaces, while make requires a tab by default.
Fix: this lesson's Makefile sets .RECIPEPREFIX = > on its first line, so recipe lines start with >; alternatively replace the spaces with a tab.
1. Add another federated credential to the same id-github-ci that lets deployment jobs in the production environment (classic subject format) log in.
az identity federated-credential create -g $RG --identity-name $ID_CI --name gh-env-production \ --issuer https://token.actions.githubusercontent.com \ --subject "repo:$GH_REPO:environment:production" --audiences api://AzureADTokenExchange
2. List the AssumeRoleWithWebIdentity calls for the CI role docker-hour5-gha in the last 24 hours (CloudTrail).
aws cloudtrail lookup-events --start-time "$(date -u -d '-24 hours' +%FT%TZ)" \ --lookup-attributes AttributeKey=EventName,AttributeValue=AssumeRoleWithWebIdentity \ --query "Events[?contains(CloudTrailEvent, 'docker-hour5-gha')].[EventTime,Username]" --output table
The security team requires that "CI must not push directly to the production registry". How do you satisfy this with this module's design?
Split into two registries/repositories and two identities: ① the CI identity can push only to the build registry (or the repository prefix ci/) and produces the candidate digest; ② the promotion job (which requires environment approval and has the subject environment:production) uses a different identity and, after verifying the signature and scan results, copies the same digest to the production registry (imagetools create, or oras cp -r to copy the signatures along with it); ③ write access to the production registry is granted only to the promotion identity; ④ the runtimes (ACA's id-myapp, the ECS task execution role) have pull permission only. This way no single CI run can bypass approval and overwrite production images directly.
Verified teaching videos
Official docs and follow-up courses
- GitHub Docs: OIDC in Azure · OIDC in AWS · OIDC reference
- azure/login · aws-actions/configure-aws-credentials · Docker Build GitHub Actions
- GitLab: OpenID Connect (OIDC) Authentication Using ID Tokens
- Go deeper: GitHub hour 3 (Azure) (Chinese) · Hour 4, Module 3: build and push to ECR (Chinese) · GitLab: push to ACR (Chinese) · Azure DevOps: push to ECR (Chinese) · Jenkins: push to ACR (Chinese)
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.
Visual: the icons of four CI platforms (GitHub, GitLab, Azure Pipelines, Jenkins) all point to the same Makefile, which in turn points to docker-bake.hcl.
Narration: the build logic lives in the repo; the CI platform only handles triggers, identity and the runtime environment.
Visual: the job asks GitHub for a token card showing sub and aud and hands it to Entra ID and AWS STS; after each door checks the repo and branch on the card, it hands back a key that expires automatically after one hour.
Narration: with OIDC there are no passwords in the repo; PR jobs aren't allowed to request a token, so they never get a key.
Visual: the image is pushed to ACR, then copied by digest to ECR; the two digest strings overlap exactly and flash.
Narration: build once, push twice; both clouds run the very same bytes.
Module 4 · Tags, Versions and Promotion: One Digest Through Every Environment
- Distinguish four kinds of reference: the candidate tag
sha-3f9a2c1, the release tagv1.5.0, floating tags1.5/latest, and the digest, and say whether each one should be used for deployment. - Make release tags non-overwritable on both clouds: ACR image locks (
--write-enabled false) and ECRIMMUTABLE/IMMUTABLE_WITH_EXCLUSION, with cache and floating tags as exceptions. - Implement promotion: when a version tag fires, find the digest main already built, add the
v1.5.0tag, write it into the environment manifest, and keep the digest unchanged when copying across environments and registries (including referrers such as signatures and SBOMs). - Design a retention and cleanup policy that never deletes live images (ACR purge, ECR lifecycle), and understand how cleanup interacts with multi-platform indexes and their child manifests.
What: four kinds of reference, each with its own job
| Reference | Example | Mutable? | Created by | Used for deployment? |
|---|---|---|---|---|
| Candidate tag | myapp:sha-3f9a2c1 | Immutable (ECR IMMUTABLE; on ACR via process + locks) | CI release job | Only for dev / automated test environments |
| Release tag | myapp:v1.5.0 | Must be immutable | Promotion job (triggered by pushing a git tag) | Readable, used in release notes and audits; resolved to a digest at deploy time |
| Floating tag | myapp:1.5, myapp:latest, myapp:prod | Mutable (designed to move) | Promotion job | Not for deployment; only lets people and tools "find the latest" |
| Digest | myapp@sha256:9c1e… | Content-addressed, never changes | Computed by the registry | The single source of truth for deploying, signing, scanning and rolling back |
Why: you need both immutable tags and digest deployment
Immutable tags guarantee that "v1.5.0 is always that content", which makes human communication (release notes, incident reports) reliable; digest deployment guarantees the runtime never gets something else because of tag resolution. Combine them: the environment manifest says myapp@sha256:9c1e… with a v1.5.0 comment next to it; anyone can go from tag to digest, and from digest back to the commit (the OCI label org.opencontainers.image.revision and provenance).
| Capability | ACR | ECR |
|---|---|---|
| Prevent tag overwrite | No repository-level "immutable" switch; lock individual images/tags: az acr repository update --image myapp:v1.5.0 --write-enabled false (locking the whole repository blocks every new push) | Repository-level IMMUTABLE; IMMUTABLE_WITH_EXCLUSION uses wildcard filters to let a few mutable tags through (e.g. latest, cache-*), available since 2025-07 |
| Prevent deletion | --delete-enabled false; purge skips locked images by default | Lifecycle rules don't match release tags; IAM denies BatchDeleteImage |
| Server-side copy | az acr import (cross-registry, cross-subscription, data never passes through the runner) | Replication rules (cross-region / cross-account, automatic on push) |
| Retention and cleanup | acr purge (scheduled via an ACR Task) | Lifecycle policies (preview first) |
How: promotion = moving pointers
- The release job on main has already pushed
sha-3f9a2c1→ digest D, scanned and signed it (Modules 5 and 6), and deployed it to staging automatically (D written into the environment manifestdeploy/staging.env). - The release owner pushes git tag
v1.5.0on the same commit. The promotion job does not build: it looks up the D behindsha-3f9a2c1, verifies the signature, then adds thev1.5.0and1.5tags to D. - The prod environment (approval required) writes D into
deploy/prod.envand deploys (Module 7). Rollback = writing the previous record's digest back into the manifest. - When copying across registries (ACR → ECR, build registry → production registry), the image index is copied as-is and the digest stays the same; referrers such as signatures and SBOMs must be copied explicitly (
oras cp -r) or re-signed on the target.
When: when to use semantic versioning
Use SemVer (vMAJOR.MINOR.PATCH) for services that are released externally, need a changelog, or are depended on by several teams; purely internal, continuously deployed services can use just sha- candidates plus a date-based version (e.g. 2026.11.17-3f9a2c1). Either way, deploy by digest.
latest can't be used" - put latest in the exceptions with IMMUTABLE_WITH_EXCLUSION, but never let a deployment reference it. ② "Promotion means re-tagging and pushing again" - if "pushing again" means rebuilding, the digest changes; the right way is to add a tag to the existing digest on the registry side (imagetools create / az acr import / put-image). ③ "Copying an image brings its signatures along" - imagetools create only copies the index and the manifests it references (including attestations), not cosign / Notation signatures attached to the digest as referrers. ④ "Cleaning up untagged images is safe" - the child manifests of a multi-platform index have no tags; ECR lifecycle won't delete child images still referenced by an index, but a home-grown script might.Architecture: one digest, three environments, two clouds
Workflow: three tiers of retention
Interactive simulator: promoting v1.5.0 (dev → staging → prod)
Choose a promotion method and play it, watching which digest each environment actually runs. Done correctly, all three environments run exactly the same digest; the anti-patterns make the digest change, or get rejected, at some step.
Core commands
| Command | Purpose | Notes |
|---|---|---|
docker buildx imagetools inspect REG/myapp:sha-3f9a2c1 --format '{{json .Manifest.Digest}}' | Look up the digest from a candidate tag | Does not pull the image |
docker buildx imagetools create -t REG/myapp:v1.5.0 -t REG/myapp:1.5 REG/myapp@sha256:… | Tag an existing digest on the registry side | With a single source the index is copied as-is and the digest is unchanged; also works across registries |
az acr import -n $ACR --source $ACR_LOGIN/myapp@sha256:… -t myapp:v1.5.0 | ACR server-side import / re-tag | Across registries, --source can be another registry's login server (permissions required) |
az acr repository update -n $ACR --image myapp:v1.5.0 --write-enabled false --delete-enabled false | Lock a release tag | purge skips locked images by default |
aws ecr put-image-tag-mutability --repository-name myapp --image-tag-mutability IMMUTABLE_WITH_EXCLUSION --image-tag-mutability-exclusion-filters filterType=WILDCARD,filter=latest | Immutable + exceptions | Check the CLI reference for the exact filter syntax |
oras cp -r SRC@sha256:… DST:v1.5.0 | Copy together with referrers (signatures, SBOM) | ORAS 1.4.0; the target registry must support OCI referrers (both ACR and ECR do) |
oras discover REG/myapp@sha256:… --format tree | List the referrers attached to a digest | Check whether signatures were copied over |
az acr run --cmd "acr purge --filter 'myapp:^sha-.*' --ago 30d --keep 30 --untagged --dry-run" -r $ACR /dev/null | Dry run of candidate-tag cleanup | Only deletes once --dry-run is removed |
aws ecr start-lifecycle-policy-preview --repository-name myapp | Lifecycle policy preview | Preview before applying |
Makefile addition: the promote target
promote: ## make promote ENV=staging|prod [TAG=v1.5.0]: write the sha- candidate's digest into the env manifest and add a version tag
> test -n "$(ENV)"
> d=$$(docker buildx imagetools inspect "$(REGISTRY)/myapp:sha-$(GIT_SHA)" --format '{{json .Manifest.Digest}}' | tr -d '"'); \
if [ -n "$(TAG)" ]; then docker buildx imagetools create -t "$(REGISTRY)/myapp:$(TAG)" "$(REGISTRY)/myapp@$$d"; fi; \
printf 'IMAGE=%s/myapp@%s\nVERSION=%s\nCOMMIT=%s\n' "$(REGISTRY)" "$$d" "$(or $(TAG),sha-$(GIT_SHA))" "$(GIT_SHA)" > deploy/$(ENV).env; \
cat deploy/$(ENV).env
Why it's written this way: promotion only reads an existing digest and never triggers a build; the environment manifest is a plain file, so a promotion is a reviewable, revertible commit (for the full GitOps form see the GitOps and Argo CD course (Chinese)). How to verify: the digest part of IMAGE is identical across the environments' deploy/*.env files.
Promotion workflow (triggered by pushing a git tag; no build)
name: promote
on:
push:
tags: ['v*.*.*']
permissions:
contents: write # commit deploy/prod.env
id-token: write
jobs:
promote:
runs-on: ubuntu-24.04
environment: production # needs approval; subject becomes …:environment:production
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with: { ref: main }
- uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0
with:
client-id: ${{ vars.AZURE_CLIENT_ID }}
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- run: az acr login -n "${{ vars.ACR }}"
- run: |
GIT_SHA=$(git rev-parse --short=7 "${GITHUB_REF_NAME}^{commit}")
make verify REGISTRY="${{ vars.ACR }}.azurecr.io" GIT_SHA="$GIT_SHA" # Module 6
make promote REGISTRY="${{ vars.ACR }}.azurecr.io" GIT_SHA="$GIT_SHA" ENV=prod TAG="$GITHUB_REF_NAME"
az acr repository update -n "${{ vars.ACR }}" --image "myapp:$GITHUB_REF_NAME" --write-enabled false --delete-enabled false
git config user.name github-actions; git config user.email github-actions@users.noreply.github.com
git add deploy/prod.env && git commit -m "promote $GITHUB_REF_NAME to prod" && git push origin HEAD:main
Pushing directly to main requires branch protection to allow this identity (or open a PR for a human to merge instead); tags on the ECR side are done the same way with make promote REGISTRY=$ECR.
Lab 4: Promote v1.5.0 and prove the digest didn't change (about 6 minutes)
sha- candidate pushed in Module 3):
source ~/hour5.env; cd ~/myapp; mkdir -p deploy export GIT_SHA=$(git rev-parse --short=7 HEAD) make promote REGISTRY=$ACR_LOGIN ENV=staging make promote REGISTRY=$ECR ENV=staging-aws 2>/dev/null || true
IMAGE=acrhour312345.azurecr.io/myapp@sha256:9c1e4b7a2f…d81 VERSION=sha-3f9a2c1 COMMIT=3f9a2c1
latest may move):
aws ecr put-image-tag-mutability --repository-name $REPO \ --image-tag-mutability IMMUTABLE_WITH_EXCLUSION \ --image-tag-mutability-exclusion-filters filterType=WILDCARD,filter=latest aws ecr describe-repositories --repository-names $REPO \ --query 'repositories[0].[imageTagMutability,imageTagMutabilityExclusionFilters]' --output json
["IMMUTABLE_WITH_EXCLUSION", [{"filterType": "WILDCARD", "filter": "latest"}]]make promote REGISTRY=$ACR_LOGIN ENV=prod TAG=v1.5.0
az acr repository update -n $ACR --image myapp:v1.5.0 --write-enabled false --delete-enabled false -o none
make promote REGISTRY=$ECR ENV=prod-aws TAG=v1.5.0
for r in "$ACR_LOGIN" "$ECR"; do for t in sha-$GIT_SHA v1.5.0; do
printf '%-60s ' "$r/myapp:$t"; docker buildx imagetools inspect "$r/myapp:$t" --format '{{json .Manifest.Digest}}'; done; done
acrhour312345.azurecr.io/myapp:sha-3f9a2c1 "sha256:9c1e4b7a2f…d81" acrhour312345.azurecr.io/myapp:v1.5.0 "sha256:9c1e4b7a2f…d81" 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:sha-3f9a2c1 "sha256:9c1e4b7a2f…d81" 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp:v1.5.0 "sha256:9c1e4b7a2f…d81"
v1.5.0 again (should fail), move latest (should succeed):
docker buildx imagetools create -t "$ECR/myapp:v1.5.0" "$ECR/myapp:sha-$GIT_SHA" 2>&1 | tail -1 docker buildx imagetools create -t "$ECR/myapp:latest" "$ECR/myapp:v1.5.0" && echo "latest moved" az acr repository untag -n $ACR --image myapp:v1.5.0 2>&1 | tail -1
ERROR: … tag invalid: The image tag 'v1.5.0' already exists in the 'myapp' repository and cannot be overwritten because the repository is immutable. latest moved (… ) The operation is disallowed on this registry, repository or image.
In some cases ECR also rejects re-applying the same tag to the same digest - that is expected too.
az acr run -r $ACR --cmd "acr purge --filter 'myapp:^sha-.*' --ago 30d --keep 30 --untagged --dry-run" /dev/null | tail -5 aws ecr start-lifecycle-policy-preview --repository-name $REPO >/dev/null 2>&1 && sleep 10 aws ecr get-lifecycle-policy-preview --repository-name $REPO --query 'summary' 2>/dev/null
The hour 4 lifecycle policy only matches sha-* and untagged images, so v1.5.0 and child manifests referenced by an index will not expire. Cleanup: keep all tags; Module 8 deletes the whole repository. Commit deploy/ to the repository: git add deploy && git commit -m "deploy manifests" && git push.
Case 1: A tag was overwritten and the rollback went "back to the future"
Problem: The team used myapp:1.4 to mean "the latest patch in the 1.4 series". During an incident, the on-call engineer rolled back to 1.4 and got the broken 1.4.3 that had been pushed an hour earlier. Approach: deploy by digest only; keep 1.4 as a floating tag but never deploy it; lock release tag v1.4.2 in ACR and make it immutable in ECR. Limitation: you need tooling that shows a digest as a readable version (release records, OCI labels).
Case 2: Separating the production registry from the build registry
Problem: Auditors require production to run only images that went through an "approved promotion". Approach: CI pushes to acrbuild; after approval, the promotion job uses az acr import (server-side copy, nothing passes through the runner) to import the digest into acrprod, then fills in the signatures with oras cp -r or by re-signing; the production runtime identity has AcrPull only on acrprod. On AWS, a cross-account replication rule copies the prod/ prefix into the production account. Limitation: storage cost for two registries; replication latency must be counted in release time.
Case 3: A lifecycle policy nearly deleted the rollback target
Problem: The cleanup rule was "keep only the last 20 sha- images", prod hadn't released for three weeks, and the running digest only had a sha- tag (the team never added release tags for prod). Approach: always add an immutable release tag when promoting to prod (the rule only matches sha-*), and compare against the digests referenced by every environment manifest before cleaning. Limitation: ECS tasks that already resolved the digest keep running after the image is deleted, but scale-out and task replacement fail to pull - the problem surfaces at the worst possible moment.
Common errors and fixes
tag invalid: The image tag 'v1.5.0' already exists … cannot be overwritten because the repository is immutable
Cause: the same version was promoted twice, or someone tried to overwrite a release tag with a new build.
aws ecr describe-images --repository-name $REPO --image-ids imageTag=v1.5.0 --query 'imageDetails[0].imageDigest'
Fix: if the digest matches what you expect, the promotion job should treat it as "already done" and skip; if not, someone pushed from somewhere else - release a new patch version v1.5.1 instead of forcing an overwrite.
The operation is disallowed on this registry, repository or image. (ACR)
Cause: the image or repository is locked (writeEnabled=false or deleteEnabled=false).
az acr repository show -n $ACR --image myapp:v1.5.0 --query changeableAttributes
Fix: once you've confirmed the change is really needed, unlock with --write-enabled true first; note that locking the whole repository blocks every new push from CI.
After promotion, cosign verify / notation verify reports no signatures found on the target registry
Cause: imagetools create / az acr import did not copy the referrers.
oras discover "$ECR/myapp@$D" --format tree
Fix: copy with oras cp -r (including referrers), or re-sign on the target registry (the keyless identity is the same, so the verification policy doesn't change).
CannotPullContainerError: … manifest unknown (during ECS scale-out)
Cause: the digest referenced by the task definition has been cleaned up (by a lifecycle rule or manual deletion).
Fix: immediately write a release digest that still exists back into the task definition and deploy; fix the cleanup rule so running and rollback-able digests fall outside its scope.
1. List all locked (non-writable) tags in the myapp repository in ACR.
az acr repository show-tags -n $ACR --repository myapp --detail \ --query "[?changeableAttributes.writeEnabled==\`false\`].name" -o tsv
2. Check whether two environment manifests point to the same digest, exiting non-zero if they differ.
diff <(grep -o 'sha256:[0-9a-f]*' deploy/staging.env) <(grep -o 'sha256:[0-9a-f]*' deploy/prod.env) \
&& echo "same digest" || { echo "digest differs"; exit 1; }The business requires that "prod always runs a version staging has verified", but staging deploys a dozen times a day. How do you design things so that at prod approval time you know exactly which one was "verified"?
① Every staging deployment writes an environment-manifest commit and a release record (digest, commit, time, link to test results); ② after automated acceptance (smoke, end-to-end) passes, mark that digest "verified" in the release record (or attach a test-result attestation to the digest in the registry); ③ when a git tag is pushed, the promotion job accepts only a digest marked verified and checks its signature; ④ the prod approval page shows the digest, version and test-result link; ⑤ after the prod deployment, the same digest is written into deploy/prod.env. The key is that "the verification result is bound to the digest", not to a point in time or a mutable tag.
About the teaching videos
Official documentation
- ACR: Lock a container image · acr purge · az acr import
- ECR: Image tag mutability · ECR tag immutability exceptions (2025-07) · Lifecycle policies
- docker buildx imagetools create · oras copy · Semantic Versioning 2.0.0
Video storyboard (about 70 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool to produce.
Visual: a gold block labelled sha256 sits fixed in the center, with several tag slips floating around it: sha, v1.5.0, 1.5, latest, each tied to the block by a thin line.
Narration: the digest is the content itself; a tag is just a slip of paper pointing to it.
Visual: three doors, dev, staging and prod, open one after another, and the same gold block is passed through each; the digest text on every door plate is identical. Next to them, a "rebuild" button gets a red cross.
Narration: promotion moves pointers, not bytes; rebuilding produces a different block.
Visual: ACR hangs a lock on the v1.5.0 tag; ECR's repository door reads IMMUTABLE, and only the latest slip can move.
Narration: release tags can't be rewritten, and cleanup rules only touch candidate tags.
Module 5 · SBOM, Provenance and Vulnerability Scanning
- Explain how buildx attestations are stored (an attestation manifest inside the same index), pull a platform's SBOM (SPDX) and SLSA provenance from the registry, and describe the difference between
mode=minandmode=maxand the leakage risk. - Use a pinned version of Trivy / Grype (or Docker Scout) to scan the image in the registry by digest without mounting
docker.sock; also rescan offline from an SBOM. - Design a vulnerability gate: severity threshold, block only vulnerabilities "with a fixed version", VEX statements and exceptions with an expiry date, plus weekly rebuilds and continuous scanning.
What: three kinds of "evidence about an image"
| Evidence | Question it answers | Who produces it | Format |
|---|---|---|---|
| SBOM (software bill of materials) | Which packages are in the image, at what versions, under which licenses | BuildKit calls the Syft scanner at build time (--sbom=true / attest type=sbom), or Syft / Scout generate it afterwards | SPDX JSON (BuildKit default), CycloneDX |
| Provenance (build provenance) | Who built it, where, and from which inputs: source repo and commit, build args, base image digest, builder | BuildKit (--provenance=mode=min|max); GitHub's attest-build-provenance can also generate it | in-toto statement + SLSA predicate |
| Vulnerability report | Which known vulnerabilities these packages have, and whether fixed versions exist | Trivy / Grype / Docker Scout / Defender / Inspector | JSON, SARIF, table |
buildx puts the SBOM and provenance into the image index as an attestation manifest (platform unknown/unknown, annotation vnd.docker.reference.type=attestation-manifest), one per platform, pushed, copied and deleted together with the image. Signatures (Module 6) are a different kind of object, attached to the digest as referrers.
Why: have the SBOM first, so you can answer when a vulnerability breaks
When a new critical vulnerability is published, the first question is always "which of our services are affected?". Teams with SBOMs search the registry or an SBOM store by package name and list the affected digests and environments in minutes; teams without SBOMs can only pull and scan images one by one. Provenance lets you prove that "this digest came from this commit of this repo and was built in our CI", which is the foundation of signature verification policies (Module 6) and SLSA levels.
How: four design decisions for the gate
| Decision | Recommendation | Rationale |
|---|---|---|
| What to scan | After pushing, scan the image in the registry by digest (all platforms) | Exactly matches what gets deployed; no local Docker daemon needed |
| Threshold | Fail on CRITICAL,HIGH with a fixed version (--ignore-unfixed); only report the rest | Blocking a release when no fix exists solves nothing; it just pushes people to bypass the gate |
| Exceptions | VEX (OpenVEX) statements of "not affected" + justification; temporary exceptions must have an expiry date and an owner | Exceptions are auditable and expire, avoiding permanent allowlists |
| The scanner itself | Pinned version + verified signature/checksum + no docker.sock mount + no latest | The March 2026 Trivy supply chain incident: the v0.69.4 binary, Docker Hub images 0.69.5 / 0.69.6 and most trivy-action tags were injected with malicious code |
When: one scan is not enough
Vulnerability databases update daily; an image that is clean today may have a new CVE next week. So: ① the CI gate blocks "newly introduced" problems; ② continuous scanning on the registry side (Defender for Containers for ACR, ECR enhanced scanning / Amazon Inspector) finds "new problems in images already in production"; ③ scheduled weekly rebuilds (--pull --no-cache) pick up base image patches and ship through the same pipeline.
trivy-action v0.35.0 and setup-trivy v0.2.6. Whatever version you use, pin the image by digest and follow Aqua's latest advisory.mode=max provenance is better, always turn it on" - it records all build args, so a token in --build-arg is written into the attestation and published with the image; secrets must use --secret (hour 2 Module 2). ② "Zero vulnerabilities from the scanner means it is safe" - scanners only know known CVEs and the packages they can recognize (manually downloaded binaries and statically linked libraries may go unrecognized). ③ "Mounting docker.sock makes scanning easier" - that hands host root to the scanner; it is exactly how the poisoned scanner in the incident stole secrets from runners. ④ "Putting an exception in .trivyignore is enough" - an exception with no expiry date lives forever, and nobody remembers why.Architecture: where attestations live in the registry
Workflow: the scan gate and exceptions
Interactive simulator: five outcomes of the scan gate
Pick a scan result and press play to see how the gate decides, what the pipeline prints, and who should do what next (output is illustrative).
Core commands
| Command | Purpose | Notes |
|---|---|---|
docker buildx imagetools inspect REF --format '{{ json (index .SBOM "linux/amd64").SPDX }}' | Extract the SPDX SBOM for one platform | For single-platform images use .SBOM.SPDX |
docker buildx imagetools inspect REF --format '{{ json (index .Provenance "linux/amd64").SLSA }}' | Extract the provenance | Look at source and args in invocation / buildDefinition |
trivy image --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 REF@DIGEST | Scan by digest and gate | Run as a container; mount Docker credentials, not the socket |
trivy sbom sbom.spdx.json / grype sbom:./sbom.spdx.json | Offline scan from an SBOM | No image pull needed; good for bulk rescans |
grype registry:REF@DIGEST --fail-on high --only-fixed | Cross-check with a second scanner | Their vulnerability databases differ, so results will differ |
syft registry:REF@DIGEST -o cyclonedx-json | Generate a CycloneDX SBOM | Use when the consumer requires CycloneDX |
docker scout cves registry://REF@DIGEST --only-severity critical,high --exit-code | Docker Scout scan | Requires a Docker account login; CLI plugin 1.29.0 |
trivy image --vex openvex.json --ignorefile .trivyignore.yaml … | Apply VEX and exceptions | Grype uses --vex |
Makefile addition: the scan target (no docker.sock mount)
TRIVY_VERSION ?= 0.76.2
GRYPE_VERSION ?= v0.122.0
SCAN_RUN = docker run --rm -e DOCKER_CONFIG=/cfg -v "$$HOME/.docker/config.json:/cfg/config.json:ro" -v "$$PWD:/src:ro"
scan: ## Scan the registry image by digest: fail on fixable HIGH/CRITICAL
> d=$$(cat .digest); \
$(SCAN_RUN) -v trivy-cache:/root/.cache/ aquasec/trivy:$(TRIVY_VERSION) image \
--severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 \
--ignorefile /src/.trivyignore.yaml --vex /src/openvex.json \
--format table "$(REGISTRY)/myapp@$$d"
sbom: ## Pull the amd64 SPDX SBOM from the registry and cross-scan with Grype (report only)
> d=$$(cat .digest); \
docker buildx imagetools inspect "$(REGISTRY)/myapp@$$d" --format '{{ json (index .SBOM "linux/amd64").SPDX }}' > sbom.spdx.json; \
$(SCAN_RUN) anchore/grype:$(GRYPE_VERSION) sbom:/src/sbom.spdx.json --only-fixed -o table || true
Why it is written this way: the scanner container only gets a read-only Docker credentials file (written by az acr login / docker login) and pulls the image from the registry itself; it cannot see the host's Docker daemon. Note: if the lab machine uses a credential helper (credsStore), config.json holds no actual credentials and the scanner reports 401 - usually not a problem in CI; locally you can pass TRIVY_USERNAME / TRIVY_PASSWORD instead. In production the scanner image should be pinned by digest (aquasec/trivy:0.76.2@sha256:…).
Exception file and VEX
vulnerabilities:
- id: CVE-2026-31337
paths:
- "usr/local/lib/python3.13/site-packages/somelib"
statement: "Code path used only at build time; unreachable at runtime. Owner @team-myapp, tracked in issue #142"
expired_at: 2027-01-31{
"@context": "https://openvex.dev/ns/v0.2.0",
"@id": "https://example.com/vex/myapp-2026-11",
"author": "team-myapp",
"timestamp": "2026-11-17T00:00:00Z",
"version": 1,
"statements": [{
"vulnerability": { "name": "CVE-2026-40404" },
"products": [{ "@id": "pkg:oci/myapp" }],
"status": "not_affected",
"justification": "vulnerable_code_not_in_execute_path"
}]
}The CVE IDs are examples. An exception (ignore file) means "we accept the risk for now" and must expire; a VEX statement means "we analyzed it and are genuinely not affected", a shareable claim you can ship to customers alongside the SBOM. Both go through code review.
Lab 5: read the SBOM and provenance, scan by digest (about 7 minutes)
release build pushed in Module 3 includes type=sbom and provenance,mode=max):
source ~/hour5.env; cd ~/myapp
REG=${ACR_LOGIN:-$ECR}; D=$(cat .digest 2>/dev/null || docker buildx imagetools inspect "$REG/myapp:sha-$(git rev-parse --short=7 HEAD)" --format '{{json .Manifest.Digest}}' | tr -d '"')
echo "$D" > .digest
docker buildx imagetools inspect "$REG/myapp@$D" --format '{{ json (index .SBOM "linux/amd64").SPDX }}' > sbom.spdx.json
jq -r '.packages | length' sbom.spdx.json
jq -r '.packages[] | select(.name=="flask" or .name=="openssl" or .name=="libssl3t64") | "\(.name) \(.versionInfo)"' sbom.spdx.json
163 flask 3.1.2 libssl3t64 3.5.1-1
docker buildx imagetools inspect "$REG/myapp@$D" --format '{{ json (index .Provenance "linux/amd64").SLSA }}' > prov.json
jq -r '(.invocation.configSource.uri // .buildDefinition.externalParameters.configSource.uri // "n/a"),
(.materials // .buildDefinition.resolvedDependencies // [] | .[] | .uri)' prov.json | head -5
https://github.com/andy-lab/docker-hour5-myapp.git#refs/heads/main pkg:docker/python@3.13-slim?platform=linux%2Famd64 pkg:docker/docker/buildkit-syft-scanner@stable-1
The provenance field layout depends on the SLSA version (v0.2 uses invocation / materials, v1 uses buildDefinition / resolvedDependencies); the jq above handles both. For local builds the source URL may be empty; in CI it includes the repo and commit.
printf 'vulnerabilities: []\n' > .trivyignore.yaml
printf '{"@context":"https://openvex.dev/ns/v0.2.0","@id":"https://example.com/vex/empty","author":"team-myapp","timestamp":"2026-11-17T00:00:00Z","version":1,"statements":[]}\n' > openvex.json
make scan REGISTRY=$REG; echo "exit=$?"
acrhour312345.azurecr.io/myapp@sha256:9c1e… (debian 13.2) Total: 0 (HIGH: 0, CRITICAL: 0) Python (python-pkg) Total: 0 (HIGH: 0, CRITICAL: 0) exit=0
git switch -c vuln-demo
echo 'cryptography==41.0.7' >> requirements.txt # old version with known HIGH vulnerabilities
docker buildx bake -f docker-bake.hcl test && docker image save myapp:ci -o /tmp/ci.tar
docker run --rm -v /tmp/ci.tar:/ci.tar:ro -v trivy-cache:/root/.cache/ aquasec/trivy:0.76.2 image \
--input /ci.tar --severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 --format table | tail -8; echo "exit=${PIPESTATUS[0]}"
git restore requirements.txt && git switch main && git branch -D vuln-demo
│ cryptography │ CVE-2023-50782 │ HIGH │ fixed │ 41.0.7 │ 42.0.0 │ … │ cryptography │ CVE-2024-26130 │ HIGH │ fixed │ 41.0.7 │ 42.0.4 │ … Total: 2 (HIGH: 2, CRITICAL: 0) exit=1
This scans a local tar (docker image save), which also needs no socket; actual CVE IDs and counts depend on that day's vulnerability database. Cleanup: rm -f /tmp/ci.tar sbom.spdx.json prov.json; you can keep the trivy-cache volume to speed up later scans.
Case 1: one critical vulnerability, 7 services located in 20 minutes
Problem: a critical vulnerability was published in a foundational library. Approach: on every release the platform team exported the SBOM to a central store (or read the attestation from the registry by digest), then bulk-rescanned every "currently running digest" (taken from the environment manifests) with grype sbom:. Within 20 minutes they had listed the 7 affected services and their owners, and the dependency bot then opened upgrade PRs. Limitation: an SBOM only covers packages the scanner can recognize; binaries fetched manually with curl need a recognizable install method in the Dockerfile or a supplemental SBOM.
Case 2: everyone hated the gate, then it was switched off
Problem: the team initially set the gate to "fail on anything MEDIUM or above". Masses of vulnerabilities with no fixed version blocked releases every day, until someone changed the scan step to || true. Approach: change the threshold to "CRITICAL/HIGH with a fixed version"; report everything else onto a weekly board; introduce an exception process with expiry dates, plus VEX. Limitation: high-severity vulnerabilities "without a fixed version" still need a risk assessment (switch base image, mitigations).
Case 3: the scanner stole secrets from the runner
Problem: in March 2026, pipelines using aquasec/trivy:latest or referencing trivy-action by tag ran malicious code during the incident window; some pipelines also mounted docker.sock and held cloud credentials in the same job. Approach: run scanning in a separate job with no cloud write permissions (registry read access only); pin the scanner image by digest and verify its signature; never mount the socket; pin Actions by SHA. Limitation: pinned versions require a dependency bot and advisory monitoring to keep up with upgrades.
Common errors and fixes
template: :1:… error calling index: map has no entry for key "linux/amd64"
Cause: the image was built for a single platform (.SBOM is not a per-platform map), or no SBOM was generated at build time.
docker buildx imagetools inspect "$REG/myapp@$D" --raw | jq '.manifests[] | {p:.platform, t:.annotations["vnd.docker.reference.type"]}'
Fix: for single-platform images use --format '{{ json .SBOM.SPDX }}'; make sure the build includes attest type=sbom.
FATAL … unable to find the specified image … UNAUTHORIZED: authentication required (Trivy container)
Cause: the mounted config.json holds no actual credentials (a credsStore credential helper is in use), or the token has expired (ACR refresh tokens last about 3 hours).
jq '{credsStore, auths: (.auths | keys)}' ~/.docker/config.json
Fix: in CI, run az acr login / docker login again; locally use -e TRIVY_USERNAME -e TRIVY_PASSWORD (for ACR, get a token with az acr login --expose-token; the username is 00000000-0000-0000-0000-000000000000).
Scan results differ every day / the same image passed yesterday and fails today
Cause: the vulnerability database was updated - this is expected behavior.
Fix: the CI gate only decides "can a new version be released"; new vulnerabilities in images already in production are handled by continuous scanning and weekly rebuilds. When you need reproducibility, record the database version in the report (trivy --version shows the DB update time).
failed to parse ignore file: yaml: … / the exception has no effect
Cause: a YAML exception file must end in .yaml and be passed with --ignorefile; expired_at has passed; paths does not match the actual path.
Fix: first remove paths to confirm the ID matches, then tighten it again; the gate failing again after an exception expires is by design.
1. From sbom.spdx.json, list the names and versions of all Python packages (sorted by name).
jq -r '.packages[] | select(any((.externalRefs // [])[]; (.referenceLocator // "") | startswith("pkg:pypi/"))) | "\(.name)\t\(.versionInfo)"' sbom.spdx.json | sort -u2. Use Grype with JSON output and count only the CRITICAL vulnerabilities that have a fixed version.
docker run --rm -v "$PWD:/src:ro" anchore/grype:v0.122.0 sbom:/src/sbom.spdx.json -o json \ | jq '[.matches[] | select(.vulnerability.severity=="Critical" and .vulnerability.fix.state=="fixed")] | length'
A customer requires an SBOM with every release, and proof that "this SBOM corresponds to the image you deployed". What do you do?
① Have BuildKit generate the SBOM as an attestation at build time, in the same index as the image - the SBOM is inherently bound to the digest; ② at release time, export SPDX with imagetools inspect (and regenerate CycloneDX with Syft if needed); ③ use cosign to sign the SBOM and attach it to the digest as an attestation (cosign attest --type spdxjson), so the customer can use cosign verify-attestation to verify both the signer identity and the SBOM content; ④ list version → digest → SBOM download link in the release notes; ⑤ attach VEX documenting the vulnerabilities analyzed as "not affected".
Verified teaching videos
Official documentation
- SBOM attestations · Provenance attestations · Attestation storage
- Trivy: Filtering (ignore files, VEX) · Grype · Syft · Docker Scout
- Aqua: Trivy supply chain attack — what you need to know · OpenVEX
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; the storyboard and narration below can be handed to a video tool.
Visual: the image index opens like a folder. Besides the amd64 and arm64 layer files there are two "manuals": a parts list (the SBOM) and a certificate of origin (the provenance).
Narration: BuildKit puts the bill of materials and the build provenance into the image index at build time.
Visual: the scanner pulls the image from the registry by digest and a vulnerability list scrolls by; only "red entries with a fix arrow" bring the barrier down, the rest go onto a board. An exception card with a calendar is voided automatically when it expires.
Narration: block only severe, fixable vulnerabilities; every exception needs a reason and an expiry date.
Visual: a scanner image labeled latest gets a skull stamp; next to it is a scanner labeled with a pinned version and digest, with no cable plugged into docker.sock.
Narration: the scanner is part of the supply chain too: pin the version, verify the signature, and never give it host privileges.
Module 6 · Signing and Verification: cosign and Notation
- Explain what signing solves and where it stops: it binds a signer identity to a digest; it does not judge whether the content is safe (that is Module 5's job).
- Use cosign for keyless signing (CI's OIDC identity → short-lived Fulcio certificate → Rekor transparency log) and KMS key signing (Azure Key Vault / AWS KMS), and verify precisely with
--certificate-identityand--certificate-oidc-issuer. - Understand the Notation route: the Azure Key Vault plugin, the AWS Signer plugin and ECR managed signing (automatic signing on push), plus trust policies and trust stores.
- Put verification in the right place: a pre-deployment gate in the pipeline + deploy by digest (ACA, ECS); Kubernetes clusters verify with admission control (only touched on here).
What: the two signing ecosystems
| Sigstore cosign | Notary Project Notation | |
|---|---|---|
| Identity model | keyless: CI's OIDC identity is exchanged for a roughly 10-minute certificate issued by Fulcio, and the signature is recorded in Rekor; or a KMS / local key | X.509 certificate chain (self-signed or CA-issued), with keys held in plugin backends such as Key Vault or AWS Signer |
| Azure | azurekms:// keys or keyless | Official approach: Notation + Key Vault (notation-azure-kv plugin v1.2.1) or Notation + Artifact Signing |
| AWS | awskms:// keys or keyless | AWS Signer plugin; ECR managed signing (since 2025-11): ECR calls AWS Signer to sign automatically on push, up to 10 signing rules per registry |
| Where it is stored | v3 uses the Sigstore bundle format by default, attached to the digest as an OCI referrer (the old sha256-….sig tag scheme requires explicitly turning off the new format) | OCI referrer (application/vnd.cncf.notary.signature) |
| Verification config | Command flags: identity (workflow URL) + issuer, or a public key | trustpolicy.json (registry scopes, trust stores, trusted identities) |
Why: a digest is not enough, you also need a signature
A digest only proves "the content has not changed". If an attacker obtains write access to the registry (or the CI is impersonated), the malicious image they push also has a perfectly valid digest. A signature turns "who vouches for this digest" into a verifiable fact: the verifier only accepts images "signed by image-ci.yml of github.com/<org>/docker-hour5-myapp on the main branch". With keyless, the identity is the workflow's OIDC claims, and there is no private key to safeguard.
How: keyless signing in five steps
- The CI job (with
id-token: write) requests an OIDC token from GitHub with audiencesigstore. - cosign generates an ephemeral key pair and sends the public key and token to Fulcio; Fulcio verifies the token and issues a certificate valid for about 10 minutes, whose extension fields record the issuer, workflow path, repository, commit and trigger event.
- cosign signs the digest with the ephemeral private key, submits the signature and certificate to the Rekor transparency log, and gets back an entry with a timestamp (proving "the certificate was valid at signing time").
- The signature, certificate and Rekor proof are packaged as a bundle and pushed to the registry as a referrer; the ephemeral private key is discarded.
- The verifier runs
cosign verify --certificate-identity … --certificate-oidc-issuer …to check: the signature is correct, the certificate chains to the Fulcio root, the entry exists in Rekor, and the identity and issuer match exactly.
When: where to verify
| Location | Azure | AWS | Notes |
|---|---|---|---|
| In the pipeline before deployment (this lesson) | Run az containerapp update / aws ecs update-service only if make verify succeeds, and pass only the digest | Container Apps and ECS do not verify signatures at pull time (check the official docs), so the gate must live in the pipeline | |
| Kubernetes admission | AKS: Ratify + Azure Policy | EKS: Kyverno / Ratify + Gatekeeper | See Kubernetes hour 5, Module 6 (Chinese) |
| At promotion / copy time | The promotion job first verifies the signature of the source digest (Module 4's promote.yml) | Prevents "an unsigned image copied into the production registry" | |
--certificate-identity-regexp '.*' to get verification working first" - that accepts anything anyone signed on the public Sigstore instance, so verification becomes meaningless. ③ "Signing the tag is enough" - signatures always target a digest; when you deploy by tag, the tag may be rewritten between a successful verification and the actual pull. ④ "Turning on ECR managed signing gives us a gate" - it only signs; verification still has to happen in the deployment pipeline or in admission control.Architecture: keyless signing and verification
Comparison: three Notation backends
Interactive simulator: sign → verify → deploy
Pick a scenario and play it to see cosign's real order of checks and failure messages (output is illustrative).
Core commands
| Command | Purpose | Notes |
|---|---|---|
cosign sign --yes REG/myapp@sha256:… | Keyless signing (picks up the OIDC token automatically in CI) | Run locally, it opens a browser to log in |
cosign verify REF@DIGEST --certificate-identity URL --certificate-oidc-issuer https://token.actions.githubusercontent.com | Verify a keyless signature | For tag builds use --certificate-identity-regexp '^https://github\.com/ORG/REPO/\.github/workflows/image-ci\.yml@refs/tags/v.*$' |
cosign generate-key-pair --kms azurekms://KV.vault.azure.net/cosign-myapp | Create a signing key in Key Vault | AWS: awskms:///alias/cosign-myapp |
cosign sign --key azurekms://… REF@DIGEST / cosign verify --key … | Sign / verify with a KMS key | The private key never leaves KMS |
cosign attest --yes --type spdxjson --predicate sbom.spdx.json REF@DIGEST | Attach the SBOM as a signed attestation | cosign verify-attestation --type spdxjson … |
cosign tree REF@DIGEST / oras discover REF@DIGEST | List signatures and attestations attached to a digest | Debugging "where did my signature go" |
notation sign REF@DIGEST --key kv-cert / notation verify REF@DIGEST | Notation sign / verify | Requires a trust policy and trust store |
aws ecr put-signing-configuration --signing-configuration file://signing-config.json | Enable ECR managed signing | Check results with describe-image-signing-status |
Makefile additions: sign and verify
GH_REPO ?= $(shell gh repo view --json nameWithOwner -q .nameWithOwner 2>/dev/null)
SIGNER_ID ?= https://github.com/$(GH_REPO)/.github/workflows/image-ci.yml@refs/heads/main
OIDC_ISS ?= https://token.actions.githubusercontent.com
sign: ## keyless-sign the digest in .digest (runs in CI; needs id-token: write)
> cosign sign --yes "$(REGISTRY)/myapp@$$(cat .digest)"
verify: ## resolve the digest from the sha- candidate tag and verify the signer identity; non-zero exit on failure
> d=$$(docker buildx imagetools inspect "$(REGISTRY)/myapp:sha-$(GIT_SHA)" --format '{{json .Manifest.Digest}}' | tr -d '"'); \
cosign verify "$(REGISTRY)/myapp@$$d" --certificate-identity "$(SIGNER_ID)" \
--certificate-oidc-issuer "$(OIDC_ISS)" -o json | jq -r '.[0].optional.Subject // "verified"'; \
echo "$$d" > .digest
Workflow additions: scanning and signing in the release job
- uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3
with: { cosign-release: v3.1.4 }
- run: make scan REGISTRY="$ACR.azurecr.io" # Module 5
- run: |
make sign REGISTRY="$ACR.azurecr.io"
make sign REGISTRY="$ECR" # sign once on each side (same identity)
make verify REGISTRY="$ECR" GH_REPO="$GITHUB_REPOSITORY"
Why it is written this way: signing lives in the release job (which already has id-token: write), and scanning comes before signing - a digest that fails the scan is never signed, and deployment only accepts signed digests, so the "scan gate" automatically extends to deployment. Common mistakes: the workflow file name or branch in SIGNER_ID does not match reality; when signing from a reusable workflow, the identity in the certificate is the path of the called workflow.
Notation + AWS Signer (ECR managed signing) snippet
aws signer put-signing-profile --profile-name myappSigning --platform-id Notation-OCI-SHA384-ECDSA \
--query profileVersionArn --output text
cat > signing-config.json <<EOF
{ "rules": [ { "signingProfileArn": "arn:aws:signer:${AWS_REGION}:${ACCOUNT_ID}:/signing-profiles/myappSigning",
"repositoryFilters": [ { "filter": "myapp", "filterType": "WILDCARD_MATCH" } ] } ] }
EOF
aws ecr put-signing-configuration --signing-configuration file://signing-config.json
# from now on, ECR signs automatically on every push to myapp:
aws ecr describe-image-signing-status --repository-name myapp --image-id imageTag=sha-3f9a2c1
The pusher (the CI role) needs the additional signer:SignPayload permission (on that signing profile). Verification still uses the Notation CLI + AWS Signer plugin and a trust policy (trust store signingAuthority:aws-signer-ts, trusted identity = the signing profile ARN). For the certificate policy and trust policy of the Azure Key Vault route, see the official tutorial (linked on the sources page).
Lab 6: sign, verify, and "no deployment if verification fails" (about 6 minutes)
source ~/hour5.env; cd ~/myapp
REG=${ACR_LOGIN:-$ECR}; D=$(cat .digest)
export COSIGN_PASSWORD='lab-only-passphrase'
cosign generate-key-pair --output-key-prefix ~/cosign-lab
cosign sign --yes --key ~/cosign-lab.key --tlog-upload=false "$REG/myapp@$D"
cosign verify --key ~/cosign-lab.pub --insecure-ignore-tlog=true "$REG/myapp@$D" -o json | jq -r '.[0].critical.image."docker-manifest-digest"'
oras discover "$REG/myapp@$D" --format tree
Private key written to /home/azureuser/cosign-lab.key Public key written to /home/azureuser/cosign-lab.pub sha256:9c1e4b7a2f…d81 acrhour312345.azurecr.io/myapp@sha256:9c1e4b7a2f…d81 ├── application/vnd.dev.sigstore.bundle.v0.3+json │ └── sha256:4a7f… └── application/vnd.docker.attestation.manifest.v1+json (shown only when the referrers view is enabled)
--tlog-upload=false keeps the lab signature out of the public Rekor; verification correspondingly uses --insecure-ignore-tlog. Do not use either flag in a production keyless flow. The exact tree printed by oras discover may differ in practice.
git add Makefile .github/workflows/image-ci.yml .trivyignore.yaml openvex.json git commit -qm "ci: scan and keyless sign" && git push && gh run watch --exit-status gh run view --log --job release | grep -E 'tlog entry created|Pushing signature|verified' | head
tlog entry created with index: 812345678 Pushing signature to: acrhour312345.azurecr.io/myapp https://github.com/andy-lab/docker-hour5-myapp/.github/workflows/image-ci.yml@refs/heads/main
git pull -q; export GIT_SHA=$(git rev-parse --short=7 HEAD) make verify REGISTRY=$REG GH_REPO=$GH_REPO cosign verify "$REG/myapp@$(cat .digest)" \ --certificate-identity "https://github.com/$GH_REPO/.github/workflows/image-ci.yml@refs/heads/dev" \ --certificate-oidc-issuer https://token.actions.githubusercontent.com 2>&1 | tail -1
https://github.com/andy-lab/docker-hour5-myapp/.github/workflows/image-ci.yml@refs/heads/main Error: no matching signatures: none of the expected identities matched what was in the certificate, got subjects [https://github.com/andy-lab/docker-hour5-myapp/.github/workflows/image-ci.yml@refs/heads/main] with issuer https://token.actions.githubusercontent.com
if make verify REGISTRY=$ACR_LOGIN GH_REPO=$GH_REPO; then
az containerapp update -g $RG -n $APP --image "$ACR_LOGIN/myapp@$(cat .digest)" \
--revision-suffix "s$GIT_SHA" -o none && echo "deployed signed digest"
else echo "signature verification failed, NOT deploying" >&2; fi
Cleanup: rm -f ~/cosign-lab.key ~/cosign-lab.pub. Signatures in the registry are deleted along with the image. If ECR managed signing is enabled, Module 8 turns it off with aws ecr delete-signing-configuration and cancels the signing profile.
Case 1: stolen registry credentials failed to get a malicious image into production
Problem: an ACR refresh token was stolen from a developer's laptop, and the attacker pushed a backdoored myapp:sha-…. Approach: the deployment pipeline only deploys digests that pass cosign verify (identity = image-ci.yml on main); the attacker cannot get GitHub to issue an OIDC token for their image, so verification fails, and the release is aborted and alerted on. Limitation: if the attacker can modify the workflow on main, the signature will be produced just as "legitimately" - branch protection and code review are still the foundation.
Case 2: migrating from self-managed certificates to managed signing
Problem: the team used Notation + Key Vault with a self-signed certificate; on the day it expired, every deployment halted on verification failures. Approach: on Azure, migrate to Artifact Signing (short-lived certificates issued automatically); on AWS, enable ECR managed signing; alert 30 days before certificate expiry. Limitation: the trust policy has to trust both old and new identities for a while, so that images with old signatures can still be rolled back to.
Case 3: a reusable workflow causes an identity mismatch
Problem: the platform team moved build and signing into an organization-level reusable workflow that each repository calls; the verification policy still named each repository's own image-ci.yml, and every verification failed. Approach: the SAN in the certificate is the path of the called workflow (e.g. platform/.github/.github/workflows/build.yml@refs/tags/v3), while the calling repository is recorded in other certificate extensions; verification switches to the platform workflow identity and restricts the calling repository with extension flags such as --certificate-github-workflow-repository. Limitation: releasing and pinning the platform workflow becomes a critical control point.
Common errors and fixes
Error: no matching signatures: none of the expected identities matched what was in the certificate
Cause: --certificate-identity does not match the SAN in the certificate: different branch/tag, different workflow file name, a reusable workflow was used, or the repository was renamed.
cosign verify REF@DIGEST --certificate-identity-regexp '.*' --certificate-oidc-issuer-regexp '.*' -o json \
| jq -r '.[0].optional | {Subject, Issuer}' # for troubleshooting only; once you see the real identity, switch back to an exact match
Fix: change the verification flags to the actual identity in the certificate (or a precise regex).
Error: no signatures found / no matching attestations
Cause: the digest being verified is not the one that was signed (a child manifest was referenced, the image was rebuilt, a tag resolved to a new digest), or referrers were not copied along when copying to another registry.
cosign tree REF@DIGEST; oras discover REF@DIGEST --format tree
Fix: always sign and verify the top-level index digest; across registries use oras cp -r or re-sign at the destination.
getting signer: getting key from Fulcio: … error obtaining token: … ACTIONS_ID_TOKEN_REQUEST_URL
Cause: the job containing the signing step does not have id-token: write.
Fix: add it to the signing job's permissions; do not put signing in PR jobs.
notation verify: … trust policy is not present / no applicable trust policy for artifact
Cause: no trust policy was imported, or registryScopes does not exactly match the image repository address (it includes the login server and is case-sensitive).
notation policy show; notation cert ls
Fix: notation policy import trustpolicy.json --force, with the scope written as acrhour312345.azurecr.io/myapp or 111122223333.dkr.ecr.ca-central-1.amazonaws.com/myapp.
AccessDeniedException: … is not authorized to perform: signer:SignPayload (push fails or signing status is FAILED after enabling ECR managed signing)
Cause: managed signing calls AWS Signer with the identity of the pusher, and the CI role lacks that permission.
Fix: grant docker-hour5-gha signer:SignPayload on the signing profile; confirm with describe-image-signing-status.
1. Verify an image signed by the release.yml workflow triggered by a v* tag (any version tag).
cosign verify "$REG/myapp@$D" \
--certificate-identity-regexp "^https://github\.com/${GH_REPO//\//\\/}/\.github/workflows/release\.yml@refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$" \
--certificate-oidc-issuer https://token.actions.githubusercontent.com2. Use cosign to attach the SBOM to the digest as an attestation, and verify the number of packages in the attested SBOM.
cosign attest --yes --type spdxjson --predicate sbom.spdx.json "$REG/myapp@$D" cosign verify-attestation --type spdxjson "$REG/myapp@$D" \ --certificate-identity "$SIGNER_ID" --certificate-oidc-issuer https://token.actions.githubusercontent.com \ | jq -r '.payload' | base64 -d | jq '.predicate.packages | length'
The company uses both Azure and AWS, and the security team wants "one signing setup, verifiable on both sides". How would you achieve that with cosign keyless and with Notation?
cosign keyless: the simplest - the same CI identity signs the same digest in each of the two registries (or signs once and copies the referrer with oras cp -r), and the verification flags are identical on both sides (workflow identity + issuer), with no keys to manage. You have to accept that signature records go into the public Rekor (or run your own Sigstore). Notation: choose a cross-cloud certificate scheme (signing certificates issued by an enterprise CA, with the private key in Key Vault or in AWS KMS/Signer), and have the trust policies on both sides trust the same CA and certificate subject; if each side uses its own managed service (Artifact Signing, ECR managed signing), the trust policy must list both identities. The key point: the verification policy accepts only a few explicit identities, and it is enforced uniformly in the deployment pipeline.
Verified teaching videos
Official documentation
- Sigstore: Signing containers · Verifying signatures · Cosign 3.0 release notes
- ACR: Sign and verify artifacts (overview) · Notation + Key Vault tutorial
- ECR: Managed signing · AWS Signer: signing container images
- Cluster-side verification: Kubernetes hour 5, Module 6: admission control (Chinese)
Video storyboard (about 70 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.
Visual: two images with perfectly valid digests side by side, one from CI, one from an attacker; the digest alone cannot tell them apart.
Narration: a digest proves the content has not changed, but it cannot prove who released it.
Visual: the CI job carries a GitHub token to Fulcio and receives a certificate that vanishes after ten minutes; after signing, it pins the record to the Rekor bulletin board and hangs the signature bundle next to the image.
Narration: keyless signing has no private key to safeguard; what you trust is "which workflow in which repository".
Visual: the deployment gate checks the signer identity; the attacker's image is stopped, and the CI image passes by digest into Container Apps and ECS.
Narration: verification must happen before deployment, and only digests get deployed.
Module 7 · Release and Rollback: Container Apps Traffic Splitting vs ECS Blue/Green
- Compare the release mechanisms of the two clouds: Container Apps uses revisions + traffic weights + label URLs (driven by the pipeline); ECS uses native blue/green / rolling (driven by the service itself, with the circuit breaker and CloudWatch alarms triggering rollback).
- Write a pipeline release script: deploy by digest → 0% smoke test → 10% canary → observe → 100% or automatic rollback, and write the outcome to the release record.
- Define the minimum signal set for a release decision (5xx ratio, latency, restarts/task stops, version probe), and know which course covers full monitoring and alerting.
- Recognize the "rolled back the image but not the problem" situation: app-level configuration, secret values and database migrations are not rolled back with a revision / task definition.
What: two models of "who controls traffic"
| Azure Container Apps | Amazon ECS (Fargate + ALB) | |
|---|---|---|
| Release unit | Revision: an immutable snapshot of the image + revision-scoped configuration (containers, scaling, probes) | Task definition revision + service deployment |
| Traffic control | Revision weights on ingress (ingress traffic set), any ratio, adjusted step by step by your pipeline | ROLLING: old and new tasks coexist and are replaced in batches; BLUE_GREEN / LINEAR / CANARY: ECS rewrites the weights of the two target groups in the ALB listener rule, advanced automatically by the service according to its configuration |
| Pre-release testing | Revision label URL: myapp---canary.<env>…, reachable even at 0% traffic | Test listener rule + lifecycle hooks (Lambda) |
| Automatic rollback trigger | No built-in automatic rollback: the pipeline switches the weights back to the old revision based on signals | Deployment circuit breaker (task start/health failures) + CloudWatch alarms (alarms={…,rollback=true}) + hook failures; blue/green can roll back during bake time |
| Manual rollback | traffic set OLD=100 (seconds) or create a new revision from the old digest | stop-service-deployment --stop-type ROLLBACK or deploy the previous task definition |
| CodeDeploy | — | Legacy approach (deploymentController=CODE_DEPLOY); prefer ECS native blue/green for new services (compared in hour 4) |
Why: progressive rollout + automatic rollback
No test suite covers real traffic. A progressive rollout shrinks the "blast radius of a bad version" from 100% of users to canary ratio × observation time; automatic rollback shrinks the "detect → find someone → act manually" cycle from a dozen-plus minutes to one detection period. The difference between the two clouds is who executes: ACA hands the decision to your pipeline, ECS writes the decision into the service configuration.
How: the minimum signal set for a release decision
| Signal | Where ACA gets it | Where ECS gets it | Typical threshold (example) |
|---|---|---|---|
| 5xx ratio | Platform metric Requests (split by revision and status code class) or Application Insights | ALB target group HTTPCode_Target_5XX_Count / RequestCount | Canary > 1% and absolute count > 5 |
| Latency | Application Insights / OpenTelemetry | ALB TargetResponseTime p95 | 50% above baseline |
| Restarts / stops | RestartCount, system logs | Task stop reasons, circuit breaker | > 0 during the window needs human judgment |
| Version probe | /healthz or / returns APP_VERSION, confirming traffic really reaches the new version | Must equal the version in the release record | |
When: how long to observe
Cover at least one full "request pattern cycle": if background jobs fire on a schedule, cover their interval; for services with noticeable cache warm-up, get past the cold-start period. In the lab we use 2 minutes of curl sampling instead of real metric queries; in production, use a metric query (or alarm state) as the gate and observe for 10–30 minutes.
Architecture: one digest, two ways to shift traffic
Sequence: one canary release with automatic rollback
Interactive simulator: traffic shifting and automatic rollback
Pick a platform and an outcome, then play; watch the traffic bar and the CLI / API call behind each step (output is illustrative).
Core commands
| Command | Purpose | Notes |
|---|---|---|
az containerapp revision set-mode -g $RG -n $APP --mode multiple | Enable multiple revisions | Only needed once |
az containerapp update … --image REG/myapp@sha256:… --revision-suffix g3f9a2c1 | Create a new revision by digest | Use the short commit as the suffix so it maps to the release record |
az containerapp ingress traffic set … --revision-weight OLD=90 NEW=10 | Adjust weights | Must sum to 100 |
az containerapp revision label add … --label canary --revision NEW | Give a revision a label URL | Reachable even at 0% |
aws ecs update-service … --deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},alarms={alarmNames=[myapp-5xx],enable=true,rollback=true}" | Circuit breaker + alarm rollback | Alarms can be configured for both rolling and blue/green |
aws cloudwatch put-metric-alarm --alarm-name myapp-5xx --namespace AWS/ApplicationELB --metric-name HTTPCode_Target_5XX_Count … | Alarm used for rollback | Dimensions are the ARN suffixes of the target group and load balancer |
aws ecs list-service-deployments --cluster $CLUSTER --service $SVC | Deployment history and status | SUCCESSFUL / ROLLBACK_SUCCESSFUL, etc. |
aws ecs stop-service-deployment --service-deployment-arn ARN --stop-type ROLLBACK | Manually roll back an in-progress deployment | Check parameters against the CLI reference |
ci/deploy-aca.sh: 0% → smoke → 10% → 100% or rollback
#!/usr/bin/env bash
# Usage: RG=… APP=… ci/deploy-aca.sh IMAGE@DIGEST SUFFIX -- requires make verify to have passed
set -euo pipefail
img=${1:?image@digest}; sfx=${2:?revision suffix}
[[ $img == *@sha256:* ]] || { echo "refuse: deploy by digest only" >&2; exit 2; }
: "${RG:?}" "${APP:?}"; WINDOW=${WINDOW:-60}; MAXERR=${MAXERR:-2}
az containerapp revision set-mode -g "$RG" -n "$APP" --mode multiple -o none
old=$(az containerapp revision list -g "$RG" -n "$APP" \
--query "[?properties.active && properties.trafficWeight > \`0\`].name | [0]" -o tsv)
[[ -n $old ]] || { echo "no revision is receiving traffic; pin once: traffic set --revision-weight latest=100" >&2; exit 2; }
new="$APP--$sfx"
az containerapp update -g "$RG" -n "$APP" --image "$img" --revision-suffix "$sfx" \
--set-env-vars APP_VERSION="$sfx" -o none
az containerapp ingress traffic set -g "$RG" -n "$APP" --revision-weight "$old=100" "$new=0" -o none
az containerapp revision label add -g "$RG" -n "$APP" --label canary --revision "$new" -o none
fqdn=$(az containerapp show -g "$RG" -n "$APP" --query properties.configuration.ingress.fqdn -o tsv)
canary="${APP}---canary.${fqdn#*.}"
rollback() { az containerapp ingress traffic set -g "$RG" -n "$APP" --revision-weight "$old=100" "$new=0" -o none
echo "::error::rolled back to $old ($1)"; exit 1; }
curl -fsS --retry 10 --retry-delay 6 --retry-all-errors "https://$canary/healthz" >/dev/null || rollback "smoke"
az containerapp ingress traffic set -g "$RG" -n "$APP" --revision-weight "$old=90" "$new=10" -o none
errs=0
for _ in $(seq "$WINDOW"); do
code=$(curl -s -o /dev/null -w '%{http_code}' "https://$fqdn/") || code=000
[[ $code -ge 500 || $code == 000 ]] && errs=$((errs+1)); sleep 2
done
echo "5xx during canary: $errs"
(( errs <= MAXERR )) || rollback "5xx=$errs"
az containerapp ingress traffic set -g "$RG" -n "$APP" --revision-weight "$new=100" "$old=0" -o none
az containerapp revision label remove -g "$RG" -n "$APP" --label canary -o none
az containerapp revision deactivate -g "$RG" -n "$APP" --revision "$old" -o none
echo "released $new ($img); previous=$old"
Why it is written this way: it refuses non-digest references; the rollback target is "the revision that was taking traffic before the deployment", and rollback only changes weights (seconds); the old revision is deactivated only after success. The lab uses curl sampling instead of a metric query — in production, replace the sampling loop with a per-revision 5xx metric query or Application Insights (see Prometheus & Grafana hour 3). Common mistake: take the label URL format from the output of az containerapp revision label.
ci/deploy-ecs.sh: replace only the image, leave the rest to the service's deployment strategy
#!/usr/bin/env bash
# Usage: CLUSTER=… SVC=… ci/deploy-ecs.sh IMAGE@DIGEST
set -euo pipefail
img=${1:?image@digest}; [[ $img == *@sha256:* ]] || { echo "refuse: deploy by digest only" >&2; exit 2; }
: "${CLUSTER:?}" "${SVC:?}"
td=$(aws ecs describe-services --cluster "$CLUSTER" --services "$SVC" --query 'services[0].taskDefinition' --output text)
aws ecs describe-task-definition --task-definition "$td" --query taskDefinition \
| jq --arg img "$img" '.containerDefinitions[0].image=$img
| del(.taskDefinitionArn,.revision,.status,.requiresAttributes,.compatibilities,.registeredAt,.registeredBy)' > /tmp/td.json
new=$(aws ecs register-task-definition --cli-input-json file:///tmp/td.json --query taskDefinition.taskDefinitionArn --output text)
aws ecs update-service --cluster "$CLUSTER" --service "$SVC" --task-definition "$new" >/dev/null
echo "deploying $new"
for _ in $(seq 120); do
read -r arn st < <(aws ecs list-service-deployments --cluster "$CLUSTER" --service "$SVC" --max-results 1 \
--query 'serviceDeployments[0].[serviceDeploymentArn,status]' --output text)
case $st in
SUCCESSFUL) echo "released $new"; exit 0 ;;
ROLLBACK_SUCCESSFUL|ROLLBACK_FAILED|STOPPED) echo "::error::deployment $st ($arn)"; exit 1 ;;
esac; sleep 15
done
echo "::error::timeout waiting for $arn"; exit 1
ECS keeps the deployment strategy (rolling / blue/green, circuit breaker, alarms, bake time) on the service; the script is only responsible for "publish a new task definition by digest + wait for a terminal state". Check the deployment status enum and the filter parameters of list-service-deployments against the AWS CLI reference.
Lab 7: pipeline-driven canary and rollback drill (about 8 minutes)
source ~/hour5.env; cd ~/myapp; export GIT_SHA=$(git rev-parse --short=7 HEAD) make verify REGISTRY=$ACR_LOGIN GH_REPO=$GH_REPO chmod +x ci/deploy-aca.sh RG=$RG APP=$APP WINDOW=30 ci/deploy-aca.sh "$ACR_LOGIN/myapp@$(cat .digest)" "g$GIT_SHA" az containerapp ingress traffic show -g $RG -n $APP -o table
5xx during canary: 0 released myapp--g3f9a2c1 (acrhour312345.azurecr.io/myapp@sha256:9c1e…); previous=myapp--g2a1b3c RevisionName Weight Label ----------------- -------- ------- myapp--g3f9a2c1 100
/ return 500 while /healthz stays healthy (exactly the case the circuit breaker/probes cannot catch); build, scan and sign it, then deploy:
git switch -c bad-release
python3 - <<'EOF'
import re,io
s=io.open("app.py",encoding="utf-8").read()
s=re.sub(r'(@app\.route\("/"\)\s*\ndef \w+\(\):\s*\n)', r'\1 raise RuntimeError("boom")\n', s, count=1)
io.open("app.py","w",encoding="utf-8").write(s)
EOF
git commit -qam "test: bad release (500 on /)"
make release REGISTRY=$ACR_LOGIN GIT_SHA=$(git rev-parse --short=7 HEAD) # local release candidate (lab only; production goes through CI + signing)
RG=$RG APP=$APP WINDOW=30 ci/deploy-aca.sh "$ACR_LOGIN/myapp@$(cat .digest)" "bad$(git rev-parse --short=5 HEAD)"; echo "exit=$?"
curl -s "https://$FQDN/"; echo
git switch main && git branch -D bad-release
5xx during canary: 4 ::error::rolled back to myapp--g3f9a2c1 (5xx=4) exit=1 [g3f9a2c1] Hello from myapp--g3f9a2c1-…, hits=N/A
With 10% of traffic going to the bad revision, roughly 1 in 10 requests fails, so 2–5 errors in 30 samples is normal (random); tune MAXERR if needed. If your app.py defines the route differently, just edit it by hand so that / raises an exception.
source ~/hour5.env
TG_DIM=${TG_BLUE##*:}; LB_DIM=$(echo "$ALB_ARN" | sed 's#.*:loadbalancer/##')
aws cloudwatch put-metric-alarm --alarm-name myapp-5xx --namespace AWS/ApplicationELB \
--metric-name HTTPCode_Target_5XX_Count --dimensions Name=TargetGroup,Value=$TG_DIM Name=LoadBalancer,Value=$LB_DIM \
--statistic Sum --period 60 --evaluation-periods 1 --threshold 5 --comparison-operator GreaterThanThreshold \
--treat-missing-data notBreaching --tags Key=course,Value=docker-hour5
aws ecs update-service --cluster $CLUSTER --service $SVC \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},alarms={alarmNames=[myapp-5xx],enable=true,rollback=true}" \
--query 'service.deploymentConfiguration.alarms' --output json
chmod +x ci/deploy-ecs.sh; CLUSTER=$CLUSTER SVC=$SVC ci/deploy-ecs.sh "$ECR/myapp@$(cat .digest)"
{ "alarmNames": ["myapp-5xx"], "rollback": true, "enable": true }
deploying arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:15
released arn:aws:ecs:ca-central-1:111122223333:task-definition/myapp:15
If you switched the service to BLUE_GREEN in hour 4, do not overwrite strategy and bakeTimeInMinutes when calling update-service (the AWS CLI replaces --deployment-configuration as a whole, so read the current values with describe-services first and write them back together). The target group dimension must be the target group currently taking production traffic; it changes after a blue/green switch, so in production it is more common to alarm at the load balancer level or to have one alarm per target group.
/, replace sampling with a metric query).Cleanup: the myapp-5xx alarm and the extra task definition revisions are deleted in Module 8; the failed ACA revision has been deactivated and is no longer billed.
Case 1: a Friday-night release, from 18 minutes down to 2
Problem: without a canary, a serialization bug made 100% of requests fail for 18 minutes (6 minutes to detect + 8 minutes to find someone + 4 minutes to roll back by hand). Approach: a pipeline canary on ACA (10%, 10 minutes, judged on per-revision 5xx metrics) + automatic rollback; alarm rollback configured on the ECS service. Result: the same class of problem now affects only 10% of requests for about 2 minutes. Limitation: the observation window makes releases longer, so concurrency control is needed to avoid a queue.
Case 2: the image was rolled back, but the outage did not go away
Problem: the release also rotated the Redis password in Key Vault and referenced the new version from an ACA app-level secret. The new revision misbehaved and the pipeline rolled back to the old revision — but the old revision also read the new value of the app-level secret, so the outage continued. Approach: release images separately from configuration/secret changes; rotate secrets with a "two keys valid at once" window; record the configuration version in the release record as well. Limitation: a true "one-click rollback of everything" only works when configuration is versioned too (GitOps).
Case 3: the ECS circuit breaker did not fire
Problem: the new version's /healthz was fine but business endpoints returned 500; the ALB health check and the circuit breaker both considered the deployment successful, and the rolling update replaced every task within 4 minutes. Approach: configure alarm rollback on HTTPCode_Target_5XX_Count for the service; switch to native blue/green with a bake time so the old tasks stay online during the observation period for rollback in seconds. Limitation: an alarm threshold that is too sensitive causes false rollbacks, one that is too sluggish lets problems through; tune it to your traffic.
Common errors and fixes
ERROR: The revision weights must add up to 100 / Revision 'myapp--…' not found
Cause: the weights do not sum to 100; or old is empty (the app was previously in single mode, so no "active revision with weight" was found).
az containerapp revision list -g $RG -n $APP --query "[].{n:name,a:properties.active,w:properties.trafficWeight}" -o table
Fix: after the first switch to multiple, pin the traffic once with traffic set --revision-weight latest=100; check in the script that old is not empty.
curl: (6) Could not resolve host: myapp---canary.… (label URL)
Cause: the label has not taken effect yet, or the hostname is assembled differently from the real one.
az containerapp revision label list -g $RG -n $APP -o table 2>/dev/null; az containerapp ingress traffic show -g $RG -n $APP -o json
Fix: trust the FQDN in the command output; give DNS a few seconds to propagate and use --retry.
InvalidParameterException: … alarms … / alarm rollback did not fire
Cause: the alarm name does not exist or is in another region; the alarm dimension points to a different target group; the alarm was already in ALARM state before the deployment started; treat-missing-data keeps it OK when there is no data.
aws cloudwatch describe-alarms --alarm-names myapp-5xx --query 'MetricAlarms[0].[StateValue,Dimensions]'
Fix: check the dimensions (ARN suffixes), region and state; run a bad-version drill once to confirm the rollback path really works.
(service myapp) deployment … has been rolled back … circuit breaker (but the new version is actually fine)
Cause: the health check grace period is too short (slow application cold start), new tasks fail to pull the image (digest cleaned up, no cross-region replication), or the task role is missing permissions.
aws ecs describe-services --cluster $CLUSTER --services $SVC --query 'services[0].events[:5].message' aws ecs describe-tasks --cluster $CLUSTER --tasks $(aws ecs list-tasks --cluster $CLUSTER --desired-status STOPPED --query 'taskArns[0]' --output text) --query 'tasks[0].stoppedReason'
Fix: act on the stop reason (the troubleshooting flow from hour 4 Module 6); adjust healthCheckGracePeriodSeconds.
1. Immediately switch all Container Apps traffic back to revision myapp--g2a1b3c and show the result.
az containerapp ingress traffic set -g $RG -n $APP --revision-weight myapp--g2a1b3c=100 -o none az containerapp ingress traffic show -g $RG -n $APP -o table
2. List the status and start time of the ECS service's last 5 deployments.
aws ecs list-service-deployments --cluster $CLUSTER --service $SVC --max-results 5 \ --query 'serviceDeployments[].[createdAt,status,targetServiceRevisionArn]' --output table
The same myapp runs on both ACA (Canadian users) and ECS (US users). How would you orchestrate a release so that risk is controlled on both sides?
① Deploy the same signed digest on both sides (Modules 3, 4, 6); ② first complete 0% → 10% → 100% on the side with less traffic (for example ACA) and observe a full cycle; ③ then trigger the ECS deployment (native blue/green + alarm rollback + bake time); ④ write both sides into the same release record (digest, ACA revision, ECS task definition revision, time); ⑤ if either side rolls back, pause further releases on the other side and assess whether it should roll back too; ⑥ release configuration and secret changes separately. This splits the risk of "failing everywhere at once" into two steps that can each be rolled back independently.
Verified teaching videos
Official docs and further courses
- ACA: Traffic splitting · Blue-green deployment in ACA · Revisions
- ECS blue/green deployments · How CloudWatch alarms detect deployment failures · Deployment circuit breaker
- Signals and alerting: Prometheus & Grafana hour 3 (Azure) (Chinese) · Hour 4 (AWS) (Chinese)
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for a video tool.
Visual: on the left, the pipeline's "hand" moves the Container Apps traffic bar notch by notch: 0, 10, 100; on the right, a gear built into the service advances the ECS traffic bar automatically.
Narration: the difference between the two clouds is who controls traffic: ACA leaves it to the pipeline, ECS writes it into the service configuration.
Visual: red 500s appear in the 10% slice, the monitoring curve crosses the threshold, the traffic bar snaps back to the old version, and the pipeline turns red and sends a notification.
Narration: when signals go bad, roll back automatically; the blast radius is the canary ratio times the observation time.
Visual: the image has rolled back, but the key labeled "secret v2" next to it did not go back, and the error keeps flashing.
Narration: configuration, secrets and database migrations do not roll back with the image; release them separately and record them separately.
Module 8 · Five-Hour Recap, Self-Test and Cleanup
- Tie Hours 1–5 together on one knowledge map: fundamentals → production readiness → Azure → AWS → image CI and release, and name each hour's key mechanisms and artifacts.
- Recognize the ten most common mistakes from the first five hours, and use the interactive troubleshooting tree to locate build / login / push-and-tag / scan / signing / release problems.
- Clean up every cloud resource and GitHub setting created in Hours 3, 4 and 5 in the order "consumers → artifacts → identities → containers", and double-check that costs drop to zero.
What: a knowledge map of the five hours
| Hour | Topic | Core mechanisms | What you built |
|---|---|---|---|
| Hour 1 | Core basics | CLI → dockerd → containerd → runc; namespaces / cgroups / union filesystem; image layers; BuildKit; networking, volumes, Compose; Registry and ACR | The first image of myapp (Flask, :5000) |
| Hour 2 | From "it runs" to "production-ready" | PID 1 and signals, multi-stage builds, resource limits and health checks, advanced Compose, tagging strategy and intro to Bake, security hardening | Production-grade Dockerfile, review script |
| Hour 3 | Going to the cloud (Azure) | ACR (cloud builds, purge, locking), Container Apps (revisions, traffic, managed identity, Key Vault references), troubleshooting in the cloud | rg-docker-hour3: ACR, cae-docker-lab, myapp |
| Hour 4 | Going to the cloud (AWS) | ECR (immutability, scanning, lifecycle), ECS on Fargate + ALB, Secrets Manager, rolling / circuit breaker / native blue/green | ca-central-1: ECR myapp, ecs-docker-lab, ALB |
| Hour 5 | Image CI, supply chain and release | BuildKit cache backends and Bake, platform-agnostic CI + OIDC, digest promotion, SBOM / provenance / scan gates, cosign / Notation, ACA canary vs ECS blue/green with automatic rollback | docker-hour5-myapp repository: Bake + Makefile + workflows; the same digest in both registries |
Why: why recap and clean up in Hour 5
The first five hours form a complete loop: "one containerized service, from your laptop to production in two clouds". Hour 6 moves into application architecture (three-tier web, gateway, async jobs, migrations, object storage) and hour 7 into deep troubleshooting and optimization; they use a new sample project, orders, and do not depend on this hour's cloud resources. Before moving on, connect the knowledge and remove resources that keep billing (ACA, ECS tasks, ALB, registry storage).
How: the ten most common mistakes from the first five hours
| # | Mistake | Appears in | What to remember |
|---|---|---|---|
| 1 | Running as root; a shell-form ENTRYPOINT swallows SIGTERM | Hours 1, 2 | exec form + non-root + HEALTHCHECK |
| 2 | Oversized build context, cache always invalidated | Hours 1, 2, 5 | .dockerignore, instruction order, ARG late, export the cache |
| 3 | Deploying by a mutable tag | Hours 3, 4, 5 | Deploy by digest only; release tags are immutable |
| 4 | arm64 / amd64 mismatch (exec format error) | Hours 4, 5 | Be explicit with --platform for multi-platform; reference the index digest |
| 5 | Long-lived keys stored in CI | Hours 3, 4, 5 | OIDC + least privilege + PRs cannot get a token |
| 6 | Actions / scanners pinned to latest or a mutable tag | Hours 2, 5 | Pin by SHA / digest, let a bot upgrade |
| 7 | Scan gate so strict it gets bypassed, or exceptions that never expire | Hour 5 | Block only on severe + fixable; exceptions carry an expiry date; VEX |
| 8 | Signing, then verifying by tag / losing signatures when copying | Hour 5 | Verify the digest; oras cp -r or re-sign |
| 9 | Assuming rolling back the image also rolls back config and secrets | Hours 3, 4, 5 | Release and record configuration separately |
| 10 | Forgetting to clean up (ALB, ACA min replicas, registry storage, Key Vault soft delete) | Hours 3, 4, 5 | Clean up by resource group / tag, then double-check |
When: when and in what order to clean up
If you continue straight to hour 6, keep your local lab machine (Hours 6 and 7 run orders locally with Compose; some extension exercises use ACA, which you can recreate following hour 3). Clean up the cloud resources now. Order: delete consumers first (ACA app, ECS service, ALB), then artifacts (images, cache repositories, alarms, signing configuration), then identities (federated credentials, IAM roles, OIDC provider), and finally the containers (resource groups), then double-check.
az keyvault purge (if purge protection is enabled, you can only wait). ② "The IAM OIDC provider belongs to this hour only" - roles for other repositories in the same account may use it too; confirm before deleting. ③ "An ECS service with desired=0 costs nothing" - the ALB bills by the hour and ECR bills for storage; they still need to be deleted. ④ "It doesn't matter whether the GitHub repository is deleted" - the identifiers stored in repository variables are not passwords, but once the federated credential and IAM trust policy are gone they should be cleaned up as well to avoid confusion.Knowledge map: from one docker run to a dual-cloud release pipeline
Cleanup map: which resources keep billing
Interactive knowledge map: flashcards for the five hours
Click an hour to draw a random "how does it work" question. Answer it in your head first, then click "Show answer". The matching verification command appears below.
Cleanup commands at a glance
| Command | Purpose | Notes |
|---|---|---|
az resource list -g rg-docker-hour3 -o table | Confirm before deleting | Delete only the lab resource group |
az group delete -n rg-docker-hour3 --yes --no-wait | Deletes ACR, ACA, the environment, managed identities (including federated credentials) and Key Vault | Runs in the background; verify afterwards |
az keyvault purge -n $KV | Permanently removes a soft-deleted Key Vault | Not available when purge protection is enabled |
bash ~/cleanup-hour4-aws.sh | Hour 4's complete AWS cleanup script | Service → task definitions → cluster → ALB → cache → ECR → secrets → logs |
aws ecr delete-repository --repository-name myapp-cache --force | Deletes this hour's cache repository | --force deletes the images too |
aws iam delete-role --role-name docker-hour5-gha | Deletes the CI role | Delete inline policies first |
aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=docker-hour4,docker-hour5 | Find leftovers by tag | The result should be empty |
gh repo delete $GH_REPO --yes | Deletes the lab repository | Needs the delete_repo scope; or archive it instead |
cleanup-hour5.sh (resources added in Hour 5; dry-run first)
#!/usr/bin/env bash
# Usage: DRY_RUN=1 ./cleanup-hour5.sh to see what would be deleted; once confirmed, DRY_RUN=0 ./cleanup-hour5.sh
set -uo pipefail
source ~/hour5.env
run() { if [[ ${DRY_RUN:-1} == 1 ]]; then echo "DRY: $*"; else echo "+ $*"; "$@"; fi; }
# --- AWS (added in hour 5) ---
if [[ -n ${ACCOUNT_ID:-} ]]; then
run aws cloudwatch delete-alarms --alarm-names myapp-5xx
run aws ecr delete-signing-configuration
run aws signer cancel-signing-profile --profile-name myappSigning
run aws ecr delete-repository --repository-name myapp-cache --force
run aws iam delete-role-policy --role-name "$AWS_CI_ROLE" --policy-name ecr-push
run aws iam delete-role --role-name "$AWS_CI_ROLE"
others=$(aws iam list-roles --query "Roles[?contains(to_string(AssumeRolePolicyDocument), 'token.actions.githubusercontent.com')].RoleName" --output text)
[[ -z $others ]] && run aws iam delete-open-id-connect-provider \
--open-id-connect-provider-arn "arn:aws:iam::${ACCOUNT_ID}:oidc-provider/token.actions.githubusercontent.com" \
|| echo "keep OIDC provider, still used by: $others"
fi
# --- Azure (added in hour 5; also removed when the resource group is deleted) ---
if [[ -n ${RG:-} ]]; then
run az identity delete -g "$RG" -n "$ID_CI"
fi
# --- GitHub and local ---
for v in ACR ECR AZURE_CLIENT_ID AZURE_TENANT_ID AZURE_SUBSCRIPTION_ID AWS_ROLE_ARN; do
run gh variable delete "$v" --repo "$GH_REPO"; done
run docker buildx rm ci
run docker volume rm trivy-cache
run rm -f ~/cosign-lab.key ~/cosign-lab.pub
Why it's written this way: dry-run by default; the OIDC provider is deleted only if no other role trusts it; resources from Hours 3 and 4 use those hours' own cleanup steps (resource group deletion / cleanup-hour4-aws.sh). Common mistake: deleting the IAM role before the ECS service causes permission errors in the service events, but doesn't block deletion; "consumers first" is still the recommended order.
Lab 8: Clean up all cloud resources from Hours 3–5 and verify (about 8 minutes, plus waiting time)
az account show and aws sts get-caller-identity point to your lab subscription / account.~/releases.jsonl and deploy/*.env as review material.
cp ~/releases.jsonl ~/myapp/deploy/ 2>/dev/null; (cd ~/myapp && git add deploy && git commit -qm "archive release records" && git push) || true
chmod +x cleanup-hour5.sh DRY_RUN=1 ./cleanup-hour5.sh DRY_RUN=0 ./cleanup-hour5.sh
DRY: aws cloudwatch delete-alarms --alarm-names myapp-5xx DRY: aws ecr delete-signing-configuration … + aws iam delete-role --role-name docker-hour5-gha keep OIDC provider, still used by: github-deploy-other-repo
cleanup-hour4-aws.sh from hour 4 Module 8 (ECS service → task definitions → cluster → ALB and target group → ElastiCache → ECR → secrets → log groups → security groups → IAM roles).
bash ~/cleanup-hour4-aws.sh aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=docker-hour4,docker-hour5 \ --query 'ResourceTagMappingList[].ResourceARN' --output text
The resource tagging API lags by a few minutes, so just-deleted resources may still show up briefly; confirm the ECR repositories and ALB once more with describe-*.
source ~/hour5.env az resource list -g $RG -o table az group delete -n $RG --yes --no-wait az group wait -n $RG --deleted --timeout 1800 && echo "rg deleted" az keyvault purge -n $KV 2>/dev/null || echo "purge skipped (purge protection or already purged)" az group exists -n $RG
rg deleted false
gh repo archive "$GH_REPO" --yes # or gh repo delete "$GH_REPO" --yes docker image prune -af --filter "label=org.opencontainers.image.source=https://github.com/$GH_REPO" docker buildx prune -af
We recommend keeping the local ~/myapp repository (Makefile, Bake, workflows, scripts) as a template. Hour 6 uses a new sample project, orders.
Case 1: Turning five hours of output into a team template
Problem: every new service rewrote its own Dockerfile, CI, scanning, signing and deployment scripts, with uneven quality. Approach: the platform team turned this hour's docker-bake.hcl, Makefile, ci/*.sh and workflows into a template repository (GitHub template / GitLab CI component / Azure Pipelines template); services fill in only the image name and registry, and a single signing identity means the deploy side maintains just one verification policy. Limitation: templates need versions and an upgrade path, or they fork.
Case 2: The weekend bill
Problem: after a training, participants left the ALB, ECS tasks and two registries running, which cost over a hundred dollars in a month. Approach: tag all lab resources with course=… and add an expires tag to Azure resource groups; a scheduled job lists expired resources; budget alerts are set on the subscription / account. Limitation: the tagging policy must be enforced at creation time (Azure Policy / AWS tag policies); adding tags afterwards is rarely complete.
Case 3: Deleting the OIDC provider broke other teams' deployments
Problem: while cleaning up "their own" lab, someone deleted the account-level GitHub OIDC provider, and deployments of three other teams all failed with No OpenIDConnect provider found. Approach: the OIDC provider is an account-level shared resource managed by the platform team (IaC); individuals only create roles; cleanup scripts first check whether it's still referenced (this hour's script already does). Limitation: shared resources need a clear owner and change process.
Interactive troubleshooting tree: build / login / push and tags / scan / signing / release
Common errors during cleanup
DeleteConflict: Cannot delete entity, must delete policies first.
Cause: the IAM role still has inline policies or attached managed policies.
aws iam list-role-policies --role-name docker-hour5-gha; aws iam list-attached-role-policies --role-name docker-hour5-gha
Fix: run delete-role-policy / detach-role-policy first, then delete the role.
RepositoryNotEmptyException: The repository with name 'myapp-cache' … cannot be deleted because it still contains images
Cause: --force was not added.
Fix: aws ecr delete-repository --repository-name myapp-cache --force.
az keyvault create … VaultAlreadyExists / name still taken
Cause: the Key Vault is in the soft-deleted state.
az keyvault list-deleted -o table
Fix: az keyvault purge -n NAME (with purge protection enabled you can only wait for the retention period to end, or use a different name).
ResourceInUse: Target group … is currently in use by a listener or a rule
Cause: wrong deletion order: the ALB or a listener rule still exists.
Fix: delete the load balancer first and wait for load-balancers-deleted, then delete the target group (the order used by the hour 4 script).
1. List all resource groups in the subscription that have a course tag, along with the tag value.
az group list --query "[?tags.course].{name:name, course:tags.course, loc:location}" -o table2. Find the digests of images in the ECR myapp repository that have no tags and were pushed more than 7 days ago (a pre-cleanup check).
aws ecr describe-images --repository-name myapp --filter tagStatus=UNTAGGED \ --query "imageDetails[?imagePushedAt<'$(date -u -d '-7 days' +%FT%TZ)'].imageDigest" --output text
Using what you learned in the first five hours, describe every key step a production release of myapp goes through, from commit to stable operation.
① Image: the multi-stage, non-root Dockerfile with HEALTHCHECK from hour 2; ② CI: triggered by a merge to main, make test (single-platform bake + smoke test), make release (multi-platform + SBOM + provenance, registry cache), passwordless OIDC login to ACR / ECR, the same digest pushed to both; ③ Gate: make scan (pinned Trivy, blocks only on severe and fixable, VEX and expiring exceptions), then keyless signing once it passes; ④ Promotion: the staging environment manifest records the digest; after acceptance, pushing the v1.5.0 tag makes the promotion job verify the signature, add an immutable tag and write the prod manifest; ⑤ Release: ACA multiple revisions 0% → smoke test → 10% → metrics check → 100%, ECS native blue/green + alarm-based rollback; ⑥ Runtime: managed identity / task role reads secrets (Hours 3, 4), continuous registry scanning, weekly rebuilds; ⑦ Rollback: the previous digest from the release record, one command.
Verified teaching videos
Official documentation
- az group delete · Key Vault soft delete · Azure budgets
- ECS: deleting a service · IAM OIDC identity providers · AWS Budgets
- Next hour: Hour 6: Production Applications and Architecture Design
Video storyboard (about 70 seconds)
This courseware cannot generate video/MP3 directly; a storyboard and narration script are provided for use with a video tool.
Visual: five puzzle pieces drop in one by one: Core basics, Production readiness, Azure, AWS, Image CI and release, forming a conveyor belt that runs from a laptop to two clouds.
Narration: In five hours, myapp went from a single docker run to an auditable dual-cloud release pipeline that can roll back.
Visual: line items on a bill turn gray one by one as the cleanup script runs: Container Apps, ALB, ECS tasks, registries, identities.
Narration: The last step is cleanup: delete consumers first, then artifacts and identities, then the resource groups, and double-check.
Visual: a three-tier architecture diagram unfolds under the title "hour 6".
Narration: Next hour, we use the orders project to dive into production application architecture.
Command Cheat Sheet
BuildKit / Bake
docker buildx create --name ci --driver docker-container --use --bootstrap docker buildx bake --print release | jq '.target.release' docker buildx bake test # single platform + --load docker buildx bake release --metadata-file build-meta.json jq -r '.release."containerimage.digest"' build-meta.json # registry cache (ECR requires the last two options) --cache-to type=registry,ref=REG/myapp-cache:main,mode=max,image-manifest=true,oci-mediatypes=true --cache-from type=registry,ref=REG/myapp-cache:main docker buildx du --verbose; docker buildx prune --keep-storage 20GB
Passwordless CI login (OIDC)
permissions: { contents: read, id-token: write } # release job only
# Azure
az identity federated-credential create -g $RG --identity-name id-github-ci --name gh-main \
--issuer https://token.actions.githubusercontent.com \
--subject "repo:ORG/REPO:ref:refs/heads/main" --audiences api://AzureADTokenExchange
az acr login -n $ACR
# AWS (trust policy: aud=sts.amazonaws.com, sub StringLike repo:ORG/REPO:ref:refs/heads/main)
aws ecr get-login-password | docker login -u AWS --password-stdin $ECRTags, promotion, copying
docker buildx imagetools inspect REG/myapp:sha-3f9a2c1 --format '{{json .Manifest.Digest}}'
docker buildx imagetools create -t REG/myapp:v1.5.0 REG/myapp@sha256:… # no rebuild
docker buildx imagetools create -t $ECR/myapp:sha-3f9a2c1 $ACR_LOGIN/myapp@sha256:…
oras cp -r $ACR_LOGIN/myapp@sha256:… $ECR/myapp:v1.5.0 # including signature/SBOM referrers
az acr repository update -n $ACR --image myapp:v1.5.0 --write-enabled false --delete-enabled false
aws ecr put-image-tag-mutability --repository-name myapp --image-tag-mutability IMMUTABLE_WITH_EXCLUSION \
--image-tag-mutability-exclusion-filters filterType=WILDCARD,filter=latestSBOM, provenance, scanning
docker buildx imagetools inspect REF --format '{{ json (index .SBOM "linux/amd64").SPDX }}' > sbom.spdx.json
docker buildx imagetools inspect REF --format '{{ json (index .Provenance "linux/amd64").SLSA }}'
docker run --rm -e DOCKER_CONFIG=/cfg -v ~/.docker/config.json:/cfg/config.json:ro \
-v trivy-cache:/root/.cache/ aquasec/trivy:0.76.2 image \
--severity HIGH,CRITICAL --ignore-unfixed --exit-code 1 REF@sha256:…
docker run --rm -v "$PWD:/src:ro" anchore/grype:v0.122.0 sbom:/src/sbom.spdx.json --only-fixed
# Do not use: trivy v0.69.4, images 0.69.5/0.69.6, anything latest; do not mount docker.sockSigning and verification
cosign sign --yes REF@sha256:… # CI keyless cosign verify REF@sha256:… \ --certificate-identity https://github.com/ORG/REPO/.github/workflows/image-ci.yml@refs/heads/main \ --certificate-oidc-issuer https://token.actions.githubusercontent.com cosign attest --yes --type spdxjson --predicate sbom.spdx.json REF@sha256:… cosign tree REF@sha256:…; oras discover REF@sha256:… --format tree aws ecr put-signing-configuration --signing-configuration file://signing-config.json notation verify REF@sha256:…
Release and rollback
# ACA
az containerapp update -g $RG -n $APP --image REG/myapp@sha256:… --revision-suffix g3f9a2c1
az containerapp ingress traffic set -g $RG -n $APP --revision-weight OLD=90 NEW=10
az containerapp ingress traffic set -g $RG -n $APP --revision-weight OLD=100 NEW=0 # rollback
# ECS
aws ecs update-service --cluster $CLUSTER --service $SVC --task-definition myapp:15 \
--deployment-configuration "deploymentCircuitBreaker={enable=true,rollback=true},alarms={alarmNames=[myapp-5xx],enable=true,rollback=true}"
aws ecs list-service-deployments --cluster $CLUSTER --service $SVC --max-results 5
aws ecs stop-service-deployment --service-deployment-arn ARN --stop-type ROLLBACKMakefile target contract
make test # bake test + ci/smoke.sh (safe for PRs) make release REGISTRY=… # multi-platform + attestations → .digest make copy REGISTRY=… MIRROR=… # copy the same digest to the second registry make scan / make sbom # gate / SBOM cross-scan make sign / make verify # keyless sign / verify (resolves the sha- candidate) make promote ENV=prod TAG=v1.5.0 # write environment manifest + version tag ci/deploy-aca.sh IMG@DIGEST SUFFIX; ci/deploy-ecs.sh IMG@DIGEST
Cleanup
DRY_RUN=1 ./cleanup-hour5.sh && DRY_RUN=0 ./cleanup-hour5.sh bash ~/cleanup-hour4-aws.sh az group delete -n rg-docker-hour3 --yes --no-wait; az keyvault purge -n $KV aws resourcegroupstaggingapi get-resources --tag-filters Key=course,Values=docker-hour4,docker-hour5 gh repo archive "$GH_REPO" --yes
Quick troubleshooting table
| Symptom / error | Most likely cause | First command |
|---|---|---|
Cache export is not supported for the docker driver | Default driver + classic image store | docker buildx ls |
| Exporting cache to ECR returns 400 | Missing image-manifest=true,oci-mediatypes=true | docker buildx bake --print release |
Unable to get ACTIONS_ID_TOKEN_REQUEST_URL | The job lacks id-token: write | Check the job-level permissions |
AADSTS700213 / Not authorized to perform sts:AssumeRoleWithWebIdentity | subject / audience mismatch | Fix the federated credential / trust policy using the subject shown in the error |
ImageTagAlreadyExistsException | ECR immutability (usually expected) | aws ecr describe-images --image-ids imageTag=… |
Scanner UNAUTHORIZED | Credential helper / expired token | jq .credsStore ~/.docker/config.json |
no matching signatures | Wrong identity / wrong digest / signature not copied | cosign tree REF@DIGEST |
| Users still see errors after the canary; rollback has no effect | App-level config / secrets are not rolled back with the revision | az containerapp show … --query properties.configuration |
| ECS circuit breaker doesn't trigger but the app returns 500 | Health checks pass; no alarm-based rollback | aws cloudwatch describe-alarms --alarm-names myapp-5xx |
Recommended configuration snippets
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule: { interval: weekly }
- package-ecosystem: docker
directory: /
schedule: { interval: weekly }
- package-ecosystem: pip
directory: /
schedule: { interval: weekly }name: weekly-rebuild
on:
schedule: [{ cron: "17 3 * * 1" }]
workflow_dispatch:
jobs:
rebuild:
uses: ./.github/workflows/image-ci.yml # or copy the release job
secrets: inherit
# image-ci.yml needs on.workflow_call; in Bake, add --pull and let an input control no-cacheCapstone Lab + Final Quiz
sha- candidate has the same digest in ACR and ECR, with an SBOM and mode=max provenance; ③ a scan gate (pinned version, no docker.sock), with at least one exception that has an expiry date or a VEX statement; ④ keyless signing, verified before deployment, deploy by digest only; ⑤ v1.5.0 cannot be overwritten on either side, and environment manifests record the promotion; ⑥ a prod canary and one automatic rollback drill; ⑦ clean up all cloud resources. Doing only Azure or only AWS is fine (skip the other cloud's steps).source ~/hour5.env; cd ~/myapp for c in docker cosign oras jq gh make; do command -v "$c" >/dev/null || echo "missing $c"; done docker buildx bake -f docker-bake.hcl --print release | jq -e '.target.release.attest | length == 2' >/dev/null && echo "bake ok" git grep -nE 'clientSecret|aws_secret_access_key|password *=' -- . ':!*.md' || echo "no long-lived secrets"
sed -i 's/^\(APP_VERSION_DEFAULT *= *\).*/\1"1.5.0"/' app.py 2>/dev/null || true git commit -qam "feat: myapp 1.5.0" --allow-empty && git push && gh run watch --exit-status
export GIT_SHA=$(git rev-parse --short=7 HEAD)
for r in "$ACR_LOGIN" "$ECR"; do docker buildx imagetools inspect "$r/myapp:sha-$GIT_SHA" --format '{{json .Manifest.Digest}}'; done
docker buildx imagetools inspect "$ACR_LOGIN/myapp:sha-$GIT_SHA" --format '{{ json (index .Provenance "linux/amd64").SLSA }}' | jq -r '.. | .uri? // empty' | head -3
gh run view --log --job release | grep -E 'Total: .* CRITICAL' | head -2make verify REGISTRY=$ACR_LOGIN GH_REPO=$GH_REPO make promote REGISTRY=$ACR_LOGIN ENV=staging RG=$RG APP=$APP WINDOW=30 ci/deploy-aca.sh "$ACR_LOGIN/myapp@$(cat .digest)" "g$GIT_SHA"
git tag v1.5.0 && git push origin v1.5.0 # triggers promote.yml (requires production environment approval)
gh run watch --exit-status
for r in "$ACR_LOGIN" "$ECR"; do docker buildx imagetools inspect "$r/myapp:v1.5.0" --format '{{json .Manifest.Digest}}'; done
git pull -q && diff <(grep -o 'sha256:[0-9a-f]*' deploy/staging.env) <(grep -o 'sha256:[0-9a-f]*' deploy/prod.env) && echo "same digest"ci/deploy-ecs.sh "$ECR/myapp@$(cat .digest)" (the service already has alarm-based rollback configured); then, following Module 7 Lab 2, release a version where / returns 500, and confirm that ACA rolls back automatically and the ECS deployment status is ROLLBACK_SUCCESSFUL. Write both results to ~/releases.jsonl.DRY_RUN=0 ./cleanup-hour5.sh → cleanup-hour4-aws.sh → delete rg-docker-hour3 → double-check.Acceptance checklist
Open-ended self-test (answer first, then expand the reference answer)
1. Why does this hour place scanning "after pushing the candidate, before signing" rather than right after the local build?
Scanning by digest after the push examines the exact bytes that will be deployed from the registry (all platforms), without depending on local Docker. Signing after the scan means "only digests that passed the gate get a signature", and since deployment accepts only signed digests, the gate naturally extends to deployment. A local scan examines the single-platform --load result, which is not the same object as the pushed multi-platform index.
2. After copying the same digest to ECR, the ECS verification step reports no signatures found. Why? What are the trade-offs of the two fixes?
A signature is a referrer attached to the digest; imagetools create copies only the index and the manifests it references, not the referrers. Fixes: ① oras cp -r copies with the referrers - you sign only once, but both registries must support referrers; ② re-sign on the ECR side with the same CI identity - the verification policy stays the same, but there is an extra Rekor entry and the signing time differs.
3. Once the ECR repository is set to IMMUTABLE, how should the BuildKit registry cache and latest be handled?
Put the cache in a separate mutable repository, myapp-cache (or use IMMUTABLE_WITH_EXCLUSION to exempt cache-*); exempt latest with an exclusion filter, but never allow any deployment to reference it. Release and candidate tags stay immutable.
4. In keyless signature verification, what should --certificate-identity be? Why can't you use .*?
The full identity of the signing workflow, such as https://github.com/ORG/REPO/.github/workflows/image-ci.yml@refs/heads/main, together with --certificate-oidc-issuer https://token.actions.githubusercontent.com. Using .* means accepting a signature made by anyone on the public Sigstore - an attacker can produce a "valid" signature from their own GitHub repository.
5. What triggers automatic rollback in ACA and in ECS? For a bad version where "health checks pass but the business endpoint returns 500", what configuration does each need to roll back?
ACA: there is no built-in automatic rollback; the pipeline shifts the weight back to the old revision based on signals (per-revision 5xx metrics or sampling) - this requires observation and decision logic in the release script. ECS: driven by service configuration - the circuit breaker looks only at task startup and health checks and cannot catch this case, so you need a CloudWatch alarm (such as target group 5xx) with rollback=true in deploymentConfiguration.alarms, and for blue/green, a bake time that keeps the old tasks around.
6. You need to migrate this hour's pipeline to GitLab. What has to change, and what doesn't?
No change: docker-bake.hcl, Makefile, ci/*.sh, and the scan/sign/promotion logic. Changes: trigger rules (rules), OIDC (the audience of id_tokens; the issuer and subject in the Azure federated credential and AWS trust policy switch to GitLab's format), runners and the Docker-in-Docker service, the keyless signing identity (GitLab's signing identity and issuer differ, so verification parameters must change accordingly), and environment approvals (protected environments).
Final quiz (12 questions covering all modules)
Sources and Version Notes
| Topic | Verified finding | Source (accessed 2026-11-17) |
|---|---|---|
| Docker Engine / buildx / BuildKit | Engine v29.10.0 (2026-11-16); buildx v0.39.0 (2026-11-11); BuildKit v0.35.0 (2026-11-11) | moby/moby releases · docker/buildx · moby/buildkit (GitHub Releases API) |
| Cache backends | registry / gha / local / inline / s3 / azblob; mode=min|max; the default docker driver supports exports other than inline only with the containerd image store; ECR remote cache needs image-manifest=true,oci-mediatypes=true | Cache storage backends · AWS Containers Blog |
| GitHub Actions (pinned by SHA) | actions/checkout v7.0.1 = 3d3c42e5…; docker/setup-buildx-action v4.4.1 = f87e5991…; docker/setup-qemu-action v4.4.0 = 99012661…; docker/build-push-action v7.4.0 = c3c9e263…; docker/bake-action v7.5.0 = 59cb1203…; docker/login-action v4.8.0 = 8aa5831f…; docker/metadata-action v6.2.0; azure/login v3.1.0 = a641126d…; aws-actions/configure-aws-credentials v6.3.0 = e1253824…; aws-actions/amazon-ecr-login v2.1.7; sigstore/cosign-installer v4.1.3 = 756fe2d2… | Each repository's Releases and the commits/<tag> API |
| GitHub OIDC | issuer https://token.actions.githubusercontent.com; Azure audience api://AzureADTokenExchange; AWS audience sts.amazonaws.com; repositories created / renamed / transferred after 2026-07-15 use an immutable subject containing IDs by default | OIDC reference · GitHub Changelog 2026-04-23 |
| ACR locking and permissions | No repository-level immutability switch; lock per image/repository (writeEnabled / deleteEnabled); purge skips locked images by default; registries with ABAC repository permissions enabled use the Container Registry Repository family of roles | Lock an image · acr purge |
| ECR immutability and exceptions | IMMUTABLE_WITH_EXCLUSION / MUTABLE_WITH_EXCLUSION, --image-tag-mutability-exclusion-filters filterType=WILDCARD,filter=… (since 2025-07); lifecycle policies do not expire images still referenced by a manifest list | Image tag mutability · What's New 2025-07 · Lifecycle policies |
| ECR managed signing | Released 2025-11-21; put-signing-configuration / get-signing-configuration / describe-image-signing-status / delete-signing-configuration; at most 10 rules per registry; the signing profile must be in the same Region and can be cross-account; calls signer:SignPayload as the pusher's identity; manual verification still needs the Notation CLI | Managed signing · What's New 2025-11 |
| Scanner versions | Trivy v0.76.2 (2026-11-05); Grype v0.122.0 (2026-11-16); Syft v1.57.2 (2026-11-16); Docker Scout CLI v1.29.0 (2026-10-28) | GitHub Releases: trivy · grype · syft · scout-cli |
| Trivy supply chain incident (2026-03) | Affected: binary v0.69.4, Docker Hub images 0.69.5 / 0.69.6, most trivy-action tags, setup-trivy tags; safe versions recommended at the time: v0.69.2 / v0.69.3, trivy-action v0.35.0, setup-trivy v0.2.6 | Aqua official advisory |
| cosign / Notation / ORAS | cosign v3.1.4 (2026-10-20); v3 enables the new bundle format and signing config by default; Notation v1.3.2 (latest stable, 2025-04-27; v2.0.0 is still alpha); notation-azure-kv v1.2.1; ORAS v1.4.0 (2026-11-17) | cosign · Cosign 3.0 · notation · oras |
| ACA and ECS releases | ACA revisions, traffic weights, label URLs; ECS native blue/green (with lifecycle hooks and bake time), circuit breaker, CloudWatch alarm rollback, service deployment API | ACA traffic splitting · ECS blue/green · ECS alarms; Hours 3 and 4 of this course |
| Other | myapp conventions (Flask, port 5000, /healthz, APP_VERSION, non-root) and resource names (rg-docker-hour3, cae-docker-lab, ca-central-1, ecs-docker-lab, tags course=docker-hour4 / course=docker-hour5) are consistent with Hours 2–4 | Hours 2–4 of this course |
Notes on video verification
The titles and channels of the following videos were verified via the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json, 2026-11-17): Fireship "Docker in 100 Seconds" (Gjnup-PuquQ); TechWorld with Nana "GitHub Actions Tutorial - Basic Concepts and CI/CD Pipeline with Docker" (R8_veQiYBjI); Jon Gallant "Connect to Azure from a GitHub Action with OpenID Connect (OIDC)" (IKuw9T6vZYU); GitHub "Securely deploy to AWS with GitHub Actions and OIDC" (Io5UFJlEJKc); Mickey Gousset "GitHub Actions Policy Update: Blocking & SHA Pinning Explained!" (4dnniFk5i2Q); Black Hat "Uncovering and Responding to the tj-actions Supply Chain Breach" (-BCngzJC1Rc); CNCF Notary Project "What is Notation? | Container Image Signing" (ZMNUazoGwdk); Kamal Rathnayake "Azure Container Apps - Revisions Explained" (5vPM94kpIO4); AWS Events "Deep Dive: ECS Managed Instances & Blue/Green for Resilient Services (CNS416)" (88PFI55eKzs); Containers from the Couch "Circuit Breakers for Amazon ECS" (Y2Ez9M7A95Y). For Modules 2 and 4 no verifiable, current video was found, so only storyboard scripts are provided. Action versions and UIs in older recordings may be out of date; this hour and the official docs take precedence.
Notes on the audio explanations
The "Audio" tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the scripts aloud in real time; quality depends on the voices installed on your system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; if you need offline audio, feed the scripts to a TTS service such as Azure AI Speech.
Relationship to the old Hour 5
The in-depth GitHub Actions + OIDC material from the old "Production-Grade Container Operations in the Cloud (Azure)" has moved to GitHub hour 3 (Chinese) (this hour keeps only the minimal login); Bicep has moved to the IaC-related courses (GitHub hour 3, Module 6 (Chinese), Terraform in 8 Hours (Chinese)); KQL / Application Insights monitoring and alerting has moved to Prometheus & Grafana in 8 + 1 Hours (Chinese) and Module 6 of hour 3 of this course; the namespace / cgroups recap is in hour 1; supply chain (SBOM, Notation, deploying by digest) and Day-2 canary rollback are expanded into dual-cloud versions in Modules 5–7 of this hour; the incident response and blameless postmortem templates remain in Module 7's lab and production cases.
Known limitations
- The commands, workflows, Makefile and scripts in this hour were not run against real Azure / AWS / GitHub in the generation environment; the digests, IDs, ARNs, times, counts and tool log wording in "expected output" are example values.
- The user-defined functions and conditional expressions in
docker-bake.hcl, and the JSON shape ofattest/cache-toin the--printoutput, were written from the Bake documentation and not actually parsed with buildx 0.39. - cosign v3's referrer storage, the
-o jsonoutput fields (optional.Subject), and the behavior of--tlog-upload=false/--insecure-ignore-tlogand KMS URIs were written from the v2 / v3 documentation; the tree output oforas discoveris illustrative. - The exclusion filter field names returned by ECR
describe-repositories, the status enum and parameters oflist-service-deployments, and the parameters ofstop-service-deploymentfollow the AWS CLI reference; billing for ECR managed signing was not verified. - How the hostname of a Container Apps label URL is composed and the metric name for querying 5xx per revision should be confirmed from
azoutput and the portal; the statement that Container Apps and ECS do not verify signatures at pull time is based on the absence of such a feature in the official documentation. - Trivy's
--vexand YAML exception file fields (statement,expired_at), Grype--only-fixedwith SBOM input, and Docker Scout's--exit-codeparameter were written from their respective documentation and not actually run; vulnerability IDs are examples. - The GitLab, Azure Pipelines and Jenkins snippets show structure only; CI tool images, service connections and agent identities must be configured as described in the corresponding courses.
- Timings, steps and logs in the animations are illustrative, to explain the mechanisms; real output depends on the actual versions.