GitHub Hour 3: Moving to the Cloud (Azure)
- Choose a deployment target based on your team and application shape, from among Azure Container Apps / AKS / App Service / Functions , and explain the trade-off between push-based deployment (GitHub Actions calling cloud APIs directly) and GitOps pull-based deployment (an in-cluster agent pulling from Git).
- Master GitHub OIDC → Microsoft Entra ID workload identity federation: the issuer / audience / subject triple of federated credentials; the difference between branch, environment, PR and tag subjects; the immutable subject that is the default for repositories created, renamed or transferred from 2026-07-15 onward
repo:OWNER@OWNER_ID/REPO@REPO_ID:…; and why client secrets are no longer used. - Use environments to build release gates: required reviewers, preventing self-approval, wait timers, branch/tag restrictions, environment-level secrets and variables, custom deployment protection rules, and feature availability across plans and private repositories.
- Deploy myapp to Azure Container Apps: build and push to ACR, create a revision per commit, pre-release at 0% traffic in multiple-revision mode → smoke test → switch traffic; on failure,automatically roll back.
- Understand AKS (
azure/aks-set-context@v5,azure/k8s-deploy@v7, kubelogin) and how App Service is deployed (deployment slots and swap with preview), plus IaC pipelines where Bicep what-if / Terraform plan are posted as PR comments and the same plan is applied after approval. - Locate within 10 minutes AADSTS700213 / AADSTS7002138 / AADSTS70021,AuthorizationFailed, ACR pull 401 errors, stuck environment approvals, concurrent deployment conflicts and other cloud deployment faults, and complete cost control and thorough cleanup.
One-hour time allocation table
| # | Time | Module | Core content | Animations / interaction | Labs (myapp repo + rg-gh-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and Azure setup | Subscription and permission check, resource providers, environment variable file, ACR + Container Apps environment + two apps | Readiness self-assessment | Azure base resources ready |
| 1 | 00–05 | From CI to CD: choosing a deployment architecture | ACA / AKS / App Service / Functions comparison, push-based vs GitOps pull-based, build once and deploy many, layered identities | Deployment target selector | Draw the myapp deployment pipeline |
| 2 | 05–14 | OIDC federated identity | ID token claims, federated credentials, the four subject formats and the immutable format, user-assigned managed identity vs app registration azure/login@v3, flexible federated credentials (preview) | OIDC token exchange animation (switchable among 6 failure scenarios) | 3 identities + federated credentials + first OIDC sign-in |
| 3 | 14–21 | Environments and deployment protection rules | Required reviewers, self-approval prevention, wait timers, branch/tag policy, admin bypass, environment secrets/variables, custom rules (public preview), plan availability | Deployment gate simulator | Create dev / prod environments and configure approvals |
| 4 | 21–30 | Deploying to Azure Container Apps | Build on the runner and push to ACR,az containerapp update vs the official action, revision modes, traffic splitting, smoke tests and automatic rollback | Revision and traffic switch animation | dev deploys automatically, prod 0% canary + traffic switch |
| 5 | 30–38 | Deploying to AKS and App Service | aks-set-context@v5 + use-kubelogin@v1 + k8s-deploy@v7, local account disabling and Azure RBAC, deployment slots and swap with preview | Deployment slot swap steps animation | (Optional) AKS / App Service workflow snippets |
| 6 | 38–45 | IaC pipeline | Bicep what-if / Terraform plan comments on PRs (read-only identity), apply the same plan after approval, deployment stacks | PR → plan → approval → apply sequence | Add a what-if PR comment for the myapp infrastructure |
| 7 | 45–54 | Troubleshooting cloud deployments | AADSTS error families, AuthorizationFailed, ACR 401, stuck approvals, concurrency conflicts, token expiry | Interactive troubleshooting tree + error decoder | Deliberately trigger 3 faults and fix them |
| 8 | 54–60 | Cost, cleanup and self-test | Cost breakdown and estimates, idle costs, cleanup order (cloud resources → federated credentials → roles → GitHub environments/secrets) | Monthly cost estimator | One-click cleanup script + verification |
| — | After class | Cheat sheet · Capstone lab | myapp: PR CI → merge → OIDC → push to ACR → dev auto → prod approval → smoke → rollback → cleanup | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / configuration | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Deployment target selection and pipeline layering | ✓ | · | · | ✓ | ✓ | · | · | ✓ | Selection table | M1 architecture diagram |
| OIDC federated credentials and subject design | · | ✓ | ✓ | · | · | ✓ | ✓ | ✓ | az identity federated-credential create,gh api …/oidc/customization/sub | M2 lab |
| Immutable subject and migration | · | ✓ | · | · | · | · | ✓ | · | use_immutable_subject,sub_claim_prefix | M2 step 3 |
| Least-privilege RBAC (pipeline identity vs runtime identity) | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | · | az role assignment create --scope | AcrPush / AcrPull separation |
| Environment approvals and deployment protection rules | · | · | ✓ | ✓ | · | ✓ | ✓ | · | environment:,gh api …/environments | dev / prod environments |
| Container Apps revisions, traffic, rollback | · | · | · | ✓ | · | · | ✓ | · | az containerapp revision,ingress traffic set | prod canary |
| AKS / App Service deployment | ✓ | · | · | · | ✓ | · | ✓ | · | k8s-deploy@v7,webapp deployment slot swap | M5 snippet |
| IaC plan comments and apply after approval | · | ✓ | ✓ | · | · | ✓ | · | · | az deployment group what-if,terraform plan -out | M6 lab |
| Cloud deployment fault diagnosis | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | Runtime logs Federated token details,az role assignment list | M7 fault injection |
| Cost control and cleanup | · | · | · | · | · | · | · | ✓ | az group delete,gh api -X DELETE | Cleanup script |
Topics excluded from this lesson (and where to learn them)
| Topic | Why it is not in this lesson | Where to learn it |
|---|---|---|
workflow syntax, triggers, matrix, caching, artifacts,GITHUB_TOKEN permissions | Already covered in the previous lesson; used directly in this lesson | Hour 2: GitHub Actions core |
| Git branching strategy, Azure Repos vs GitHub comparison, using Git in CI/CD | Belongs to the Git course | Git 8-hour course(lessons 3 and 5) |
| Writing Dockerfiles, slimming images, detailed Bicep templates for Container Apps, Redis and Key Vault | Belongs to the Docker course; this lesson only covers how the pipeline gets images to the cloud | Docker lesson 3 · Docker lesson 5 (GitHub Actions + OIDC → ACA) |
| Terraform remote state, HCP Terraform, policy as code, drift detection | Belongs to the Terraform course; module 6 of this lesson covers only the GitHub-side pipeline shape | Terraform lesson 5 |
AWS (IAM OIDC identity provider,configure-aws-credentials, ECS/EKS) | Next lesson | Hour 4 |
| Reusable workflows, pinning actions by SHA and supply-chain attestation, self-hosted runner hardening | Belongs to “production-grade Actions” | Hour 5 |
| Installing and operating Argo CD / Flux | Belongs to the Kubernetes course; this lesson only compares push vs pull | Kubernetes 8 + 1 hour course |
How to use this courseware
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quiz · voice · video. Recommended: read “Theory” and “Animation” first, then do the “Lab”. All labs build up incrementally in the same
myapp repository and resource group rg-gh-lab , building up step by step.Counts toward progress when your quiz score is 70% or higher, or when you click “Mark this module complete”; saved in this browser (cleared on refresh if browser local storage is disabled).
The “voice” pages read the lecture script aloud with the built-in browser Web Speech API (en-US), and English terms are pronounced with en-US; the script stays readable if no Chinese voice pack is installed.
azure/login v3.1.0 (2026-09-10, supported major version v3; v2 is in maintenance mode); actions/checkout v7.0.1; docker/build-push-action v7.4.0,docker/setup-buildx-action v4.4.1; azure/aks-set-context v5.0.1,azure/k8s-deploy v7.0.1,azure/setup-kubectl v5.2.0,azure/use-kubelogin v1.3; azure/webapps-deploy v3.0.8; azure/bicep-deploy v2.5.0; azure/container-apps-deploy-action the latest is still v2 (2023-10,action.yml declares a node16 runtime); Azure CLI 2.93.0. Examples use @vN for readability; in production pin to a full commit SHA (covered in lesson 5).Module 0 · Warm-up and Azure setup (complete before class)
- CompletedHour 2: the
myapprepository under a personal account (Python Flask + gunicorn, with a Dockerfile,/healthzand pytest tests.github/workflows/ci.yml), which runs and passes on PR and push. - Installed on your machine or in Codespaces:
ghCLI (alreadygh auth login), Git 2.56, Docker Engine 29 (for local image verification only, optional), Azure CLI 2.9x (az version). - An Azure subscription where you can create resources and role assignments. A personal trial subscription is fine. For an enterprise subscription, first confirm that you can create role assignments in
rg-gh-labthe target scope. - myapp container port: keep the port from the Container Apps template in the Docker lesson, 5000 and health-check path
/healthz. If your Dockerfile differs, useEXPOSEas the source of truth and updatePORTbelow.
Connection to the previous lesson
| Previous lesson output | Usage in this lesson |
|---|---|
ci.yml (lint + test + docker build) | Unchanged, as a required PR check; add deploy.yml that runs only on main |
permissions: Least-privilege habit (default contents: read) | Deploy jobs additionally declare id-token: write, and only add it to the jobs that need it |
concurrency Job dependencies needs | used to chain dev → prod and to prevent two deployments from changing production at the same time |
| Artifacts and job outputs | The build job outputs the image digest, and deploy jobs deploy by digest (build once, deploy many) |
Step 1: sign in to Azure and check permissions
az login # Interactive browser sign-in (or az login --use-device-code)
az account show --query "{name:name, id:id, tenant:tenantId, user:user.name}" -o table
az account set --subscription "<subscription name or ID>" # When you have multiple subscriptions
# Confirm your role on the subscription (requires Owner, or Contributor + Role Based Access Control Administrator)
az role assignment list --assignee "$(az ad signed-in-user show --query id -o tsv)" \
--scope "/subscriptions/$(az account show --query id -o tsv)" --query "[].roleDefinitionName" -o tsv
Name Id Tenant User ------------- ------------------------------------ ------------------------------------ ------------------ Pay-As-You-Go 11111111-2222-3333-4444-555555555555 aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee you@example.com Owner
az role assignment create step will fail (Contributor does not include Microsoft.Authorization/roleAssignments/write). Ask your administrator to grant Role Based Access Control Administrator (you can add a condition to restrict which roles can be assigned), or grant Owner at the resource-group level.Step 2: register resource providers, install extensions, write the environment variable file
az provider register -n Microsoft.App --wait az provider register -n Microsoft.OperationalInsights --wait az provider register -n Microsoft.ContainerRegistry --wait az extension add --name containerapp --upgrade --only-show-errors cat > ~/gh-lab.env <<EOF RG=rg-gh-lab LOC=canadacentral ACR=acrghlab$RANDOM$RANDOM # Globally unique, 5–50 lowercase letters and digits CAE=cae-gh-lab APP_DEV=myapp-dev APP_PROD=myapp-prod PORT=5000 REPO=$(gh repo view myapp --json nameWithOwner -q .nameWithOwner 2>/dev/null || echo "$(gh api user -q .login)/myapp") SUB_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) EOF source ~/gh-lab.env && cat ~/gh-lab.env
Note:$RANDOM Expanded when the file is written, so the ACR name is fixed; in each new terminal, first run source ~/gh-lab.env. All commands in this lesson rely on these variables.
Step 3: create the resource group, ACR and Container Apps environment
source ~/gh-lab.env
az group create -n $RG -l $LOC --tags course=github-8h part=3 -o none
az acr create -g $RG -n $ACR --sku Basic --admin-enabled false -o none
az containerapp env create -g $RG -n $CAE -l $LOC -o none # By default this also creates a Log Analytics workspace
az containerapp env show -g $RG -n $CAE --query "{state:properties.provisioningState, domain:properties.defaultDomain}" -o table
State Domain --------- ------------------------------------------ Succeeded bluepond-1a2b3c4d.canadacentral.azurecontainerapps.io
Step 4: create the dev / prod apps (using a public sample image as a placeholder first)
source ~/gh-lab.env
for APP in $APP_DEV $APP_PROD; do
az containerapp create -g $RG -n $APP --environment $CAE \
--image mcr.microsoft.com/k8se/quickstart:latest --target-port 80 --ingress external \
--min-replicas 0 --max-replicas 2 --system-assigned -o none
# Runtime identity: the app’s own system-assigned identity, granted only AcrPull to pull images from ACR
PID=$(az containerapp show -g $RG -n $APP --query identity.principalId -o tsv)
az role assignment create --assignee-object-id $PID --assignee-principal-type ServicePrincipal \
--role AcrPull --scope $(az acr show -n $ACR --query id -o tsv) -o none
az containerapp registry set -g $RG -n $APP --server $ACR.azurecr.io --identity system -o none
done
# prod uses multiple-revision mode for a 0% traffic canary and rollback (module 4)
az containerapp revision set-mode -g $RG -n $APP_PROD --mode multiple -o none
az containerapp list -g $RG --query "[].{name:name, fqdn:properties.configuration.ingress.fqdn, mode:properties.configuration.activeRevisionsMode}" -o table
Name Fqdn Mode ---------- ------------------------------------------------------------------- -------- myapp-dev myapp-dev.bluepond-1a2b3c4d.canadacentral.azurecontainerapps.io Single myapp-prod myapp-prod.bluepond-1a2b3c4d.canadacentral.azurecontainerapps.io Multiple
mcr.microsoft.com/k8se/quickstart (port 80) to create the app, ingress and runtime identity; in module 4 the first pipeline deployment replaces the image and port with myapp:5000. New role assignments can take a few minutes to take effect, so grant AcrPull early.Warm-up: answer from memory (30 seconds)
In the previous lesson, what is the difference between GITHUB_TOKEN and the OIDC ID token used in this lesson?
GITHUB_TOKEN The first is the installation token GitHub gives a job for calling GitHub API ; the OIDC ID token is an identity assertion signed by GitHub as the identity provider, JWT used to prove to external clouds that it is a particular run in a given repository and environment; the cloud then exchanges it for its own short-lived access token. Getting the ID token requires the permissions: id-token: write.
If a job sets environment: prod, which secrets can it read?
Organization-level and repository-level secrets, and the prod environment’s secrets (environment-level values take precedence when names clash). If prod requires approval, the job does not start until approval, so it cannot read the environment secrets. This sets up module 3 of this lesson.
Readiness self-assessment (8 items)
Tick off the items you can already do (saved in this browser). Come back and tick again after finishing this lesson and the capstone lab.
Module 1 · From CI to CD: choosing a deployment architecture
- Explain the difference between Continuous Delivery and Continuous Deployment, and the standard GitHub pattern of “build once, promote through environments”.
- Based on team skills, application shape and control needs, make a reasoned choice among Container Apps, AKS, App Service and Functions.
- Compare push-based and GitOps pull-based deployment: where the credentials live, who owns the “current state”, how rollback works, and how it is audited.
What: what CD adds on top of CI
CI CI’s output is “a tested commit”; CD CD’s output is “an artifact running in an environment and traceable to a commit”. On GitHub, CD usually consists of three parts:
- Artifacts: container images (ACR), zip packages, Bicep/Terraform plans. The key is that they are immutable and traceable— tag with the commit SHA, and when deploying prefer the digest (
@sha256:…). - Identity: how the pipeline proves “I am allowed to deploy”. This lesson uses OIDC workload identity federation throughout,with no cloud password stored in the repository (module 2).
- Gate: environment approvals, wait timers, branch restrictions and custom protection rules (module 3), plus post-deployment smoke tests and rollback.
Continuous Delivery: every commit that passes CI can be deployed to production with one click, but requires manual approval; Continuous Deployment: anything that passes all automated checks goes live automatically, with no manual gate. Most teams use continuous deployment for dev and continuous delivery for prod — exactly the shape of myapp in this lesson.
Why: why choose first
The deployment target determines what the GitHub pipeline’s “last mile” looks like: which API to call, which RBAC role is needed, how canaries are run and how coarse rollback is. For example, Container Apps rolls back by “shifting traffic back to the old revision”; on AKS it is kubectl rollout undo or reverting in the GitOps repo; on App Service it is “swapping the slot again”; on Functions it is redeploying the old package or using slots (depending on the plan).
How: four common Azure deployment targets
| Azure Container Apps (ACA) | AKS | App Service | Azure Functions | |
|---|---|---|---|---|
| Abstraction level | Serverless containers (underlying Kubernetes + KEDA + Envoy, invisible to users) | Managed Kubernetes; the control plane is managed, while you are responsible for nodes and cluster components | Managed web platform (code or containers) | Event-driven functions |
| GitHub deployment method | az containerapp update / Bicep / official action | kubectl / Helm / azure/k8s-deploy, or GitOps (Flux extension, Argo CD) | azure/webapps-deploy, zip deploy, container image | azure/functions-action, zip deploy |
| Canary / rollback | Revisions + traffic percentage + labels | Deployment rolling updates, service mesh or Gateway weights | Deployment slot swap, percentage routing to slots | Slots supported on some plans; otherwise redeploy |
| Scale to zero | Yes (Consumption) | Requires KEDA, and the nodes still bill | No (the plan bills continuously) | Yes (Consumption / Flex Consumption) |
| Typical permissions needed by the pipeline identity | Write permission on the app resource + ACR push | Cluster credentials (Azure RBAC for Kubernetes or admin credentials) + namespace-level permissions | Write permission on the site (and its slots) | Write permission on the function app |
| Suited for | Microservices, APIs, background jobs, teams that do not want to run Kubernetes | Needs the full Kubernetes API, CRDs, service mesh, multi-tenant platforms | Traditional web apps; needs slots and built-in authentication | Event handling, scheduled tasks, glue logic |
Push-based deployment vs GitOps pull-based deployment
| Push-based | GitOps pull-based | |
|---|---|---|
| Who calls the target API | GitHub Actions runner | An in-cluster agent (Flux / Argo CD) periodically pulls from Git and reconciles |
| Where cloud credentials live | On the runner (short-lived token obtained via OIDC) | In the cluster (workload identity); GitHub only needs permission to write to the Git repo |
| Source of truth for “desired state” | The last successful pipeline run | The Git repository (declarative manifests) |
| Drift handling | Not handled until the next deployment | The agent continuously detects and corrects it |
| Rollback | Re-run the deployment job for the old version, or the platform’s native rollback | git revert Revert the manifest commit |
| Applicable targets | Any target with an API (ACA, App Service, Functions, AKS) | Mainly Kubernetes (AKS’s GitOps extension is based on Flux v2) |
| Gates on GitHub | Environment approvals block the deployment job directly | Approval sits on the PR that changes the manifest (review + rulesets) |
When: how to choose
- Team has no Kubernetes operations capability, and the service is HTTP/event-driven containers → ACA + push-based (this lesson’s main path).
- A platform team and AKS cluster already exist, and you need CRDs or multi-tenancy → AKS + GitOps, where the GitHub pipeline only builds the image and opens a PR that changes the image tag in the manifest repo.
- Traditional .NET/Java/Node web app that needs zero downtime with “warm up, then swap” → App Service + deployment slots.
- Whichever target you choose, follow the rule “build once, promote through environments”: the same image digest moves from dev to prod; never rebuild for prod.
Architecture diagram: myapp’s push-based CD (this lesson’s main path)
Comparison diagram: credential boundaries of push-based and pull-based
Interactive selector: choose a deployment target for your service
Answer 5 questions; the selector recommends a target, the GitHub deployment method, the minimum RBAC role needed and the rollback method. Every question can be changed, and the result refreshes instantly.
Core commands: find out what the deployment target looks like now
| Command | Purpose | Notes |
|---|---|---|
az containerapp show -g RG -n APP --query properties.template.containers[0].image | Current image | Used after deployment to verify that the SHA that went live is the expected one |
az containerapp revision list -g RG -n APP -o table | Revisions and traffic | ACA’s deployment history |
az aks show -g RG -n AKS --query "{rbac:aadProfile.enableAzureRbac, local:disableLocalAccounts}" | AKS auth mode | Determines how the pipeline gets cluster credentials (module 5) |
az webapp deployment slot list -g RG -n WEB -o table | App Service slots | Slots are only available on the Standard tier and above |
gh run list -w deploy.yml -L 5 | Last 5 deployment runs | GitHub-side deployment history |
gh api repos/$REPO/deployments -q '.[0:5][] | {env:.environment, sha:.sha[0:7], created:.created_at}' | Deployments API records | Any job that uses environment: automatically creates deployment records. |
source ~/gh-lab.env
az containerapp show -g $RG -n $APP_DEV --query "{image:properties.template.containers[0].image, rev:properties.latestRevisionName, fqdn:properties.configuration.ingress.fqdn}" -o table
gh api repos/$REPO/deployments --jq 'length'
Image Rev Fqdn -------------------------------------------- ---------------------- --------------------------------------------------------------- mcr.microsoft.com/k8se/quickstart:latest myapp-dev--0000001 myapp-dev.bluepond-1a2b3c4d.canadacentral.azurecontainerapps.io 0
How to verify: After module 4, the image should change to acrghlab….azurecr.io/myapp@sha256:…, and the number of Deployments grows with each environment job. Common mistake: Assuming latestRevisionName is the revision receiving traffic — in multiple-revision mode this is not always so; check ingress.traffic.
Lab 1: write the deployment design for myapp (about 4 min, pen and paper + commands)
docs/deploy.md, and write down: artifact = $ACR.azurecr.io/myapp@digest; target = ACA; method = push-based.
cd ~/myapp && mkdir -p docs cat > docs/deploy.md <<'EOF' # myapp deployment design - Artifact: ACR image, tagged with the commit SHA; deploy by digest - Target: Azure Container Apps (myapp-dev: Single; myapp-prod: Multiple) - Method: push-based (GitHub Actions + OIDC), no long-lived cloud password - Environments: dev (automatic after merge to main) → prod (required reviewers + main only) - Identities: build = AcrPush on ACR; dev = write myapp-dev; prod = write myapp-prod; app runtime = AcrPull - Rollback: new prod revision canaried at 0% traffic; if smoke tests fail, deactivate the new revision EOF
az containerapp show, and record the two FQDNs in docs/deploy.md.git switch -c docs/deploy-design git add docs/deploy.md && git commit -m "docs: deployment design for Azure" git push -u origin HEAD && gh pr create --fill gh pr checks --watch
All checks were successful 0 cancelled, 0 failing, 1 successful, 0 skipped, and 0 pending checks NAME DESCRIPTION ELAPSED URL ✓ ci / test 41s https://github.com/you/myapp/actions/runs/…
gh pr merge --squash --delete-branch. At this point there is no deploy.yml, so merging deploys nothing.Case 1: rebuilding for prod made “what was tested is not what shipped”
Problem: The team ran one build in each of the dev and prod jobs docker build. One day the upstream base image python:3.13-slim was updated between the two builds. The prod image picked up an OpenSSL patch, which changed certificate-chain behaviour, so prod failed while dev worked. Approach: Change the build job to output the digest, and have both dev and prod deploy the same digest. Constraint: The only differences between dev and prod may come from configuration (environment variables, secret references), not from the artifact.
Case 2: the platform team moves from push-based to GitOps
Problem: 40 repositories each hold deployment permission on the AKS cluster, and audit cannot answer “who changed production, and when?”Approach: Enable the AKS GitOps (Flux v2) extension; each app repository’s pipeline only builds the image and opens a PR against a central manifest repo; the manifest repo uses rulesets to require review from the platform team. Result: Write access to the cluster shrinks from 40 pipeline identities to one Flux identity inside the cluster; rollback = revert the PR. Limitation: The signal that a deployment has finished must be reported back from Flux (via a notification controller or status checks), otherwise GitHub shows no deployment result.
Case 3: a small team moves from App Service to Container Apps
Problem: 3 low-traffic internal APIs each use their own App Service plan (billed continuously). Approach: Move them into the same Container Apps environment, with minimum replicas set to 0. Limitation: After scaling to zero, the first request has a cold start; for APIs with an SLA, set --min-replicas 1 minimum replicas ≥ 1; App Service’s built-in authentication must be replaced with ACA’s built-in authentication or implemented in the app.
Common design mistakes and symptoms
After going live to prod, the version differs from dev even though both jobs used the same SHA
Cause: the two jobs each built separately, or the deployment used a mutable tag (such as :latest,:main) that was overwritten in the meantime.
az containerapp revision list -g $RG -n $APP_PROD --query "[].{rev:name, image:properties.template.containers[0].image}" -o table
az acr manifest list-metadata -r $ACR -n myapp --query "[].{digest:digest, tags:tags}" -o table
Fix: Have the build job output the digest (docker/build-push-action ) and then outputs.digest deploy by image@digest.
In GitOps mode GitHub shows the deployment as successful, but the cluster still runs the old version
Cause: Pushing to the manifest repo does not mean the cluster has reconciled. Flux/Argo CD may be stuck on the old state because of manifest errors or image pull failures.
kubectl get kustomizations,helmreleases -A # Flux kubectl -n argocd get applications # Argo CD
Fix: Add a “wait for reconciliation” step to the pipeline, or use notifications to write the status back to GitHub (commit status / checks).
Using one high-privilege identity for build, dev deployment and prod deployment together
Risk: Any branch that can trigger the workflow, and any poisoned third-party Action, can obtain prod write permission.
Fix: Split identities by job (module 2); the prod identity’s federated credential should trust only environment:prod, and then use the environment to restrict prod deployments to main only (module 3).
1. Use one command to list all Container Apps in rg-gh-lab with their names, revision modes and current images.
az containerapp list -g rg-gh-lab --query "[].{name:name, mode:properties.configuration.activeRevisionsMode, image:properties.template.containers[0].image}" -o table2. Use gh to check the environment and SHA for the last 3 deployment records of the myapp repo.
gh api repos/$REPO/deployments --jq '.[0:3][] | "\(.environment) \(.sha[0:7]) \(.created_at)"'
A company has a 6-person team maintaining 5 Python APIs, with no Kubernetes experience. It requires an approval before prod releases and rollback within 1 minute. How would you design it?
Choose Container Apps + push-based deployment: one container app per API, all in the same environment; on GitHub: build → dev (automatic) → prod (environment with required reviewers); prod uses multiple-revision mode, so the new revision is smoke-tested at 0% traffic before traffic is switched; rollback is simply switching traffic back to the old revision (seconds). Identities are split by job, and federated credentials trust only the matching environment. Not AKS: the team has no operations capability. Not App Service: a dedicated plan for 5 low-traffic APIs is not cost-effective.
Verified teaching videos
Official documentation
- Comparing Container Apps with other Azure container options
- GitHub Docs: Deploying with GitHub Actions
- GitOps Flux v2 (AKS / Arc extension)
Video storyboard (about 75 seconds)
This courseware cannot generate video directly; the storyboard and narration script are provided for use with a video tool.
Visual: a green CI tick, with a question mark beside it pointing at the cloud.
Narration: a green CI only means the code can be merged. CD must answer: which artifact, approved by whom, under which identity, going to where.
Visual: four cards — ACA, AKS, App Service, Functions — flip open in turn, each showing its “rollback method”.
Narration: the deployment target determines the last mile of the pipeline. ACA shifts traffic, AKS rolls back the Deployment, App Service swaps slots.
Visual: on the left, a runner arrow pushes toward the cloud; on the right, a small robot inside the cluster pulls from Git.
Narration: push-based means the runner calls the cloud API; pull-based means an agent inside the cluster pulls from Git, and GitHub only needs permission to write to Git.
Visual: the same image digest moves from a dev box to a prod box.
Narration: whichever you choose, build once and promote through environments: what ships must be exactly the one that was tested.
Module 2 · OIDC federated identity: GitHub → Microsoft Entra ID
- Describe the full token exchange:
id-token: write→ the GitHub OIDC provider issues a JWT → the job presents it as client assertion to the Entra token endpoint → Entra checks the signature and issuer / audience / subject → returns an Azure access token → ARM authorizes via RBAC. - Write the four classic subjects correctly (environment / pull_request / branch / tag) and immutable subjects
repo:OWNER@OWNER_ID/REPO@REPO_ID:…, and know how to query the prefix a repository actually uses via the API and opt in. - Choose between user-assigned managed identity and app registration, and use
azure/login@v3to sign in and explain why client secrets should be retired (credsJSON).
permissions, and the basic structure of a JWT (header.payload.signature). Importance:★★★★★ (the number-one source of cloud deployment failures)What: workload identity federation
The traditional approach is to create a service principal with a client secret in Entra ID, then store the clientId/clientSecret/tenantId/subscriptionId JSON as a GitHub secret (AZURE_CREDENTIALS). Workload identity federation takes a different approach: register a federated identity credential (FIC), stating “I trust tokens from this issuer issued for this subject with audience this audience ”. Then, on each run, GitHub issues a JWT on the spot, and Entra issues an Azure token once validation passes. The repository holds no password that could be stolen and used for a long time.
| FIC field | Value for GitHub | Notes |
|---|---|---|
| issuer | https://token.actions.githubusercontent.com | GitHub.com’s OIDC provider; Entra uses its /.well-known/openid-configuration to fetch JWKS public keys and verify signatures. GHE.com data residency or GHES uses a different issuer. |
| audiences | api://AzureADTokenExchange | azure/login Default audience when requesting an ID token; Entra’s recommended value. Sovereign clouds can change it through the audience audience input |
| subject | (see the table below) | Must match exactly, character for character (case-sensitive, no wildcards) |
| name | e.g. gh-env-prod | 3–120 characters; cannot be changed after creation |
Limit (Microsoft Learn): each app registration or user-assigned managed identity can have at most 20 federated credentials (FICs); the issuer + subject combination must be unique on one identity; attribute values do not support wildcards. A wrong subject still creates successfully, and the error only appears at token exchange.
How: the four classic subject formats (GitHub OIDC reference)
| Job situation | subject (classic format) | Rule |
|---|---|---|
| The job references an environment | repo:OWNER/REPO:environment:prod | highest priority: whenever you specify environment:, it is used regardless of event and branch |
| pull_request trigger and no environment | repo:OWNER/REPO:pull_request | does not include the branch name! PRs from any branch produce the same subject |
| Other events, branches | repo:OWNER/REPO:ref:refs/heads/main | push, workflow_dispatch, schedule and other events |
| Other events, tags | repo:OWNER/REPO:ref:refs/tags/v1.2.0 | One FIC per tag (no wildcards); release scenarios usually use environment instead |
Colons inside values are encoded as %3A. Some Microsoft Learn pages write the PR form as pull-request, whereas the actual token contains pull_request; always treat the subject shown in the run log as authoritative.
Immutable subject (an important 2026 change)
- to @): Repositories created, renamed or transferred after 2026-07-15 automatically use repo:OWNER@OWNER_ID/REPO@REPO_ID:…, for example repo:octocat@123456/my-repo@456789:ref:refs/heads/main. Earlier repositories keep the classic format unless you opt in through the organization or repository OIDC setting (UI or REST API field use_immutable_subject). GitHub Enterprise Server is not applicable.Why change: Names can be changed, transferred and re-registered by others. A classic subject repo:contoso/payments-api:… trusts a “name”; if the original repo is renamed, someone else can create a repo with the same name and get the same subject — Microsoft calls this subject recycling. A numeric ID is never reused once assigned, so an FIC bound to an ID trusts only the original repository, forever.
How to tell which format a repository uses: call GET /repos/{owner}/{repo}/actions/oidc/customization/sub; the sub_claim_prefix field in the response gives the current prefix (see the Commands page); or look at the subject azure/login printed Federated token details in the run log.
AADSTS700213② the reverse: azure/login the README specifically warns that if you fill in the optional “Owner ID / Repository ID” fields when creating an FIC in the Azure portal, the portal generates a subject that includes IDs, whereas old repositories that have not opted into the immutable format emit tokens without IDs, so they will never match either. The only conclusion: the FIC subject must be sub exactly identical to the one in the token.Migrating an old repository (zero downtime, Microsoft Learn recommended procedure): First, for the immutable subject add an FIC (alongside the old one) → opt the repository in on GitHub → run the workflow to confirm success → delete the old classic FIC, removing trust that could be “reclaimed”.
User-assigned managed identity vs app registration
| User-assigned managed identity (UAMI) | App registration (service principal) | |
|---|---|---|
| Where created | An Azure resource (in a resource group),az identity create | an Entra directory object,az ad app create |
| Permissions needed | Managed Identity Contributor (or Contributor) on the resource group | Directory permission to create apps (many enterprise tenants forbid ordinary users from registering apps) |
| Can create secrets? | No— by design, only federated credentials can be used | Yes (so policy must prohibit it) |
| Lifecycle | Deleted along with the resource group | Directory object must be cleaned up separately |
| Access to Microsoft Graph and other directory APIs | Application permissions can be granted, but usually need an admin consent process | Common usage |
| Flexible federated identity credentials (claims matching expression, preview) | Follow the official docs (current documentation examples target app registrations) | Supported (preview) |
This lesson uses a UAMI: subscription Owner is enough, no directory admin is needed, and it is cleaned up when the resource group is deleted. azure/login The usage of the client-id input is identical for both: enter the UAMI’s clientId or the app registration’s Application (client) ID.
Why stop using client secrets
- Long-lived: secrets are often valid for one to two years; if leaked, they can be used from anywhere until they expire or are revoked. OIDC-issued access tokens usually expire after about an hour, and the ID token itself is even shorter-lived.
- Not bound to context: whoever holds the secret does not need to run inside your repository; the OIDC subject binds trust to a specific environment or branch of a repository.
- Rotation cost and incidents: an expired secret causing a failed deployment at midnight is a classic incident; many organizations now use app-management policies to forbid creating secrets.
- Supply-chain risk: any step that can read secrets (including a poisoned third-party Action) can send the JSON out.
azure/loginThe README also notes: whenever any of theclient-id/tenant-id/subscription-idinputs is set,credsthe OIDC inputs are ignored — so during a migration you can add the OIDC inputs first, verify, and then delete the secret.
When: subject design principles
- Deploy jobs always use the environment subject, and set the environment’s branch policy to allow only main (module 3) — “who may deploy” is decided by GitHub’s protection rules; Azure only checks the environment name.
- PR jobs get a read-only identity only (subject
pull_request, role Reader) for what-if / plan; PRs from forks do not getid-token: write. - One identity per trust boundary: do not let dev and prod share one identity and rely on multiple FICs to tell them apart — RBAC is granted per identity, so sharing means dev jobs also get prod permissions.
- When you need tighter constraints (for example, trusting only a particular reusable workflow), use a
include_claim_keyscustom subject template (such as addingjob_workflow_ref),first configure the matching in the cloud, then switch the template.
id-token: write ① “lets the job write to GitHub” — no, it only allows requesting an OIDC ID token. ② “Adding workflow-level permissions is enough” — note that a job-level permissions will completely override the workflow-level setting; if the job only writes id-token: write will make contents become none, so checkout fails. ③ “FICs support refs/heads/*” — they do not support wildcards; use flexible federated credentials when you need a matching expression (preview, with extra restrictions). ④ “client-id is a secret” — it is not a password, but the README suggests passing these inputs only from the azure/login secrets context secrets , and masking them in logs by default (mask-client-id: true).Sequence diagram: the six steps of one OIDC sign-in
Decision diagram: what is this job’s sub?
Core animation: OIDC token exchange (switchable failure scenarios)
Select a scenario, then click “Run job”. Each step highlights the parties involved and shows in the terminal what you would actually see in the Actions log or in Azure. The last scenario shows “authentication succeeds but authorization fails”.
Subject calculator
Enter the repository information and the calculator gives the sub in that job’s token, and compares it with the subject you plan to enter in the FIC (character by character, case-sensitive).
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
az identity create -g RG -n NAME | Create a user-assigned managed identity | Output clientId (for azure/login) and principalId (for role assignment) |
az identity federated-credential create | Add an FIC to a UAMI | --identity-name --name --issuer --subject --audiences |
az ad app federated-credential create --id APP --parameters fic.json | Add an FIC to an app registration | In the JSON: name / issuer / subject / audiences |
az role assignment create --assignee-object-id PID --assignee-principal-type ServicePrincipal --role R --scope S | Grant RBAC | Use object ID + principal type to avoid failures caused by Graph query delay |
gh api repos/OWNER/REPO/actions/oidc/customization/sub | View the subject template and current prefix | Response includes use_default,include_claim_keys,use_immutable_subject and sub_claim_prefix |
gh api -X PUT …/oidc/customization/sub -F use_default=true -F use_immutable_subject=true | Opt an older repository into the immutable format | First add the new-format FIC in Azure, then run |
gh api repos/OWNER/REPO --jq '.owner.id, .id' | Query the owner ID and repository ID | Used when constructing the immutable subject |
source ~/gh-lab.env gh api repos/$REPO/actions/oidc/customization/sub
{
"use_default": true,
"use_immutable_subject": true,
"sub_claim_prefix": "repo:octo-dev@5544123/myapp@821093847"
}
Field names follow the GitHub REST documentation on the “Actions OIDC” page (verified 2026-11-15). If your gh version or API response does not contain sub_claim_prefix, build the prefix yourself using the fallback logic below, and use the subject claim in the first run log as the final reference.
# Fallback: build the prefix from repository creation time and ID read OWNER OID NAME RID CREATED < <(gh api repos/$REPO --jq '"\(.owner.login) \(.owner.id) \(.name) \(.id) \(.created_at)"') PREFIX="repo:$OWNER@$OID/$NAME@$RID" [[ "$CREATED" < "2026-07-15" ]] && PREFIX="repo:$OWNER/$NAME" # Older repository that has not opted in and has not been renamed or transferred echo "$PREFIX"
Common mistake: An older repository that is renamed or transferred after 2026-07-15 also switches to the immutable format, so judging by creation date alone is error-prone — this is the reason to prefer sub_claim_prefix .
Lab 2: three identities, five federated credentials, first keyless sign-in (about 10 min)
source ~/gh-lab.env
for n in build dev prod; do az identity create -g $RG -n id-myapp-$n -o none; done
az identity list -g $RG --query "[].{name:name, clientId:clientId}" -o table
Name ClientId -------------- ------------------------------------ id-myapp-build 0a1b2c3d-1111-2222-3333-444455556666 id-myapp-dev 1b2c3d4e-1111-2222-3333-444455556666 id-myapp-prod 2c3d4e5f-1111-2222-3333-444455556666
source ~/gh-lab.env
pid(){ az identity show -g $RG -n $1 --query principalId -o tsv; }
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
CAE_ID=$(az containerapp env show -g $RG -n $CAE --query id -o tsv)
# build: AcrPush (push/pull images) + Reader (lets az acr login read registry metadata)
az role assignment create --assignee-object-id $(pid id-myapp-build) --assignee-principal-type ServicePrincipal --role AcrPush --scope $ACR_ID -o none
az role assignment create --assignee-object-id $(pid id-myapp-build) --assignee-principal-type ServicePrincipal --role Reader --scope $ACR_ID -o none
# Custom role: allows linking an app to an environment (when updating an app, ARM checks association authorization against the referenced environment)
cat > /tmp/aca-env-join.json <<EOF
{ "Name": "ACA Environment Joiner ($RG)",
"Description": "Read and join the lab Container Apps environment",
"Actions": ["Microsoft.App/managedEnvironments/read","Microsoft.App/managedEnvironments/join/action"],
"AssignableScopes": ["/subscriptions/$SUB_ID/resourceGroups/$RG"] }
EOF
az role definition create --role-definition @/tmp/aca-env-join.json -o none
for e in dev prod; do
APP=$([ $e = dev ] && echo $APP_DEV || echo $APP_PROD)
APP_ID=$(az containerapp show -g $RG -n $APP --query id -o tsv)
az role assignment create --assignee-object-id $(pid id-myapp-$e) --assignee-principal-type ServicePrincipal --role Contributor --scope $APP_ID -o none
az role assignment create --assignee-object-id $(pid id-myapp-$e) --assignee-principal-type ServicePrincipal --role "ACA Environment Joiner ($RG)" --scope $CAE_ID -o none
done
az role assignment list -g $RG --query "[?principalType=='ServicePrincipal'].{role:roleDefinitionName, scope:scope}" -o table | sed 's#/subscriptions/[^/]*/resourceGroups/##'
A newly created custom role definition may need 1–2 minutes before it can be assigned; if the second az role assignment create reports “role definition not found”, wait and retry. If your registry has “ABAC repository permissions” enabled, AcrPush no longer takes effect and you must use the repository roles for that mode (see the official ACR documentation).
source ~/gh-lab.env
PREFIX=$(gh api repos/$REPO/actions/oidc/customization/sub --jq '.sub_claim_prefix // empty')
[ -z "$PREFIX" ] && echo "sub_claim_prefix was not returned; set PREFIX with the fallback logic on the Commands page" && return 2>/dev/null
echo "PREFIX=$PREFIX" | tee -a ~/gh-lab.env
fic(){ az identity federated-credential create -g $RG --identity-name $1 --name $2 \
--issuer https://token.actions.githubusercontent.com --audiences api://AzureADTokenExchange \
--subject "$PREFIX:$3" -o none && echo "✓ $1 $PREFIX:$3"; }
fic id-myapp-build gh-main ref:refs/heads/main
fic id-myapp-dev gh-env-dev environment:dev
fic id-myapp-prod gh-env-prod environment:prod
# The read-only identity is reserved for the module 6 what-if; create
az identity create -g $RG -n id-myapp-plan -o none
az role assignment create --assignee-object-id $(az identity show -g $RG -n id-myapp-plan --query principalId -o tsv) --assignee-principal-type ServicePrincipal --role Reader --scope $(az group show -n $RG --query id -o tsv) -o none
fic id-myapp-plan gh-pr pull_request
fic id-myapp-plan gh-main-ro ref:refs/heads/main
PREFIX=repo:octo-dev@5544123/myapp@821093847 ✓ id-myapp-build repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/main ✓ id-myapp-dev repo:octo-dev@5544123/myapp@821093847:environment:dev ✓ id-myapp-prod repo:octo-dev@5544123/myapp@821093847:environment:prod ✓ id-myapp-plan repo:octo-dev@5544123/myapp@821093847:pull_request ✓ id-myapp-plan repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/main
source ~/gh-lab.env
cid(){ az identity show -g $RG -n $1 --query clientId -o tsv; }
gh secret set AZURE_TENANT_ID -R $REPO --body "$TENANT_ID"
gh secret set AZURE_SUBSCRIPTION_ID -R $REPO --body "$SUB_ID"
gh secret set AZURE_CLIENT_ID_BUILD -R $REPO --body "$(cid id-myapp-build)"
gh secret set AZURE_CLIENT_ID_PLAN -R $REPO --body "$(cid id-myapp-plan)"
gh variable set ACR -R $REPO --body "$ACR"; gh variable set RG -R $REPO --body "$RG"
gh secret list -R $REPOname: oidc-test
on: workflow_dispatch
permissions:
contents: read
jobs:
whoami:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # Job-level permissions override workflow-level permissions; write both
steps:
- name: Show OIDC claims (payload only)
run: |
TOKEN=$(curl -sS -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
"$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" | jq -r .value)
echo "::add-mask::$TOKEN"
P=$(echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+'); while [ $(( ${#P} % 4 )) -ne 0 ]; do P="$P="; done
echo "$P" | base64 -d | jq '{iss, aud, sub, ref, environment, repository_id, repository_owner_id, event_name, exp, iat}'
- uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID_BUILD }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- run: az acr show -n ${{ vars.ACR }} --query loginServer -o tsv
cd ~/myapp && git switch main && git pull mkdir -p .github/workflows && $EDITOR .github/workflows/oidc-test.yml # paste the content above git add .github/workflows/oidc-test.yml && git commit -m "ci: oidc smoke test" && git push gh workflow run oidc-test.yml --ref main && sleep 5 && gh run watch --exit-status
{
"iss": "https://token.actions.githubusercontent.com",
"aud": "api://AzureADTokenExchange",
"sub": "repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/main",
"ref": "refs/heads/main",
"environment": null,
"repository_id": "821093847",
"repository_owner_id": "5544123",
"event_name": "workflow_dispatch",
...
}
Run azure/login@v3
Federated token details:
issuer - https://token.actions.githubusercontent.com
subject claim - repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/main
audience - api://AzureADTokenExchange
Login successful.
acrghlab1234512345.azurecr.io
Pushing directly to main requires a bypass permission in the ruleset; if main is protected, use the PR merge path, then run it manually from the Actions page. Verify: The subject claim value in the log must match the FIC subject you created in Azure exactly.
Case 1: migrating AZURE_CREDENTIALS across 120 repositories
Problem: The platform team found that 120 repositories each stored a service-principal secret JSON; 30 of them expire within 6 months, and nobody knows who uses them. Approach: For each repository, create a UAMI and FIC per “build / each environment”; add permissions: id-token: write and switch to client-id/tenant-id/subscription-id inputs (at this point creds is ignored, so both can coexist safely for a week); after confirming success, delete the secret and delete the key in Entra; finally, use a tenant app-management policy to prohibit new client secrets. Limitation: A small number of pipelines that still need Graph application permissions keep their app registration, but they too switch to federated credentials.
Case 2: after the repository was transferred to a new organization, all deployments failed
Problem: In September 2026 we moved payments-api from a personal account to the company organization, and all deployments reported AADSTS700213. Root cause: The transfer happened after 2026-07-15, so the repository automatically adopted the immutable subject, and the owner name also changed. Fix: Using the subject claim value from the run log, add a new FIC and delete the old one after verifying. Prevention: Include repository renames and transfers in the change process, and add the new subject in the cloud in advance.
Case 3: a dev branch borrowed the same identity to deploy to prod
Problem: A team’s deployment identity had both ref:refs/heads/main and environment:prod FICs. A developer on a feature branch wrote a job that references environment: prod , and because the prod environment had no branch restriction, the job obtained production permission. Fix: Set the prod environment to a deployment branch policy of “main only” and require reviewers; keep only the environment FIC on the identity. Lesson: The security of an environment subject depends entirely on GitHub’s environment protection rules — which is the topic of the next module.
Common errors and fixes
Error: AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:octo-dev@5544123/myapp@821093847:environment:prod'
Cause: The FIC has no record that exactly matches the token’s sub : the environment name or branch differs, PR and branch are confused, classic and immutable formats are mixed, or the repository was renamed or transferred.
az identity federated-credential list -g $RG --identity-name id-myapp-prod --query "[].subject" -o tsv gh api repos/$REPO/actions/oidc/customization/sub --jq .sub_claim_prefix
Fix: Copy the subject exactly as shown in the error message’s quotes and add a new FIC. A new FIC can take a short time to propagate; retry after a moment.
Error: AADSTS7002138: No matching federated identity record found … The subject matches with case-insensitive comparison, but not with case-sensitive comparison.
Cause: Different case, e.g. the FIC says environment:Prod, but the token has environment:prod or the owner name has uppercase letters.
Fix: FIC names cannot be modified; delete and recreate it using the case shown in the run log.
Error: Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable / Please make sure to give write permissions to id-token in the workflow.
Cause: the job lacks id-token: write; or a job-level permissions overrides the workflow-level setting; or the PR comes from a fork.
Fix: In that job’s permissions , write both contents: read and id-token: write. Fork PRs should not get cloud credentials; instead use pull_request to run only checks that do not need cloud access.
AADSTS700016: Application with identifier '…' was not found in the directory '…'
Cause:client-id Wrong value entered for tenant-id (for example, entering principalId / objectId), or it points to a different tenant.
az identity show -g $RG -n id-myapp-build --query "{clientId:clientId, principalId:principalId, tenant:tenantId}"
Fix:client-id Use clientId; role assignments use principalId.
Login successful, but the next az command reports No subscriptions found / AuthorizationFailed
Cause: Successful authentication does not mean you have permission. If the identity has no role on that subscription,az it cannot see the subscription; if it has a role whose scope does not cover the target resource, it reports AuthorizationFailed.
Fix: Check the role assignments and scopes (covered in module 7). If you only need to sign in to the tenant (for example, to call Graph), set allow-no-subscriptions: true.
1. For id-myapp-prod, add one federated credential that trusts environment:prod (assuming the prefix is already in $PREFIX).
az identity federated-credential create -g rg-gh-lab --identity-name id-myapp-prod --name gh-env-prod \ --issuer https://token.actions.githubusercontent.com --audiences api://AzureADTokenExchange \ --subject "$PREFIX:environment:prod"
2. For a repository created in 2025 that has never been renamed and opts into the immutable subject, write the command sequence with zero downtime.
# ① First add the FIC for the new format in Azure (coexisting with the old one)
read OID RID < <(gh api repos/$REPO --jq '"\(.owner.id) \(.id)"')
az identity federated-credential create -g $RG --identity-name id-myapp-prod --name gh-env-prod-imm \
--issuer https://token.actions.githubusercontent.com --audiences api://AzureADTokenExchange \
--subject "repo:${REPO%/*}@$OID/${REPO#*/}@$RID:environment:prod"
# ② Opt the repository in on GitHub
gh api -X PUT repos/$REPO/actions/oidc/customization/sub -F use_default=true -F use_immutable_subject=true
# ③ After a deployment run confirms success, delete the old FIC
az identity federated-credential delete -g $RG --identity-name id-myapp-prod --name gh-env-prod --yesA workflow runs what-if on pull_request and the FIC is configured for repo:o/r:ref:refs/heads/feature-x, and login fails. The developer says, “the PR comes from the feature-x branch.” Explain and give the correct design.
A pull_request job without an environment reference has a token sub is repo:o/r:pull_request (in the immutable format, the ID-bearing prefix + :pull_request) and has nothing to do with the source branch. Correct design: give the read-only identity (Reader) an FIC for pull_request so every PR can run what-if/plan; write permission goes only to the deployment identity with the environment subject. Note that fork PRs get no id-token by default, so what-if being unavailable for forks is an intended security feature.
Verified teaching videos
Official documentation
- GitHub: OpenID Connect reference (subject format, immutable subject, claim list)
- Microsoft Learn: Migrate GitHub Actions federated credentials to immutable subjects
- Microsoft Learn: Create a trust relationship (FIC fields and limits)
- Azure/login README (inputs, v3 support policy, troubleshooting AADSTS700213 / 7002138)
- GitHub Changelog: Immutable subject claims for GitHub Actions OIDC tokens
Video storyboard (about 90 seconds)
Visual: a key labeled clientSecret is copied into ten keys and scattered everywhere.
Narration: the problem with long-lived secrets is not whether they leak, but that once leaked they can be used everywhere for a long time.
Visual: the runner holds up an ID card stamped by GitHub, with fields such as sub printed on it.
Narration: OIDC lets every run present a GitHub-signed ID card on the spot. The sub field shows which repository, environment or branch it came from.
Visual: the Entra gatekeeper ticks off three lines — issuer, audience, subject; when the third line gets a cross, an AADSTS700213 pop-up appears.
Narration: Entra compares the three fields character by character. One wrong letter or one missing numeric ID, and it is rejected.
Visual: the repository name plate is swapped out, but the number on the back stays the same; the federated credential is firmly tied to that number.
Narration: from July 15, 2026, repositories that are created, renamed or transferred use an immutable subject with a numeric ID by default. The name can change, and the trust cannot be taken over by someone else.
Module 3 · Environments, approvals and deployment protection rules
- Configure every protection option of an environment: required reviewers, prevention of self-approval, wait timers, deployment branches and tags, admin bypass, and custom deployment protection rules.
- Understand the visibility of environment-level secrets and variables, the timing rule that they are unreadable before approval, and how they work with the OIDC environment subject.
- Know which features are available on Free / Pro / Team / Enterprise for public and private repositories, and choose the correct repository visibility for personal experiments.
What: what an environment is
An environment is a named deployment target (for example dev,prod). When a job sets environment: prod , four things happen:
- Before the job starts, the environment's deployment protection rules, and only if all pass is the job assigned to a runner.
- The job can read the environment's secrets (
secrets.X) and variables (vars.X), with same-name values overriding the repository- and organization-level ones. - GitHub automatically creates a deployment record (Deployments API), and the repository home page shows environments and recent deployments; you can use
environment.urlto set the access URL. - The OIDC token's
subbecomes…:environment:prod, withenvironmentclaims.
If a workflow references an environment that does not exist, GitHub automatically creates it (with no protection rules). So create the environment and set its rules first, then write the workflow.
How: rule-by-rule explanation (GitHub Docs, verified 2026-11-15)
| Rule | Behavior | Key points |
|---|---|---|
| Required reviewers | Up to 6 users or teams; any one person's approval is enough | Reviewers need at least read access to the repository; if rejected, the job fails |
| Prevent self-review | The person who triggers the deployment cannot approve their own deployment | On a personal repository where you are the only reviewer,do not enable it,, otherwise no one can ever approve |
| Wait timer | Wait 1–43,200 minutes (30 days) before the job starts | Wait time does not count toward billed minutes; often used for “observe dev for 15 minutes after merging” |
| Deployment branches and tags | No restriction / Protected branches only / Selected branches and tags (matched by name pattern GITHUB_REF) | “Protected branches only” equals no restriction when no branch is protected; branch and tag patterns are configured separately |
| Allow administrators to bypass | Default: enabled, admins can force-bypass protection rules | For production, it is recommended to turn this off so everyone goes through approval |
| Custom deployment protection rules | Implemented by a GitHub App; after receiving a deployment_protection_rule webhook, it calls the API and returns approved / rejected | the official docs currently label this as public preview; each environment can enable at most 6 custom rules at once; common uses: checking monitoring alerts, change tickets and quality gates |
Timing of environment secrets / variables
- Only jobs that reference this environment can read them; other jobs in the same workflow cannot.
- When approval is required, the job does not start before approval, so it also cannot read environment secrets. The approver is approving exactly “handing the prod credentials to this run.”
- Jobs on self-hosted runners are not isolated; environment secrets need the same protection as repository and organization secrets.
Plans and availability (summary of GitHub Docs)
| Feature | Public repo | Private repo: Free | Private: Pro / Team | Private / internal: Enterprise |
|---|---|---|---|---|
| environments, environment secrets / variables, deployment branches and tags | All plans ✓ | ✗ | ✓ | ✓ |
| Required reviewers, wait timer, admin bypass control, custom rules | All plans ✓ | ✗ | ✗ | ✓ |
myapp to public in order to use required reviewers (the repo contains no passwords, so public is safe; cloud identifiers are not secrets either). Alternatively, use a trial organization on GitHub Enterprise Cloud. Availability follows the official GitHub docs; plan rules may change.When: how to pair environments with rules
| Environment | Recommended rules | OIDC identity |
|---|---|---|
dev | Deployment branches: only main; no reviewers (continuous deployment) | id-myapp-dev (can only write myapp-dev) |
prod | Deployment branches: only main (for release, switch to v* tags); required reviewers; (team) prevent self-review; disable admin bypass; optionally a wait timer or custom rules | id-myapp-prod (can only write myapp-prod) |
if: github.ref == 'refs/heads/main' in the workflow is enough” is wrong: anyone who edits the workflow file can delete that line; deployment branch policy is enforced by the platform, so editing the workflow cannot get around it.Flowchart: a prod job from queued to receiving credentials
Comparison: the secrets seen by three jobs in the same workflow
| Job | environment | AZURE_CLIENT_ID visible | OIDC sub |
|---|---|---|---|
| build | None | Repository level AZURE_CLIENT_ID_BUILD | …:ref:refs/heads/main |
| deploy-dev | dev | dev environment level AZURE_CLIENT_ID (id-myapp-dev) | …:environment:dev |
| deploy-prod | prod | prod environment level AZURE_CLIENT_ID (id-myapp-prod),after approval | …:environment:prod |
Deployment gate simulator
Adjust the prod environment rules and this run's conditions, then click “Trigger deploy-prod”. Observe the job's status at each gate, when it can read the environment secrets, and the message shown on the Actions page on failure.
Manage environments with the REST API (scriptable and auditable)
| API (gh api) | Purpose | Key fields |
|---|---|---|
PUT repos/{o}/{r}/environments/{name} | Create / update environment | wait_timer,prevent_self_review,reviewers[] (type: User/Team,id) deployment_branch_policy |
POST …/environments/{name}/deployment-branch-policies | , add branch/tag patterns | name (e.g., main,v*) type (branch / tag) |
gh secret set NAME --env prod / gh variable set NAME --env prod | Environment-level secret / variable | Visible only to jobs that reference this environment |
GET repos/{o}/{r}/actions/runs/{id}/pending_deployments | View deployments awaiting approval | Returns the environment ID and whether the current user can approve |
POST …/runs/{id}/pending_deployments | Approve / reject | environment_ids[],state (approved / rejected),comment |
POST …/runs/{id}/deployment_protection_rule | GitHub App callback for custom rules | environment_name,state,comment |
# View the current protection rules of the prod environment
gh api repos/$REPO/environments/prod --jq '{name, protection_rules: [.protection_rules[] | {type, wait_timer, prevent_self_review}], branch_policy: .deployment_branch_policy, can_admins_bypass}'
{
"name": "prod",
"protection_rules": [
{ "type": "required_reviewers", "wait_timer": null, "prevent_self_review": false },
{ "type": "branch_policy", "wait_timer": null, "prevent_self_review": null }
],
"branch_policy": { "protected_branches": false, "custom_branch_policies": true },
"can_admins_bypass": false
}
Field names follow the GitHub REST “Deployment environments” docs. can_admins_bypass It can also be set in a PUT request.
Lab 3: create dev / prod environments and write environment-level secrets (about 6 minutes)
source ~/gh-lab.env gh repo view $REPO --json visibility -q .visibility # If PRIVATE and on a Free account: gh repo edit $REPO --visibility public --accept-visibility-change-consequences
gh api -X PUT repos/$REPO/environments/dev --input - <<'EOF' >/dev/null
{ "deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true } }
EOF
gh api -X POST repos/$REPO/environments/dev/deployment-branch-policies -f name=main -f type=branch --jq '{name, type}'MY_ID=$(gh api user --jq .id)
gh api -X PUT repos/$REPO/environments/prod --input - <<EOF >/dev/null
{ "wait_timer": 0,
"prevent_self_review": false,
"reviewers": [ { "type": "User", "id": $MY_ID } ],
"can_admins_bypass": false,
"deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true } }
EOF
gh api -X POST repos/$REPO/environments/prod/deployment-branch-policies -f name=main -f type=branch --jq '{name, type}'
gh api repos/$REPO/environments --jq '.environments[] | {name, rules: [.protection_rules[].type]}'
{"name":"main","type":"branch"}
{"name":"dev","rules":["branch_policy"]}
{"name":"prod","rules":["required_reviewers","branch_policy"]}
A personal repository has only you, so “prevent self-review” is turned off here. For team repositories, turn it on and configure at least two reviewers or a team.
AZURE_CLIENT_ID in different environments point to different identities; the workflow syntax is identical:
cid(){ az identity show -g $RG -n $1 --query clientId -o tsv; }
gh secret set AZURE_CLIENT_ID --env dev -R $REPO --body "$(cid id-myapp-dev)"
gh secret set AZURE_CLIENT_ID --env prod -R $REPO --body "$(cid id-myapp-prod)"
gh variable set APP --env dev -R $REPO --body "$APP_DEV"
gh variable set APP --env prod -R $REPO --body "$APP_PROD"
gh secret list --env prod -R $REPO; gh variable list --env prod -R $REPOname: env-probe
on: workflow_dispatch
permissions: { contents: read }
jobs:
probe:
runs-on: ubuntu-latest
environment: prod
steps:
- run: echo "APP=${{ vars.APP }}"
git switch -c probe/env && mkdir -p .github/workflows $EDITOR .github/workflows/env-probe.yml && git add . && git commit -m "ci: env probe" && git push -u origin HEAD gh workflow run env-probe.yml --ref probe/env; sleep 8; gh run list -w env-probe.yml -L 1
X env-probe env-probe probe/env workflow_dispatch … failure # Run page comment: Branch "probe/env" is not allowed to deploy to prod due to environment protection rules.
Cleanup: git switch main && git push origin --delete probe/env. Note workflow_dispatch The workflow file must exist on the default branch before it is visible in the UI; the command line --ref can specify a branch directly.
Case 1: automatically block changes during a freeze with a custom rule
Problem: A retail company freezes production changes for the two weeks before Black Friday. Previously this relied on group announcements, and some people still deployed during the freeze. Approach: An internal GitHub App subscribes to deployment_protection_rule events and queries the change calendar: during a freeze it returns rejected with an explanation; outside a freeze, if there is an approved change ticket, it returns approved. Limitation: This capability is still in public preview in the official docs; if the App goes down, jobs wait indefinitely, so monitoring and a timeout policy are needed.
Case 2: the reviewer approved the “wrong commit”
Problem: Two PRs were merged one after another on Friday afternoon, creating two prod runs awaiting approval. The reviewer approved only the earlier one, thinking the latest code had gone live. Approach: The prod job uses concurrency: { group: deploy-prod, cancel-in-progress: false } for serialization; the approval-note template requires checking the SHA; after deployment, display the SHA at the environment URL's /healthz or version endpoint. Takeaway: The approval applies to “that particular run”, not to “the latest state of main”.
Case 3: an org owner bypasses approval for a hotfix
Problem:“Allow administrators to bypass” was on by default, so an admin skipped approval late at night and deployed directly; no one reviewed it afterward. Approach: Turn off admin bypass for prod; set up a “break-glass” process for emergencies: temporarily add the on-call person as a reviewer, and leave a trace in the audit log.
Common errors and fixes
Branch "feature/x" is not allowed to deploy to prod due to environment protection rules.
Cause: The deployment branch policy does not match. Note that the pattern matches the short name of the GITHUB_REF ; tags need a separate type: tag policy.
gh api repos/$REPO/environments/prod/deployment-branch-policies --jq '.branch_policies[] | {name, type}'
Fix: Run from an allowed branch; when releasing with tags, add a v* tag policy.
Job shows “Waiting for review: prod needs approval to start deploying changes.”, but no one can approve
Cause: Prevent self-review is on and the only reviewer is the triggering user; people in the reviewer team lack repository read access; the reviewer is an outside collaborator but team settings are inconsistent.
gh api repos/$REPO/actions/runs/RUN_ID/pending_deployments --jq '.[] | {env: .environment.name, can_approve: .current_user_can_approve, reviewers: [.reviewers[].reviewer.login // .reviewers[].reviewer.slug]}'
Fix: Add another reviewer or team; for personal experiments, turn off prevent self-review. Jobs waiting for approval eventually time out and fail (per the official docs, currently 30 days).
The environment is referenced, but secrets.AZURE_CLIENT_ID is empty, and azure/login reports an input error like “client-id … is required”
Cause: The environment name is spelled inconsistently (Prod vs prod ) is treated as a new environment and created automatically, with no secret; or the secret was created at the repository level or in another environment.
gh api repos/$REPO/environments --jq '.environments[].name' gh secret list --env prod -R $REPO
Fix: Unify the environment name and delete the accidentally created environment.
Settings → Environments of a private repository does not show “Required reviewers”
Cause: Plan limit: private repositories on Free/Pro/Team do not support required reviewers or wait timers.
Fix: For experiments, use a public repository or GitHub Enterprise Cloud; alternatively, move the approval gate to a ruleset that requires review for merges into the release branch.
1. Use gh to approve a waiting prod deployment in a given run (RUN_ID is known).
ENV_ID=$(gh api repos/$REPO/environments/prod --jq .id) gh api -X POST repos/$REPO/actions/runs/$RUN_ID/pending_deployments \ -F "environment_ids[]=$ENV_ID" -f state=approved -f comment="SHA verified, approved for release"
2. Add a policy to prod that allows deployment from v* tags.
gh api -X POST repos/$REPO/environments/prod/deployment-branch-policies -f name='v*' -f type=tag
The security team requires: “No one may obtain prod's Azure write permission without approval, including repository admins and anyone who can modify the workflow file.” Provide the complete configuration on both the GitHub and Azure sides.
Azure side: id-myapp-prod has only one FIC, with subject …:environment:prod, and its role covers only myapp-prod. GitHub side: the prod environment sets deployment branches to “only main”, required reviewers (a team, with prevent self-review on),disable admin bypass; main is protected by a ruleset (required PR review + required checks + block force pushes), so modifying the workflow must also pass review before it can reach main; prod's client-id goes in an environment-level secret. No other branch or unapproved run can obtain an environment:prod token.
Verified instructional videos
Official docs
- Deployments and environments (rules, limits, plan availability)
- REST: Deployment environments · Deployment branch policies
- Creating custom deployment protection rules
Video storyboard (about 70 seconds)
Visual: a door labeled prod, with three gates in front of it.
Narration: Azure only recognizes environment colon prod. Whether you can reach this door is decided by GitHub's three gates.
Visual: a feature-branch job is bounced back at the first “branch policy” gate; a main job, after passing it, lights up “waiting for approval” at the second gate.
Narration: the branch policy first filters out deployments from the wrong sources; required reviewers decide whether this run may get production credentials.
Visual: after approval, the environment secret vault opens, and the key is handed to the runner.
Narration: before approval the job does not start at all, so it cannot read environment-level secrets either.
Visual: the admin's “bypass” button gets a seal placed over it.
Narration: turn off admin bypass for production so everyone takes the same path.
Module 4 · Deploying to Azure Container Apps
- Write the three-job build → deploy-dev → deploy-prod pipeline
deploy.yml: OIDC login,az acr loginimage push, job output digest and environment-level secrets. - Understand Container Apps revisions: scope of changes to revisions vs. application-scope changes, Single / Multiple / Labels (preview) revision modes, and revision suffix rules.
- Use
az containerapp ingress traffic setto achieve 0% pre-release → smoke test → traffic switch, and on failure useif: failure()to roll back automatically.
What: a revision is ACA's deployment unit
A revision is an immutable snapshot of one version of the container app. For properties.template changes (image, container config, environment variables, scaling rules, revision suffix) belong to revision-scope changes, which create a new revision. For properties.configuration changes (secrets values, revision mode, ingress and traffic rules, labels, private registry credentials, Dapr) belong to application-scope changes, which apply to all revisions and do not create a new revision (Microsoft Learn “Update and deploy changes”).
| Revision mode | Behavior | Suitable for |
|---|---|---|
| Single (default) | The new revision is provisioned and scaled to the same replica count as the old one; traffic switches from the old to the new revision only after all replicas pass startup and readiness probes; on failure, traffic stays on the old revision, which is then automatically deactivated | dev, simple services; inherently zero-downtime |
| Multiple | Multiple revisions can be active at once, with traffic split by percentage; you decide when to deactivate old revisions | prod canary, blue-green, A/B |
| Deployment labels (preview) | Give revisions names such as dev / staging / prod, and switch traffic and roll back by label | Follow the official docs; this course does not use it |
Revision suffix: may contain only lowercase letters, digits and -, must start with a letter, end with a letter or digit, and cannot have --, the full revision name is <app>--<suffix>. This course uses r<run number>-<retry count>-<first 7 characters of SHA>, for example myapp-prod--r42-1-a1b2c3d: traceable to the commit while avoiding name clashes on re-runs. By default, up to 100 inactive revisions are kept.
Why: why prod needs the multiple-revision mode
Single mode only guarantees “the new revision receives traffic only after passing probes”, but probes only check whether the process responds,and it does not check whether the business logic is correct. In multiple-revision mode, we can run the new revision first at 0% traffic, smoke test it through its own revision FQDN, and shift traffic only after confirmation; if something goes wrong, shift traffic back to the old revision, with users barely noticing.
How: three ways to have ACA swap images
| Method | Advantages | Notes |
|---|---|---|
az containerapp update --image (this course's main line) | Behavior is transparent and parameters match local debugging; updated with Azure CLI | Requires the containerapp extension; when only the image changes, other template fields remain unchanged |
azure/container-apps-deploy-action@v2 | Completes “build (ACR or the Oryx builder) + push + create or update the app” in one step; inputs such as acrName,containerAppName,resourceGroup,imageToDeploy,targetLabel | The latest version is still v2 from 2023-10,action.yml declares the node16 runtime (GitHub-hosted runners force a newer Node and show deprecation warnings); requires in advance azure/login |
| Update the image parameter in Bicep / Terraform | Same source of truth as the infrastructure code | Every deployment runs IaC, which takes time; suits teams that also bring the application version into IaC (Module 6) |
Image build: on the runner vs. ACR Tasks
- Build on runner (this course):
az acr loginUses the OIDC session to obtain an ACR refresh token and write it into the Docker config, thendocker/build-push-actionpush; the build identity only needs AcrPush on ACR (plus Reader, to conveniently read registry metadata). The GitHub Actions cache from the previous lesson can be used. - ACR Tasks (
az acr build): builds in Azure, no Docker needed on the runner; but it needs permission to run tasks (Microsoft.ContainerRegistry/registries/scheduleRun/action, which AcrPush does not include), and some subscription types may be restricted. Docker Hour 5 uses this approach.
Two identities: never mix them up
| Pipeline identity (id-myapp-build / dev / prod) | Runtime identity (the app's system-assigned identity) | |
|---|---|---|
| Who uses it | GitHub runner, via OIDC | Container Apps platform, when pulling images and at app runtime |
| What it does | Pushes images, updates apps, changes traffic | Pulls images from ACR (AcrPull), accesses Key Vault, etc. |
| Error symptoms | AADSTS*, AuthorizationFailed (in Actions logs) | Revision provisioning failures, image pull 401/403 (in ACA system logs) |
When: which release approach to use
- dev: Single mode + direct update + smoke test; on failure, just fix the code and redeploy.
- prod: Multiple mode + 0% pre-release + smoke test + one-time or staged traffic shift (e.g., 20% → 100%) + automatic rollback on failure.
- When testers need a long-lived “pre-release address”, use a label rather than a temporary revision FQDN.
latestRevisionName is the live version” is wrong: in multiple-revision mode, go by ingress.traffic . ③ “Using :latest also produces a new revision” is wrong: when the image string is unchanged, update it does not necessarily produce a new revision, and it cannot be traced; use SHA tags or digests. ④ “A 0%-traffic revision does not run” is wrong: it is an active revision and runs at the minimum replica count (0 in this course, woken on the first request).Pipeline diagram: the three jobs in deploy.yml
State diagram: prod revisions and traffic
Animation: 0% pre-release, traffic shifting and automatic rollback in multiple-revision mode
Decide whether the new version is “healthy”, then proceed step by step. The left side shows the revision list and traffic weights; the terminal below shows the commands run in the workflow and the results Azure returns.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az acr login --name ACR | Log in to ACR with the current Azure session (writes Docker credentials) | Requires Docker on the runner; if there is no Docker, you can add --expose-token |
az containerapp update -g RG -n APP --image IMG --revision-suffix S | Revision-scope change → new revision | --set-env-vars K=V Also revision-scope |
az containerapp revision list -g RG -n APP -o table | revisions, active state, traffic, health | --all Includes inactive revisions |
az containerapp revision show … --revision R --query properties.fqdn | Revision-specific FQDN | Used for 0%-traffic smoke tests |
az containerapp ingress traffic set -g RG -n APP --revision-weight A=100 B=0 | Set traffic split | can also be used latest=100; only meaningful in Multiple mode |
az containerapp revision deactivate / activate --revision R | Deactivate / reactivate revision | Deactivated revisions are not billed |
az containerapp revision label add --label L --revision R | Add a label to a revision | The label URL is fixed and can be moved between revisions |
az containerapp logs show -g RG -n APP --type system --tail 30 | Platform system logs | Image pull and probe failures appear here |
source ~/gh-lab.env
az containerapp revision list -g $RG -n $APP_PROD \
--query "[].{rev:name, active:properties.active, traffic:properties.trafficWeight, health:properties.healthState, image:properties.template.containers[0].image}" -o table
Rev Active Traffic Health Image --------------------------- -------- --------- --------- ---------------------------------------------------- myapp-prod--r41-1-9f8e7d6 True 0 Healthy acrghlab….azurecr.io/myapp@sha256:4be1… myapp-prod--r42-1-a1b2c3d True 100 Healthy acrghlab….azurecr.io/myapp@sha256:77c0…
Lab 4: dev auto-deployment, prod approval + 0% pre-release + traffic shift (about 12 minutes)
source ~/gh-lab.env for APP in $APP_DEV $APP_PROD; do az containerapp ingress update -g $RG -n $APP --target-port $PORT -o none; done
name: deploy
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
concurrency: # only one deployment pipeline at a time; queue rather than cancel
group: deploy-main
cancel-in-progress: false
env:
RG: ${{ vars.RG }}
ACR: ${{ vars.ACR }}
jobs:
build:
runs-on: ubuntu-latest
permissions: { contents: read, id-token: write }
outputs:
image: ${{ steps.ref.outputs.image }}
steps:
- uses: actions/checkout@v7
- uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID_BUILD }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- run: az acr login --name "$ACR"
- uses: docker/setup-buildx-action@v4
- id: push
uses: docker/build-push-action@v7
with:
context: .
push: true
tags: ${{ vars.ACR }}.azurecr.io/myapp:${{ github.sha }}
cache-from: type=gha
cache-to: type=gha,mode=max
- id: ref
run: echo "image=$ACR.azurecr.io/myapp@${{ steps.push.outputs.digest }}" >> "$GITHUB_OUTPUT"
deploy-dev:
needs: build
runs-on: ubuntu-latest
permissions: { contents: read, id-token: write }
environment:
name: dev
url: ${{ steps.up.outputs.url }}
env:
APP: ${{ vars.APP }}
IMAGE: ${{ needs.build.outputs.image }}
steps:
- uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }} # dev environment-level secret → id-myapp-dev
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- id: up
run: |
az extension add --name containerapp --upgrade --only-show-errors
SUFFIX="r${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ATTEMPT}-${GITHUB_SHA::7}"
az containerapp update -g "$RG" -n "$APP" --image "$IMAGE" \
--set-env-vars APP_VERSION="$GITHUB_SHA" --revision-suffix "$SUFFIX" -o none
echo "url=https://$(az containerapp show -g "$RG" -n "$APP" --query properties.configuration.ingress.fqdn -o tsv)" >> "$GITHUB_OUTPUT"
- name: Smoke test
run: |
curl --fail --silent --show-error --retry 12 --retry-delay 5 --retry-all-errors "${{ steps.up.outputs.url }}/healthz"
LIVE=$(az containerapp show -g "$RG" -n "$APP" --query "properties.template.containers[0].image" -o tsv)
test "$LIVE" = "$IMAGE" || { echo "::error::live image $LIVE != $IMAGE"; exit 1; }
deploy-prod:
needs: [build, deploy-dev]
runs-on: ubuntu-latest
permissions: { contents: read, id-token: write }
environment:
name: prod
url: ${{ steps.stage.outputs.url }}
env:
APP: ${{ vars.APP }}
IMAGE: ${{ needs.build.outputs.image }}
steps:
- uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }} # prod environment-level secret → id-myapp-prod
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- id: stage
name: Stage new revision at 0%
run: |
az extension add --name containerapp --upgrade --only-show-errors
OLD=$(az containerapp revision list -g "$RG" -n "$APP" --query "[?properties.trafficWeight > \`0\`] | [0].name" -o tsv)
[ -z "$OLD" ] && OLD=$(az containerapp show -g "$RG" -n "$APP" --query properties.latestReadyRevisionName -o tsv)
az containerapp ingress traffic set -g "$RG" -n "$APP" --revision-weight "$OLD=100" -o none
SUFFIX="r${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ATTEMPT}-${GITHUB_SHA::7}"
NEW="$APP--$SUFFIX"
echo "old=$OLD" >> "$GITHUB_OUTPUT"; echo "new=$NEW" >> "$GITHUB_OUTPUT"
az containerapp update -g "$RG" -n "$APP" --image "$IMAGE" \
--set-env-vars APP_VERSION="$GITHUB_SHA" --revision-suffix "$SUFFIX" -o none
for i in $(seq 1 30); do
S=$(az containerapp revision show -g "$RG" -n "$APP" --revision "$NEW" --query properties.provisioningState -o tsv)
[ "$S" = "Provisioned" ] && break; [ "$S" = "Failed" ] && { echo "::error::revision $NEW failed"; exit 1; }
sleep 10
done
echo "revfqdn=$(az containerapp revision show -g "$RG" -n "$APP" --revision "$NEW" --query properties.fqdn -o tsv)" >> "$GITHUB_OUTPUT"
echo "url=https://$(az containerapp show -g "$RG" -n "$APP" --query properties.configuration.ingress.fqdn -o tsv)" >> "$GITHUB_OUTPUT"
- name: Smoke test new revision (0% traffic)
run: curl --fail --silent --show-error --retry 12 --retry-delay 5 --retry-all-errors "https://${{ steps.stage.outputs.revfqdn }}/healthz"
- name: Shift traffic
run: |
az containerapp ingress traffic set -g "$RG" -n "$APP" \
--revision-weight "${{ steps.stage.outputs.old }}=0" "${{ steps.stage.outputs.new }}=100" -o none
sleep 20
curl --fail --silent --show-error --retry 6 --retry-delay 5 "${{ steps.stage.outputs.url }}/healthz"
- name: Roll back on failure
if: failure() && steps.stage.outputs.new != ''
run: |
echo "::warning::rolling back to ${{ steps.stage.outputs.old }}"
az containerapp ingress traffic set -g "$RG" -n "$APP" \
--revision-weight "${{ steps.stage.outputs.old }}=100" "${{ steps.stage.outputs.new }}=0" -o none || true
az containerapp revision deactivate -g "$RG" -n "$APP" --revision "${{ steps.stage.outputs.new }}" -o none || true
Key points:① Numeric literals in JMESPath need backticks; in YAML, the run: | value is written as \`0\`. ② The if: failure() 's rollback step runs when any smoke-test or traffic-switch step fails; it is skipped if new is empty. ③ On the first run, the “old revision” is the sample image's revision; since the port has changed to 5000, it is actually unhealthy and only recovers after the first prod deployment shifts traffic. This is a one-time issue.
cd ~/myapp && git switch -c ci/deploy $EDITOR .github/workflows/deploy.yml git add .github/workflows/deploy.yml && git commit -m "ci: deploy to Azure Container Apps via OIDC" git push -u origin HEAD && gh pr create --fill && gh pr checks --watch && gh pr merge --squash --delete-branch
sleep 10; RUN=$(gh run list -w deploy.yml -L 1 --json databaseId -q '.[0].databaseId')
gh run view $RUN
gh api repos/$REPO/actions/runs/$RUN/pending_deployments --jq '.[] | {env: .environment.name, can_approve: .current_user_can_approve}'
✓ main deploy · 1234567890
✓ build in 1m12s
✓ deploy-dev in 58s
* deploy-prod (waiting)
{"env":"prod","can_approve":true}ENV_ID=$(gh api repos/$REPO/environments/prod --jq .id)
gh api -X POST repos/$REPO/actions/runs/$RUN/pending_deployments -F "environment_ids[]=$ENV_ID" -f state=approved -f comment="lab approve" >/dev/null
gh run watch $RUN --exit-status
az containerapp revision list -g $RG -n $APP_PROD --query "[].{rev:name, traffic:properties.trafficWeight, active:properties.active}" -o tableok; the repository home page's right side “Deployments” shows dev and prod; prod's live image is exactly the digest output by the build job.
for APP in $APP_DEV $APP_PROD; do curl -s https://$(az containerapp show -g $RG -n $APP --query properties.configuration.ingress.fqdn -o tsv)/healthz; echo " ← $APP"; done
ok ← myapp-dev ok ← myapp-prod
Case 1: all probes green but the business completely down
Problem: The new version renamed the database connection-string environment variable,/healthz only checked process liveness, Single mode shifted traffic as usual, and the order API returned errors 100% of the time for 12 minutes. Approach: prod switched to multiple revisions + 0% pre-release; the smoke test added a read-only business endpoint (for example /api/catalog?limit=1); after traffic shifts, query the failure rate in Application Insights within 2 minutes; if it exceeds the threshold, fail and trigger the rollback step. Limitation: Write-operation endpoints are not suitable for smoke tests; prepare a test tenant or read-only probing.
Case 2: still erroring after rollback
Problem: The release rotated the Redis secret in Key Vault and also updated the container app secret (application-scope); after the new version errored and traffic was switched back to the old revision, the old revision also read the new secret. Takeaway: Split “configuration changes” and “code releases” into two separate changes; when a secret references a versioned Key Vault URI, define the rollback policy explicitly. (Docker Hour 5, troubleshooting scenario 5, has a similar analysis.)
Case 3: concurrent merges let revisions “cut in line”
Problem: Two PRs were merged one minute apart; the two runs' deploy-dev jobs executed concurrently; the image built later deployed first and was then overwritten by the earlier-built image, so dev ran the old code. Approach: Workflow-level concurrency: deploy-main,cancel-in-progress: false queue runs; or for dev, use cancel-in-progress: true (keeping only the latest), and prod never cancels an in-progress deployment.
Common errors and fixes
ERROR: denied: requested access to the resource is denied / unauthorized: authentication required (during docker push)
Cause: The build identity lacks AcrPush, or the role was just assigned and has not taken effect yet, or az acr login was not run, or logged in to a different registry.
az role assignment list --assignee $(az identity show -g $RG -n id-myapp-build --query principalId -o tsv) --all -o table
Fix: Grant AcrPush at the ACR scope, wait a few minutes, and re-run.
Revision provisioning failed: … unable to pull image … 401 Unauthorized (ACA system logs)
Cause: Runtime identity problem: the app is not configured to access the registry with a managed identity, or the system identity lacks AcrPull. It is not a pipeline identity problem.
az containerapp show -g $RG -n $APP_DEV --query "{registries:properties.configuration.registries, identity:identity.type}"
az containerapp logs show -g $RG -n $APP_DEV --type system --tail 30
Fix: Per Module 0 step 4, assign AcrPull to the app and az containerapp registry set --identity system. See Module 7 for details.
(ContainerAppInvalidRevisionSuffix) / The revision suffix … is invalid, or revision with name … already exists
Cause: The suffix contains uppercase letters or starts with a digit, or contains --; or re-running the same run causes a name clash.
Fix: Use a suffix like r${GITHUB_RUN_NUMBER}-${GITHUB_RUN_ATTEMPT}-${GITHUB_SHA::7} that starts with a letter and includes the retry count.
(LinkedAuthorizationFailed) The client … has permission to perform action 'Microsoft.App/containerApps/write' … however, it does not have permission to perform action 'Microsoft.App/managedEnvironments/join/action' on the linked scope(s)
Cause: The deployment identity only has Contributor at the app scope, and when updating the app, ARM also checks its association permission on the referenced Container Apps environment.
Fix: Grant at the environment scope a role that includes managedEnvironments/join/action (the custom role “ACA Environment Joiner” from Module 2).
Smoke test curl: (6) Could not resolve host, or a long-lasting 404 (0% traffic revision)
Cause: The revision has not finished provisioning; the revision FQDN was taken wrongly (the app FQDN or an empty value was used); or the app is in Single mode (which does not provide revision-level traffic).
Fix: Confirm prod is in Multiple mode; wait for provisioningState=Provisioned before fetching properties.fqdn; in curl, use --retry-all-errors to handle cold starts.
1. Manually split myapp-prod's traffic: 20% to revision B and 80% kept on revision A.
az containerapp ingress traffic set -g rg-gh-lab -n myapp-prod --revision-weight A_NAME=80 B_NAME=20
2. Manual rollback: find the previous revision that is currently at 0% but still active, and switch all traffic back to it.
PREV=$(az containerapp revision list -g rg-gh-lab -n myapp-prod --query "[?properties.active && properties.trafficWeight==\`0\`] | sort_by(@, &properties.createdTime) | [-1].name" -o tsv) CUR=$(az containerapp revision list -g rg-gh-lab -n myapp-prod --query "[?properties.trafficWeight==\`100\`].name | [0]" -o tsv) az containerapp ingress traffic set -g rg-gh-lab -n myapp-prod --revision-weight "$PREV=100" "$CUR=0"
While the prod job is waiting, an approver merged a new PR. There are now two runs: #41 awaiting approval, and #42 whose build is queued. Explain what will happen, and how you would configure the behavior you want.
With workflow-level concurrency: deploy-main and cancel-in-progress: false set, #41 holds the concurrency group (waiting for approval also counts as in progress), so #42 waits; the group keeps only one “pending” run, and a newer pending run replaces an older one. After #41 is approved it goes live, and then #42 starts its build. If you always want the latest version live, you can reject #41, or give the prod job its own job-level concurrency group and weigh a cancellation policy; but do not let an in-progress prod job that is performing a traffic switch get cancelled.
Verified instructional videos
Official docs
- Update and deploy changes in Azure Container Apps (revisions, modes, scope)
- Traffic splitting · Blue-green deployment
- Deploy to Azure Container Apps with GitHub Actions · Azure/container-apps-deploy-action
Video storyboard (about 80 seconds)
Visual: the build job spits out a container with a sha256 fingerprint, which moves along the conveyor belt into dev, then prod.
Narration: build once, promote by digest. dev and prod run the same container.
Visual: in prod, the old revision holds the 100% traffic bar, and the new revision appears at 0%; a test robot knocks on its door separately.
Narration: in multiple-revision mode, the new revision goes live with zero traffic first and is smoke tested at its own address.
Visual: the traffic bar slides from the old revision to the new one.
Narration: the smoke test passes, and one command switches traffic. Traffic rules are application-scope settings and take effect immediately.
Visual: the new revision turns red, the traffic bar snaps back to the old revision, and the new revision turns grey.
Narration: if any step fails, the rollback step switches traffic back to the old revision and deactivates the new one; users barely notice.
Module 5 · Deploying to AKS and App Service
- Write deployment jobs for AKS clusters with Microsoft Entra integration, Azure RBAC for Kubernetes, and local accounts disabled:
azure/login→azure/use-kubelogin→azure/aks-set-context→azure/k8s-deploy, and give the minimal namespace-level role. - Understand the
azure/k8s-deploy@v7basic / canary / blue-green strategies and promote / reject actions. - Master App Service deployment slots: which tiers are available, the six swap steps, which settings move with the swap, swap with preview, percentage routing and rollback.
AKS: What / Why / How
What: Push-style deployment to AKS passes two authorization gates: ① Azure RBAC (ARM) — whether you can obtain the cluster user credentials (listClusterUserCredential); ② Kubernetes authorization— whether each request to the API server can create a Deployment in a given namespace. When “Azure RBAC for Kubernetes Authorization” is enabled, gate ② is also expressed with Azure role assignments.
Why kubelogin: A cluster with Entra integration issues a kubeconfig that contains no static token; instead, the client must authenticate with an Entra token. kubelogin is a kubectl exec credential plugin; in CI it can directly reuse the azure/login session established by Azure CLI to obtain tokens. azure/aks-set-context@v5 's use-kubelogin: true action converts the kubeconfig to use kubelogin (conversion mode per the action docs), provided you first use azure/use-kubelogin@v1 to install it.
| Action (verified 2026-11) | Version | Purpose / key inputs |
|---|---|---|
azure/use-kubelogin | v1.3 (node24) | Install kubelogin: kubelogin-version,skip-cache |
azure/setup-kubectl | v5.2.0 | installs a pinned kubectl version (hosted runners already include it; use when you need a fixed version) |
azure/aks-set-context | v5.0.1 (node24) | resource-group,cluster-name,admin (default false),use-kubelogin,public-fqdn,subscription |
azure/k8s-deploy | v7.0.1 (2026-08, node24) | namespace,manifests,images (replaces the image in the manifest),strategy (basic / canary / blue-green, default basic),action (deploy / promote / reject),traffic-split-method (pod / smi),percentage,route-method |
azure/k8s-bake | v4.1.1 | renders Helm / Kustomize / Kompose into manifests, then hands them to k8s-deploy |
Least privilege (Azure RBAC for Kubernetes)
| Role | Scope | Purpose |
|---|---|---|
| Azure Kubernetes Service Cluster User Role | Cluster resource | Get the user kubeconfig (no Kubernetes permissions included) |
| Azure Kubernetes Service RBAC Writer | <cluster resource ID>/namespaces/myapp | Read and write workloads only in the myapp namespace (cannot change RBAC, cannot read other namespaces) |
If the cluster uses Entra integration plus Kubernetes native RBAC (Azure RBAC not enabled), gate ② requires creating a RoleBinding in the cluster whose subject is the managed identity's object ID. Do not use admin: true to get cluster admin credentials — with local accounts disabled (--disable-local-accounts) it would not work anyway.
App Service: deployment slots
What: A deployment slot is a “live app” with its own hostname within the same App Service app (such as myweb-staging.azurewebsites.net). Requires Standard, Premium or Isolated tier ; Standard allows up to 5 slots, and the slots themselves are not charged extra (they share the plan's compute).
How: the swap steps (Microsoft Learn): ① apply the slot-specific settings of the target slot (production) to all instances of the source slot and restart them (swap with preview pauses here); ② wait for all instances to finish restarting; if any instance fails, roll back and stop; ③ if local cache is enabled, initialize it; ④ warm-up: request the app root path (or applicationInitialization,WEBSITE_SWAP_WARMUP_PING_PATH), any HTTP response counts as warm-up complete (you can use WEBSITE_SWAP_WARMUP_PING_STATUSES to restrict status codes); ⑤ switch the routing rules of the two slots; ⑥ do the same for the original production instances (now in staging). Throughout, the production slot stays online.
| Moves with the swap (follows the code) | Does not move with the swap (stays on the slot) |
|---|---|
| Language/framework version, 32/64-bit, WebSockets, app settings and connection strings (unless marked as deployment slot settings), handler mappings, public certificates, WebJobs content, Hybrid Connections, service endpoints, path mappings | Custom domains, non-public certificates and TLS settings, publishing endpoints, scale settings, WebJobs schedule, IP restrictions, Always On, diagnostic logs, CORS,managed identities,_EXTENSION_VERSION settings ending with the suffix, VNet integration |
Note: Managed identities do not move with the swap, so the staging slot needs its own identity and its own AcrPull / Key Vault permissions. Auto swap is not supported for Linux and Web App for Containers.
GitHub side
azure/webapps-deploy@v3(v3.0.8, node24): inputsapp-name,slot-name,package(code package) orimages(container),resource-group-nameetc. Used withazure/login's OIDC session,do not use againpublish-profile(it is a long-lived credential, with the same problem as a client secret).- For the swap, use
az webapp deployment slot swap --slot staging --target-slot production, which can be placed in another environment job protected by approval: deploy to staging automatically; swapping to production requires approval. - Pipeline identity role: the Website Contributor role scoped to the site (including slots).
When: comparison table
| ACA (Module 4) | AKS | App Service | |
|---|---|---|---|
| Pre-release method | 0% traffic revision | canary / blue-green variants (k8s-deploy), or mesh weights | staging slot |
| switch | ingress traffic set | action: promote / modify the Service selector | slot swap |
| Rollback | switch traffic back to the old revision | action: reject,kubectl rollout undo, GitOps revert | swap again |
| Permissions the pipeline needs | Contributor on the app + environment join | Cluster User + namespace RBAC Writer | Website Contributor |
k8s-deploy 's canary can split exactly 10% of traffic” is wrong: without a service mesh (traffic-split-method: pod) it only approximates the split by replica count.AKS: two authorization gates
App Service: routing before and after the swap
Animation: the six steps of an App Service slot swap
Switch between “swap with preview” and “warm-up failure” to see the difference. Each step shows the state of the production and staging slots, where user traffic goes, and az the corresponding information in the command output or activity log.
AKS commands
| Command | Purpose |
|---|---|
az aks show -g RG -n AKS --query "{aad:aadProfile.managed, azureRbac:aadProfile.enableAzureRbac, localDisabled:disableLocalAccounts}" | Confirm the authentication/authorization mode |
az role assignment create --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp … | Namespace-level write permission |
kubectl auth can-i create deployments -n myapp | Self-check permissions in the pipeline |
kubelogin convert-kubeconfig -l azurecli | Manually convert kubeconfig to reuse the Azure CLI session |
App Service commands
| Command | Purpose |
|---|---|
az webapp deployment slot create -g RG -n WEB --slot staging | Create a slot (no content) |
az webapp config appsettings set … --slot staging --slot-settings KEY=VALUE | Set slot-specific app settings (not swapped) |
az webapp deployment slot swap -g RG -n WEB --slot staging --target-slot production | Swap (can add --action preview|swap|reset) |
az webapp traffic-routing set -g RG -n WEB --distribution staging=15 | Route 15% of production traffic to staging (session pinned via x-ms-routing-name cookie) |
az monitor activity-log list -g RG --query "[?contains(operationName.value,'slotsswap')]" | View swap operation records |
# Preview which settings will change before swapping (the portal's Swap dialog also shows this) az webapp deployment slot swap -g $RG -n $WEB --slot staging --target-slot production --action preview # After verifying that staging works under production settings: az webapp deployment slot swap -g $RG -n $WEB --slot staging --target-slot production --action swap # If problems are found, cancel (after phase one): az webapp deployment slot swap -g $RG -n $WEB --slot staging --target-slot production --action reset
Lab 5 (optional, incurs costs): AKS and App Service deployment jobs
aks-gh-lab namespace myapp, and for the new identity id-myapp-aks create a environment:aks-prod FIC.
source ~/gh-lab.env AKS_ID=$(az aks show -g $RG -n aks-gh-lab --query id -o tsv) az identity create -g $RG -n id-myapp-aks -o none P=$(az identity show -g $RG -n id-myapp-aks --query principalId -o tsv) az role assignment create --assignee-object-id $P --assignee-principal-type ServicePrincipal --role "Azure Kubernetes Service Cluster User Role" --scope $AKS_ID -o none az role assignment create --assignee-object-id $P --assignee-principal-type ServicePrincipal --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp -o none az identity federated-credential create -g $RG --identity-name id-myapp-aks --name gh-env-aks-prod \ --issuer https://token.actions.githubusercontent.com --audiences api://AzureADTokenExchange --subject "$PREFIX:environment:aks-prod"
deploy-aks:
needs: build
runs-on: ubuntu-latest
environment: aks-prod
permissions: { contents: read, id-token: write }
steps:
- uses: actions/checkout@v7 # needs the manifests in the k8s/ directory
- uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- uses: azure/use-kubelogin@v1
with:
kubelogin-version: 'latest' # pin a specific version in production
- uses: azure/aks-set-context@v5
with:
resource-group: ${{ vars.RG }}
cluster-name: aks-gh-lab
admin: 'false'
use-kubelogin: 'true'
- run: kubectl auth can-i create deployments -n myapp
- uses: azure/k8s-deploy@v7
with:
namespace: myapp
manifests: |
k8s/deployment.yaml
k8s/service.yaml
images: ${{ needs.build.outputs.image }}
strategy: basic
AKS nodes pull images from ACR using the kubelet identity (az aks update --attach-acr), which is unrelated to the pipeline identity — yet another instance of “pipeline identity vs. runtime identity”.
source ~/gh-lab.env
WEB=web-myapp-$RANDOM; echo "WEB=$WEB" >> ~/gh-lab.env
az appservice plan create -g $RG -n plan-gh-lab --is-linux --sku S1 -o none
az webapp create -g $RG -p plan-gh-lab -n $WEB --deployment-container-image-name mcr.microsoft.com/k8se/quickstart:latest -o none
az webapp deployment slot create -g $RG -n $WEB --slot staging -o none
for S in "" "--slot staging"; do # each slot needs its own identity (managed identities do not move with the swap)
PID=$(az webapp identity assign -g $RG -n $WEB $S --query principalId -o tsv)
az role assignment create --assignee-object-id $PID --assignee-principal-type ServicePrincipal --role AcrPull --scope $(az acr show -n $ACR --query id -o tsv) -o none
az webapp config set -g $RG -n $WEB $S --generic-configurations '{"acrUseManagedIdentityCreds": true}' -o none
az webapp config appsettings set -g $RG -n $WEB $S --settings WEBSITES_PORT=$PORT WEBSITE_SWAP_WARMUP_PING_PATH=/healthz WEBSITE_SWAP_WARMUP_PING_STATUSES=200 -o none
done
web-staging: # automatic: deploy to the staging slot
needs: build
runs-on: ubuntu-latest
environment: web-staging
permissions: { contents: read, id-token: write }
steps:
- uses: azure/login@v3
with: { client-id: '${{ secrets.AZURE_CLIENT_ID }}', tenant-id: '${{ secrets.AZURE_TENANT_ID }}', subscription-id: '${{ secrets.AZURE_SUBSCRIPTION_ID }}' }
- uses: azure/webapps-deploy@v3
with:
app-name: ${{ vars.WEB }}
slot-name: staging
images: ${{ needs.build.outputs.image }}
- run: curl --fail --retry 12 --retry-delay 5 --retry-all-errors "https://${{ vars.WEB }}-staging.azurewebsites.net/healthz"
web-swap: # requires approval: swap to production
needs: web-staging
runs-on: ubuntu-latest
environment: web-prod
permissions: { contents: read, id-token: write }
steps:
- uses: azure/login@v3
with: { client-id: '${{ secrets.AZURE_CLIENT_ID }}', tenant-id: '${{ secrets.AZURE_TENANT_ID }}', subscription-id: '${{ secrets.AZURE_SUBSCRIPTION_ID }}' }
- run: az webapp deployment slot swap -g ${{ vars.RG }} -n ${{ vars.WEB }} --slot staging --target-slot production
Each of the two environments needs one identity (or the same identity with two FICs), and Website Contributor must be granted on the site. The combined length of the slot name and hostname is limited (site name ≤ 40, slot name ≤ 19 characters).
source ~/gh-lab.env az webapp delete -g $RG -n $WEB 2>/dev/null; az appservice plan delete -g $RG -n plan-gh-lab --yes 2>/dev/null az identity delete -g $RG -n id-myapp-aks 2>/dev/null # If you created the lab AKS: az aks delete -g $RG -n aks-gh-lab --yes --no-wait
Case 1: moving from admin kubeconfig to kubelogin + namespace RBAC
Problem: The pipeline has been using az aks get-credentials --admin, so every app repository was effectively a cluster admin. After the security baseline required disabling local accounts, all deployments failed. Approach: One deployment identity per app repository; Cluster User Role + RBAC Writer on each namespace; add use-kubelogin to the workflow; the platform team keeps cluster-level permissions. Limitation: Apps that need to create CRDs or cluster-level resources (such as Operators) should instead be deployed by a platform pipeline or GitOps.
Case 2: after the swap, production connected to the test database
Problem: The staging slot's database connection string was not marked as a “deployment slot setting”, so after the swap it followed the code into production. Approach: Mark all environment-related settings (connection strings, external API addresses) as slot-specific using --slot-settings ; check during phase one with swap with preview. Takeaway: A swap moves “code + non-slot-specific settings”.
Case 3: auto swap failed for a Linux app
Problem: The team copied the Windows app's auto swap configuration to a Linux container app, but it had no effect. Cause: Auto swap is not supported for Linux and Web App for Containers. Fix: Run the swap explicitly from a GitHub workflow (as in this page's snippets), and place it in an environment that requires approval.
Common errors and fixes
Error from server (Forbidden): deployments.apps is forbidden: User "…" cannot create resource "deployments" in API group "apps" in the namespace "myapp": User does not have access to the resource in Azure. Update role assignment to allow access.
Cause: Gate ② authorization failed: the namespace-level Azure RBAC role is missing, or the scope was written for a different namespace, or the role was just assigned and has not taken effect yet (this may take several minutes).
az role assignment list --assignee $P --all --query "[].{role:roleDefinitionName, scope:scope}" -o table
Fix: Grant RBAC Writer at $AKS_ID/namespaces/myapp .
kubelogin is not installed / exec: executable kubelogin not found
Cause: The kubeconfig has been converted to the exec plugin, but kubelogin is not installed on the runner.
Fix: Add aks-set-context before azure/use-kubelogin@v1.
(BadRequest) Getting static credential is not allowed because this cluster is set to disable local accounts.
Cause:admin: true or az aks get-credentials --admin was used, but the cluster has local accounts disabled.
Fix: Use user credentials + kubelogin; do not request admin credentials.
Cannot swap site slots … because the warm-up request failed / swap has no response for a long time
Cause: The warm-up path returned a status code not in WEBSITE_SWAP_WARMUP_PING_STATUSES , or the app startup timed out (each request waits 90 seconds, with up to 5 retries); a URL rewrite rule intercepted the internal warm-up request.
az monitor activity-log list -g $RG --query "[?contains(operationName.value,'slotsswap')].{status:status.value, time:eventTimestamp}" -o table
Fix: First make sure the staging slot itself is healthy; correct the warm-up path; if necessary, troubleshoot step by step with swap with preview.
The slot cannot be changed because its configuration settings have been prepared for swap.
Cause: Phase one of swap with preview has completed but was neither completed nor cancelled.
Fix:--action swap Complete it, or run --action reset to cancel it.
1. Route 30% of production traffic to the staging slot, then restore it to 0.
az webapp traffic-routing set -g $RG -n $WEB --distribution staging=30 az webapp traffic-routing clear -g $RG -n $WEB
2. In the pipeline, verify that the current identity can create a Deployment in the myapp namespace, and fail early if it cannot.
kubectl auth can-i create deployments -n myapp || { echo "::error::missing RBAC in namespace myapp"; exit 1; }The platform team maintains a multi-tenant AKS cluster, with 20 app teams each having a GitHub repository. The security team requires that app teams must not affect each other and that no repository holds cluster admin credentials. Compare the push-style and GitOps approaches.
Push-style: one UAMI per repository, with the FIC trusting only its prod environment; Cluster User Role + RBAC Writer in its own namespace; local accounts disabled on the cluster; the workflow uses kubelogin. The advantage is simplicity and directness; the drawback is that all 20 identities can reach the cluster API directly, which requires network reachability (a private cluster needs a self-hosted runner or az aks command invoke). GitOps: in-cluster Flux reconciles each team's manifests under a single identity (tenant-isolated Kustomizations and service accounts); app repositories only build images and open PRs against the manifest repository. The advantage is that the cluster API is not exposed to GitHub and auditing is native; the drawback is that deployment results must be reported back. A multi-tenant platform leans toward GitOps.
Verified instructional videos
Official docs
- AKS: kubelogin authentication · Azure RBAC for Kubernetes Authorization
- Azure/k8s-deploy · Azure/aks-set-context · Azure/use-kubelogin
- App Service: Set up staging environments (deployment slots) · Azure/webapps-deploy
Video storyboard (about 75 seconds)
Visual: the runner carries an Azure token to the AKS gate; first it collects a kubeconfig at the ARM window, then at the API server door its “namespace pass” is checked.
Narration: deploying to AKS passes two authorization gates: first get the cluster credentials, then pass Kubernetes authorization.
Visual: a kubelogin plugin is attached to the kubeconfig; the plugin takes the token from the az session.
Narration: a cluster with Entra integration has no static token; kubelogin reuses the azure/login session to obtain a token.
Visual: the App Service staging slot lights up as it warms up; flip the routing switch, and the user arrows turn to the new version.
Narration: the deployment slot warms up in staging first, then the routing rules are swapped, and production stays online throughout.
Visual: the managed identity and custom domain icons stay pinned to the original slot.
Narration: remember, managed identities, custom domains and slot-specific settings do not move with the swap.
Module 6 · Infrastructure-as-code pipelines (Bicep / Terraform)
- Design a two-stage IaC pipeline of “PR preview / apply after approval”, and configure read-only and write identities separately for the two stages (
pull_requestsubject vsenvironmentsubject). - Use
az deployment group what-if(--validation-level ProviderNoRbac) under read-only permissions to generate a Bicep change preview and publish it as a PR comment. - Understand Bicep what-if and Terraform saved plans (
plan -out), and their essential differences, and how they affect the principle that “what is approved is what is executed”.
What: the two stages of an IaC pipeline
| Stage | Trigger | OIDC subject / identity | Output |
|---|---|---|---|
| Preview (plan / what-if) | pull_request | …:pull_request → read-only identity (Reader + the minimum operations needed for preview) | PR comment: which resources will be created / modified / deleted |
| Apply (apply / deploy) | Merge to main (push) | …:environment:infra → write identity, scoped only to the resources it manages | Actual changes + deployment record |
Why: why put the preview in the PR
Reviewers find it hard to judge consequences from a Bicep/HCL diff (changing one parameter may cause a resource recreation). Posting the what-if / plan results on the PR means the review discusses “what will happen”. At the same time, the preview stage does not need write permissions, so even if the code in the PR is maliciously modified, it cannot change cloud resources.
How: differences between Bicep and Terraform
| Bicep / ARM | Terraform | |
|---|---|---|
| Preview command | az deployment group what-if; or azure/bicep-deploy@v2 's operation: whatIf | terraform plan -out=tfplan |
| can a “plan” be saved | No: what-if is a one-time prediction; at deployment time ARM recalculates it | Yes: a saved plan file can be executed as-is at apply time; if state has changed, it is rejected |
| State | No state; Azure itself is the source of truth; deployment stacks can manage the set of resources “I created” | Remote state (Azure Storage / HCP Terraform), which needs a lock |
| Permissions for a read-only preview | By default, Provider validation requires the same permissions as deployment; ProviderNoRbac only checks the read permissions on each resource (Azure CLI ≥ 2.76) | Read cloud resources + read/write state (plan also acquires the state lock, which needs Blob write/lease permission, or use -lock=false for a read-only preview) |
| Azure authentication | azure/login Session | azurerm: ARM_USE_OIDC=true + ARM_CLIENT_ID/ARM_TENANT_ID/ARM_SUBSCRIPTION_ID (Terraform Hour 5 explains in detail) |
About ProviderNoRbac: Microsoft Learn describes it as running the same full validation as the provider but checking only read permissions; the identity still needs Microsoft.Resources/deployments/whatIf/action and similar operations on the deployment itself. This course uses a custom role containing only deployments read / validate / what-if operations, plus Reader (this combination is based on a community example; check the official docs for the minimal operation set).
When: guarding the apply stage
- The apply job references a protected environment (such as
infra: only main + required reviewers). - Terraform: after the PR is merged, re-plan on main and save it as an artifact; after approval, apply the same plan file (do not re-plan in the apply job).
- Bicep: since no plan was saved, the apply job runs what-if again before deployment and compares it with the result seen at approval (for example, checking whether any Delete appears), and fails if they differ; or use the deployment stack's
deny-settingsto prevent out-of-band changes. - Use
concurrencyto ensure that only one apply job runs at a time for the same infrastructure.
id-token: write the token for writing comments; using pull_request_target to bypass it is a high-risk operation (covered in detail in Hour 5). ④ “Bicep incremental mode will delete resources outside the template” is wrong: incremental mode (the default) does not, only complete mode does; deployment stacks have their own action-on-unmanage settings.Sequence diagram: one infrastructure change
Animation: PR preview → approval → apply (including the “plan expired” scenario)
Choose the engine and scenario, then play step by step. The “out-of-band change” scenario simulates someone manually changing a resource in the portal after PR review, so you can observe how a saved Terraform plan and a re-run Bicep what-if react differently.
Core commands
| Command | Purpose | Notes |
|---|---|---|
az deployment group what-if -g RG -f main.bicep -p k=v --validation-level ProviderNoRbac --no-pretty-print | Read-only preview, outputs JSON | Without --no-pretty-print , output is colored text |
az deployment group what-if … --exclude-change-types NoChange Ignore | Filter out noise | Shorter comments |
az deployment group create -g RG -f main.bicep -p k=v --name gh-$GITHUB_RUN_ID | Deploy (incremental mode) | Use the run ID as the deployment name for easy tracing in the portal |
az bicep build -f main.bicep / az bicep lint | Compile and static checks | Put in CI; no cloud permissions needed |
gh pr comment N --body-file whatif.md --edit-last | Update the same comment | Falls back to creating a new one if there is no comment the first time |
terraform plan -out=tfplan / terraform show -no-color tfplan | Save and display the plan | See Terraform Hour 5 for details |
# Trial run locally with your own identity (verify the templates before the lab)
source ~/gh-lab.env
az deployment group what-if -g $RG -f infra/main.bicep -p acrName=$ACR --validation-level ProviderNoRbac \
--no-pretty-print | jq -r '.changes[] | "\(.changeType)\t\(.resourceId | split("/") | last)"'
Modify acrghlab1234512345
Lab 6: add a what-if PR comment for the ACR Bicep definition (about 8 minutes)
source ~/gh-lab.env
cat > /tmp/whatif-role.json <<EOF
{ "Name": "Deployment What-If Runner ($RG)",
"Description": "Run ARM/Bicep what-if with read-only resource access",
"Actions": ["Microsoft.Resources/deployments/read","Microsoft.Resources/deployments/validate/action","Microsoft.Resources/deployments/whatIf/action"],
"AssignableScopes": ["/subscriptions/$SUB_ID/resourceGroups/$RG"] }
EOF
az role definition create --role-definition @/tmp/whatif-role.json -o none
sleep 30
az role assignment create --assignee-object-id $(az identity show -g $RG -n id-myapp-plan --query principalId -o tsv) \
--assignee-principal-type ServicePrincipal --role "Deployment What-If Runner ($RG)" --scope $(az group show -n $RG --query id -o tsv) -o none@description('Existing ACR name')
param acrName string
param location string = resourceGroup().location
resource acr 'Microsoft.ContainerRegistry/registries@2023-07-01' = {
name: acrName
location: location
sku: { name: 'Basic' }
properties: { adminUserEnabled: false }
tags: {
course: 'github-8h'
part: '3'
owner: 'platform-team'
}
}name: infra-whatif
on:
pull_request:
paths: ['infra/**']
permissions:
contents: read
jobs:
whatif:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write # sub = …:pull_request → id-myapp-plan (read-only)
pull-requests: write # write PR comments
steps:
- uses: actions/checkout@v7
- uses: azure/login@v3
with:
client-id: ${{ secrets.AZURE_CLIENT_ID_PLAN }}
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
- name: What-if
run: |
az deployment group what-if -g "${{ vars.RG }}" -f infra/main.bicep -p acrName="${{ vars.ACR }}" \
--validation-level ProviderNoRbac --exclude-change-types NoChange Ignore --no-pretty-print > whatif.json
{
echo "### Bicep what-if (read-only identity, $(date -u +%FT%TZ))"
echo '| Change | Resource |'; echo '|---|---|'
jq -r '.changes[] | "| \(.changeType) | `\(.resourceId | split("/") | last)` |"' whatif.json
echo; echo "Commit: ${{ github.event.pull_request.head.sha }}"
} > whatif.md
if jq -e '.changes[] | select(.changeType=="Delete")' whatif.json >/dev/null; then echo "::warning::what-if contains Delete"; fi
- name: Comment
env:
GH_TOKEN: ${{ github.token }}
run: gh pr comment ${{ github.event.pull_request.number }} -R ${{ github.repository }} --body-file whatif.md --edit-last || gh pr comment ${{ github.event.pull_request.number }} -R ${{ github.repository }} --body-file whatif.mdcd ~/myapp && git switch main && git pull && git switch -c infra/acr-tags mkdir -p infra && $EDITOR infra/main.bicep && $EDITOR .github/workflows/infra-whatif.yml git add infra .github/workflows/infra-whatif.yml && git commit -m "infra: manage ACR tags with Bicep" git push -u origin HEAD && gh pr create --fill && gh pr checks --watch gh pr view --comments | tail -n 12
### Bicep what-if (read-only identity, 2026-11-15T10:21:07Z) | Change | Resource | |---|---| | Modify | `acrghlab1234512345` | Commit: 5d1e…
Note: a new workflow file also runs when it first appears in a PR (pull_request using the workflow definition from the PR's merge commit).
infra environment (only main + required reviewers) and the write identity id-myapp-infra (Contributor on ACR, FIC environment:infra), then add the apply workflow:
on:
push:
branches: [main]
paths: ['infra/**']
concurrency: { group: infra-apply, cancel-in-progress: false }
jobs:
apply:
runs-on: ubuntu-latest
environment: infra
permissions: { contents: read, id-token: write }
steps:
- uses: actions/checkout@v7
- uses: azure/login@v3
with: { client-id: '${{ secrets.AZURE_CLIENT_ID }}', tenant-id: '${{ secrets.AZURE_TENANT_ID }}', subscription-id: '${{ secrets.AZURE_SUBSCRIPTION_ID }}' }
- name: Re-check what-if (reject unexpected deletions)
run: |
az deployment group what-if -g "${{ vars.RG }}" -f infra/main.bicep -p acrName="${{ vars.ACR }}" --no-pretty-print > w.json
! jq -e '.changes[] | select(.changeType=="Delete")' w.json
- run: az deployment group create -g "${{ vars.RG }}" -f infra/main.bicep -p acrName="${{ vars.ACR }}" --name "gh-${{ github.run_id }}" -o none
Terraform version: on the PR, terraform plan comment + on main, plan -out artifact upload + after environment approval, download and apply tfplan, full syntax in Terraform Hour 5 Module 2, which also covers permission design for the state lock and remote backend.
Case 1: a what-if comment saved a production database
Problem: A developer changed the PostgreSQL Flexible Server's location parameter from hard-coded to a variable, and the default value had the wrong region. The code diff was a single line and looked harmless. Result: A Create (in the new region) appeared in the PR comment, and reviewers spotted it immediately. In complete mode, or with the deployment stack's “delete unmanaged resources” setting, a Delete could also have come with it. Approach: The pipeline tags Delete/recreation changes with ::warning:: and requires an extra review label.
Case 2: the PR preview identity was asked to “just give it write permission, it's simpler”
Problem: The team found that what-if reported permission errors under the provider validation level, and proposed giving the PR identity Contributor. Risk: Anyone who can open a PR can add a step to the workflow az group delete. Approach: Switch to ProviderNoRbac + a minimal what-if custom role; the PR identity's FIC trusts only pull_request.
Case 3: the state changed between a Terraform plan and apply
Problem: Two PRs were merged one after another; the first apply changed the state, and the saved plan used by the second apply had expired. Result: Terraform refused to apply the expired plan (“Saved plan is stale”), which is exactly the value of a saved plan. Approach: After an apply fails, automatically re-plan and re-request approval; concurrency serialize the apply jobs.
Common errors and fixes
(AuthorizationFailed) The client '…' … does not have authorization to perform action 'Microsoft.Resources/deployments/whatIf/action' over scope '/subscriptions/…/resourceGroups/rg-gh-lab/…'
Cause: The read-only identity only has Reader and lacks the what-if operations needed for deployment.
Fix: Grant the custom role from Lab step 1; wait a minute or two after the role definition is first created.
what-if fails asking for write permission on resources (…/write)
Cause: The default Provider validation level was used, which checks against deployment permissions; or the Azure CLI version is below 2.76 and does not support --validation-level.
az version --query '"azure-cli"'
Fix: Upgrade the CLI and add --validation-level ProviderNoRbac.
GraphQL: Resource not accessible by integration (addComment) / HTTP 403: failed to write PR comment
Cause: The job permissions does not have pull-requests: write; or the PR comes from a fork (the token is read-only).
Fix: Add the missing permission; for fork PRs, write the results to the job summary $GITHUB_STEP_SUMMARY.
no comments found for current user (gh pr comment --edit-last)
Cause: On the first run there is no comment to edit yet.
Fix: Use the || step from the lab; if none exists, fall back to creating a new comment (newer gh versions also provide --create-if-none; see the gh docs).
1. Use jq to check whether the what-if result contains any deletions, and fail the job if it does.
az deployment group what-if -g $RG -f infra/main.bicep -p acrName=$ACR --no-pretty-print > w.json if jq -e '.changes[] | select(.changeType=="Delete")' w.json >/dev/null; then echo "::error::Delete detected"; exit 1; fi
2. Add a federated credential for pull_request to the read-only PR identity.
az identity federated-credential create -g $RG --identity-name id-myapp-plan --name gh-pr \ --issuer https://token.actions.githubusercontent.com --audiences api://AzureADTokenExchange --subject "$PREFIX:pull_request"
The security team challenges: “Bicep does not save a plan, so the what-if the reviewer approved may differ from what is actually executed after merge.” How do you respond and improve the pipeline?
Acknowledge the difference: ARM recalculates at deployment time. Improvements: ① the apply job references a protected environment, and the approval view shows the what-if re-run on main (job summary), so approvers see the version that will execute; ② run what-if again before apply, and fail if Delete / unexpected types appear; ③ use a deployment stack + deny settings to block out-of-band changes and reduce drift; ④ serialize apply; ⑤ for scenarios that must “execute exactly what was approved”, switch to a Terraform saved plan, or compare the PR-time and apply-time what-if summary hashes within the job.
Verified instructional videos
Official docs
- Bicep deployment what-if (including validation level)
- Azure/bicep-deploy (deployment / deploymentStack, operation: whatIf)
- Deployment stacks
Video storyboard (about 70 seconds)
Visual: the PR diff has a single-line change, and a what-if comment pops up beside it: “Create / Delete”.
Narration: review the consequences, not just the code. Post the preview results on the PR.
Visual: the PR job wears a “read-only” badge and the apply job wears an “infra environment” badge; the two walk toward different doors.
Narration: preview uses a read-only identity; apply uses the approval-protected environment identity.
Visual: Terraform seals the plan in an envelope; Bicep takes a fresh snapshot and compares it before execution.
Narration: Terraform can execute a saved plan as-is; Bicep recalculates every time, so it must be compared again before execution.
Visual: two apply jobs are queued, and only one is allowed through at a time.
Narration: use a concurrency group to serialize, so two changes never modify the same infrastructure at once.
Module 7 · Hands-on troubleshooting of cloud deployments
- Use the “five-layer model” to identify the failing layer within one minute: environment gates, ID token, Entra authentication, Azure authorization, runtime (image pull / probes).
- Understand the AADSTS error family and
AuthorizationFailed/LinkedAuthorizationFailedin each message, and give precise fixes accordingly. - Handle operational issues such as ACR pull 401s, stuck environment approvals, concurrent deployment conflicts, and long-running job token expiry.
What: the five-layer failure model
| Layer | Typical symptoms / errors | Where to look | First diagnostic command |
|---|---|---|---|
| ① GitHub gates | Waiting for review, Branch … is not allowed to deploy, Canceling since a higher priority waiting request … exists | Run page annotations | gh api …/runs/ID/pending_deployments |
| ② ID token | Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable | azure/login step logs | Check the job permissions |
| ③ Entra authentication | AADSTS700213 / 7002138 / 70021 / 700016 / 700024 … | Within the azure/login logs, the Federated token details | az identity federated-credential list |
| ④ Azure authorization | AuthorizationFailed, LinkedAuthorizationFailed, No subscriptions found | az step logs, activity log | az role assignment list --assignee PID --all |
| ⑤ Runtime | Revision provisioning failed, image pull 401/403, probe failure, ImagePullBackOff | ACA system logs,kubectl describe | az containerapp logs show --type system |
AADSTS error family (follow the exact error message text)
| Code | Meaning | Common root causes |
|---|---|---|
| AADSTS700213 | No matching federated identity record found for presented assertion subject | Environment / branch / PR / tag mismatch; classic vs. immutable format; repository renamed or transferred; custom subject template |
| AADSTS7002138 | Same as above, but differs only in letter case (original text in README: matches with case-insensitive comparison, but not with case-sensitive comparison) | Prod vs prod, owner name case |
| AADSTS70021 | No matching federated identity record found for presented assertion (the message lists Assertion Issuer / Subject / Audience) | Any one of the three values does not match; compare the values in the message one by one |
| AADSTS700211 / 700212 | issuer / audience mismatch (common cause) | GHE.com or GHES have a different issuer; changed the audience input or the FIC's audiences |
| AADSTS70025 | The client has no federated identity credentials configured at all (common cause) | client-id points to another identity |
| AADSTS700016 | Application with identifier … was not found in the directory | client-id was filled in with principalId, or the tenant is wrong |
| AADSTS700024 | Client assertion is not within its valid time range | The GitHub ID token has expired: in a long job, when az needs to re-fetch a token, the original ID token has long since expired |
How to read authorization errors
(AuthorizationFailed) The client '1b2c3d4e-…' with object id '9a8b7c6d-…' does not have authorization to perform action 'Microsoft.App/containerApps/write' over scope '/subscriptions/…/resourceGroups/rg-gh-lab/providers/Microsoft.App/containerApps/myapp-prod' or the scope is invalid. If access was recently granted, please refresh your credentials.
- client: which identity is used (compare with
clientIdto confirm the environment secret was not mixed up). - action: the specific missing operation; search the built-in role definitions to find which role includes it.
- scope: the target resource; the role assignment's scope must be that resource or one of its parents.
- recently granted: role assignments may take several minutes to propagate; a role just assigned within the same job may not yet be reflected in the existing token, so re-run the job.
LinkedAuthorizationFailed: has permission on the primary resource, but lacks join/read operations on the associated resources (Container Apps environment, subnet, Key Vault).
Why: why layering matters
The phrase “deployment failed” can hide things owned by completely different people: environment rules (repository admins), FIC (cloud identity admins), RBAC (subscription owners), images and probes (application team). Only by identifying the layer first can you find the right person and change the right thing, rather than randomly adding Owner to an identity.
When: other high-frequency issues
- Environment approval stuck: the only reviewer is the triggering user with prevent self-review enabled; members of the reviewer team lack read permission; on a private-repository plan that does not support required reviewers, the rule does not take effect (and therefore does not block).
- Concurrent deployment conflicts: two runs modify the same container app at once, and ARM may return 409 Conflict (operation in progress); or a later-started run finishes first, so an older version overwrites a newer one. Use
concurrencyto serialize. - Token expiry: in a long-running job (build + many deployments), az reports AADSTS700024 later on; split the long job, or run
azure/loginagain before the steps that need Azure (follow the latest guidance in the azure/login docs).
Five-layer localization diagram
Error decoder
Paste an error from Actions logs or Azure (or click an example). The decoder identifies the failing layer, extracts key fields (subject, client, action, scope), and gives diagnostic commands and a fix. It is pure front-end regex matching and does not send any data.
Troubleshooting command checklist
| Layer | Command | What to look at |
|---|---|---|
| ① | gh run view RUN --log-failed | Failed step logs |
| ① | gh api repos/$REPO/actions/runs/RUN/pending_deployments | Who can approve, which environment it waits for |
| ③ | az identity federated-credential list -g RG --identity-name ID -o table | subject / issuer / audiences |
| ③ | gh api repos/$REPO/actions/oidc/customization/sub | Prefix format, whether a custom template is used |
| ④ | az role assignment list --assignee PRINCIPAL_ID --all -o table | Role and scope |
| ④ | az role definition list --name "ROLE" --query "[].permissions[].actions" | Whether the role includes the action in the error |
| ④ | az monitor activity-log list -g RG --offset 1h --query "[?status.value=='Failed']" | ARM-side failure record |
| ⑤ | az containerapp logs show -g RG -n APP --type system --tail 50 | Pull, probe and scheduling events |
| ⑤ | az containerapp revision list -g RG -n APP --all -o table | Revision provisioning / running / health status |
# One-step “identity check”: list each deployment identity's FIC and roles source ~/gh-lab.env for n in build dev prod plan; do ID=id-myapp-$n; P=$(az identity show -g $RG -n $ID --query principalId -o tsv 2>/dev/null) || continue echo "== $ID" az identity federated-credential list -g $RG --identity-name $ID --query "[].subject" -o tsv | sed 's/^/ FIC /' az role assignment list --assignee $P --all --query "[].[roleDefinitionName, scope]" -o tsv | sed 's#/subscriptions/[^/]*/resourceGroups/##; s/^/ ROLE /' done
== id-myapp-build FIC repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/main ROLE AcrPush rg-gh-lab/providers/Microsoft.ContainerRegistry/registries/acrghlab1234512345 ROLE Reader rg-gh-lab/providers/Microsoft.ContainerRegistry/registries/acrghlab1234512345 == id-myapp-dev FIC repo:octo-dev@5544123/myapp@821093847:environment:dev ROLE Contributor rg-gh-lab/providers/Microsoft.App/containerApps/myapp-dev ROLE ACA Environment Joiner (rg-gh-lab) rg-gh-lab/providers/Microsoft.App/managedEnvironments/cae-gh-lab …
Lab 7: create 3 faults and fix them (about 8 minutes)
cd ~/myapp && git switch -c fault/subject && git push -u origin HEAD gh workflow run oidc-test.yml --ref fault/subject; sleep 8 gh run view $(gh run list -w oidc-test.yml -L 1 --json databaseId -q '.[0].databaseId') --log-failed | grep -E "AADSTS|subject claim"
subject claim - repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/fault/subject Error: AADSTS700213: No matching federated identity record found for presented assertion subject 'repo:octo-dev@5544123/myapp@821093847:ref:refs/heads/fault/subject'. …
Conclusion: This is a correct rejection— the fix is not to add an FIC for the fault branch, but to run only from main. Cleanup: git switch main && git push origin --delete fault/subject.
cat >> .github/workflows/oidc-test.yml <<'EOF'
- run: az containerapp show -g ${{ vars.RG }} -n myapp-dev --query name -o tsv
EOF
git add . && git commit -m "test: authz fault" && git push # go via PR if protected
gh workflow run oidc-test.yml --ref main; sleep 8
gh run view $(gh run list -w oidc-test.yml -L 1 --json databaseId -q '.[0].databaseId') --log-failed | grep -o "(AuthorizationFailed).*scope '[^']*'"
(AuthorizationFailed) The client '0a1b2c3d-…' with object id '…' does not have authorization to perform action 'Microsoft.App/containerApps/read' over scope '/subscriptions/…/resourceGroups/rg-gh-lab/providers/Microsoft.App/containerApps/myapp-dev'
Conclusion: Authentication succeeded and authorization failed, as expected under least-privilege design. Undo this step: git revert HEAD and push.
source ~/gh-lab.env
PID=$(az containerapp show -g $RG -n $APP_DEV --query identity.principalId -o tsv)
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment delete --assignee $PID --role AcrPull --scope $ACR_ID
sleep 120 # wait for the role deletion to propagate
az containerapp update -g $RG -n $APP_DEV --revision-suffix fault401 --set-env-vars FAULT=1 -o none
az containerapp revision show -g $RG -n $APP_DEV --revision $APP_DEV--fault401 --query "{prov:properties.provisioningState, run:properties.runningState}" -o table
az containerapp logs show -g $RG -n $APP_DEV --type system --tail 20 | grep -iE "pull|401|unauthor" | head -5
Prov Run ------- ------------- Failed Failed … Failed to pull image "acrghlab….azurecr.io/myapp@sha256:…": … 401 Unauthorized …
In Single mode, the failed new revision receives no traffic and the old revision keeps serving — this is itself an “automatic rollback”. Fix:
az role assignment create --assignee-object-id $PID --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_ID -o none
sleep 120
az containerapp update -g $RG -n $APP_DEV --revision-suffix fixed401 --remove-env-vars FAULT -o none
az containerapp revision list -g $RG -n $APP_DEV --query "[?properties.active].{rev:name, health:properties.healthState}" -o tableCase 1: all repository deployments failed on Monday morning
Symptom: 30 repositories in the organization all reported AADSTS700213. Investigation: The sub in the token became repo:…:environment:prod:job_workflow_ref:…— over the weekend someone enabled a custom subject template at the organization level (added job_workflow_ref to include_claim_keys) and made all repositories use the organization template. Fix: Roll back the template; plan the migration: first add FICs for the new format in Azure, then switch repositories one by one. Lesson: Changing the subject template is a breaking change; the GitHub docs explicitly require “configure the matching conditions in the cloud first”.
Case 2: AuthorizationFailed appeared only in prod
Symptom: dev deployments were fine, but prod reported Microsoft.App/containerApps/write an authorization failure. Investigation: The client ID in the error did not match id-myapp-prod but matched id-myapp-dev — someone set the prod environment's AZURE_CLIENT_ID secret to the dev identity's value. Because the dev identity also happened to have environment:prod 's FIC (leftover configuration), authentication succeeded anyway. Fix: Correct the secret, and delete the extra FIC on the dev identity. Lesson: The client ID in the error is the first clue.
Case 3: login failed at the end of a long build job
Symptom: A single job that builds for 40 minutes before deploying occasionally reports AADSTS700024. Cause: Late in the run, az needs to re-fetch a token for another resource scope, but the original GitHub ID token had already expired. Fix: Split into build and deploy jobs (the structure used in this course), each logging in on its own.
Interactive troubleshooting tree
Starting from the symptom you see, answer the questions step by step to get the diagnosis and fix commands.
Addendum: errors that are easily confused
Canceling since a higher priority waiting request for 'deploy-main' exists
Cause: The concurrency group keeps only one “waiting” run, and the new run replaced the old waiting run (this is not a failure).
Fix: This is the expected behavior; if you want every merge to deploy, redesign the concurrency group (e.g., distinguish by SHA), but weigh the risk of concurrent changes.
ERROR: No subscriptions found for ….
Cause: Authentication succeeded, but the identity has no role assignment in the subscription (or subscription-id was entered wrongly).
Fix: Grant the required role; only when tenant-level operations are needed, set allow-no-subscriptions: true.
(Conflict) … operation is in progress / another operation is in progress
Cause: Two deployments are modifying the same container app or its traffic configuration at the same time (exact error codes and wording follow what is actually returned).
Fix: Serialize with workflow-level concurrency ; in the script, retry 409 a limited number of times with backoff.
1. Given the client ID in an error, find which managed identity it is and list all of its roles.
CID=1b2c3d4e-1111-2222-3333-444455556666
az identity list -g rg-gh-lab --query "[?clientId=='$CID'].{name:name, principalId:principalId}" -o table
az role assignment list --assignee $(az identity list -g rg-gh-lab --query "[?clientId=='$CID'].principalId | [0]" -o tsv) --all -o table2. Check which built-in role includes Microsoft.App/managedEnvironments/join/action.
az role definition list --query "[?permissions[?contains(join(',', actions), 'Microsoft.App/managedEnvironments/join/action') || contains(join(',', actions), 'Microsoft.App/*')]].roleName" -o tsvA colleague reports: “prod deployment reports AADSTS700213; I already gave the identity Owner, but it still fails.” Point out the error and give the correct troubleshooting steps.
AADSTS700213 is a layer ③ (authentication) failure; RBAC belongs to layer ④; adding Owner does nothing and seriously violates least privilege, so it should be revoked immediately. Correct steps: ① copy from the azure/login logs subject claim; ② az identity federated-credential list compare the two; ③ determine the source of the difference: environment name, letter case (if it is 7002138), classic vs. immutable prefix (check sub_claim_prefix), whether the repository was renamed or transferred, whether a custom template is enabled; ④ add the correct FIC, and delete the wrong one after confirming.
Verified instructional videos
No verified video dedicated to AADSTS700213 / immutable subject troubleshooting was found; refer to this module and the official docs.
Official docs
- Azure/login: OIDC login fails with AADSTS700213 / AADSTS7002138
- Microsoft Entra authentication and authorization error codes
- Troubleshoot Azure RBAC · Troubleshoot Azure Container Apps
Video storyboard (about 80 seconds)
Visual: five doors in a row, labeled gate, token, authentication, authorization, runtime.
Narration: when a deployment fails, don't rush to change the configuration; first work out which door it is stuck at.
Visual: the third door flashes AADSTS700213; the doorman holds two cards bearing a subject, and one character differs.
Narration: AADSTS is an authentication failure, so compare the subject; adding a role does nothing.
Visual: the fourth door flashes AuthorizationFailed; a magnifying glass lights up the client, action and scope fields in turn.
Narration: an authorization failure means authentication already succeeded. Read out who it is, what operation is missing, and at which scope.
Visual: behind the fifth door, the container app figure carries another key to ACR to pull the image, and is turned back with a 401.
Narration: an image pull 401 is a runtime identity problem, unrelated to the pipeline identity.
Module 8 · Cost, cleanup and self-test
- Explain how each resource in this course is billed, including the items that charge even when idle, and estimate the lab costs.
- Clean up in the right order: stop the pipeline first, then delete cloud resources, then delete tenant-level objects (custom roles), and finally clean up the GitHub side (environments, secrets, variables, workflows).
- Use 8 self-test questions to check the core skills from this course.
What: how the resources in this course are billed
| Resource | Billing method | When idle | Course estimate |
|---|---|---|---|
| Container Apps (Consumption) | Billed per vCPU-second, GiB-second and request count; each subscription gets a monthly free grant of 180,000 vCPU-seconds, 360,000 GiB-seconds and 2 million requests | No resource charges at min replicas 0; at min replicas ≥ 1, billed at the “idle rate” | Usually within the free grant |
| Log Analytics for the Container Apps environment | Billed by log ingestion volume (GB) | Any system logs mean ingestion | Lab volumes are tiny: cents to around one dollar |
| ACR Basic | Billed per day + storage beyond the included amount | Charged daily even when idle | About 0.17 USD per day |
| User-assigned managed identities, federated credentials, role assignments | Free | — | 0 (but with the security risk of “leftover trust”) |
| GitHub Actions minutes | Public repositories are free on GitHub-hosted standard runners; private repositories consume plan minutes | — | 0 for public repositories |
| (Optional) App Service S1, AKS nodes | Hourly | Charged even when idle | About 0.1 USD per hour; delete immediately after finishing |
Amounts are order-of-magnitude estimates (2026-11); for actual figures, refer to the Container Apps pricing, ACR and Log Analytics pricing pages and your region. It is recommended to set a budget alert on the subscription (Cost Management → Budgets).
Why: cleanup is about more than saving money
- Leftover trust: a federated credential trusts “a certain environment of a certain repository”. If the identity is kept but the repository is later deleted and recreated under the same name by someone else,the classic subject can be satisfied again (subject recycling). Only deleting the identity or switching to immutable subjects removes this completely.
- Tenant-level objects: custom role definitions are not in the resource group; they still exist after the resource group is deleted, and their names are unique within the tenant, so they block the next lab.
- Leftovers on the GitHub side: the client-id in environment-level secrets is not itself a credential, but a leftover deployment workflow will error or misfire on the next push.
How: cleanup order
- Stop the pipeline:
gh workflow disablethe deployment-related workflows, so cleanup does not trigger revision recreation or failures. - Delete the resource group: delete together the ACR, the Container Apps environment and apps, Log Analytics, all UAMIs (their FICs are deleted with them), and role assignments scoped within the resource group.
- Delete custom role definitions: “ACA Environment Joiner (rg-gh-lab)”, “Deployment What-If Runner (rg-gh-lab)”.
- Clean up GitHub: delete environments (along with their environment secrets/variables), repository-level secrets/variables, and the lab workflows; switch the repository back to private or delete the test repository.
- Verify:
az group exists,az role definition list --custom-role-only,gh api …/environments,gh secret list.
When: when not to delete
If you plan to continue to Hour 5 (reuse, release and hardening), you can keep the myapp repository's workflows and GitHub environments and delete only the Azure resources; rebuild later in 10 minutes with the Module 0 script (note: after rebuilding you need to write the new client-id again, and recreate the FICs).
Cleanup dependency diagram
Monthly cost estimator (order of magnitude)
Drag the sliders to estimate the cost of keeping this course's resources. Unit prices are order-of-magnitude assumptions as of 2026-11, used only to build intuition; for actual figures, use the Azure pricing calculator.
Cleanup and verification commands
| Command | Purpose |
|---|---|
gh workflow disable deploy.yml -R $REPO | Disable workflows (keep the files) |
az group delete -n rg-gh-lab --yes --no-wait | Delete resource group (async) |
az group wait -n rg-gh-lab --deleted | Wait for deletion to complete |
az role definition list --custom-role-only true --query "[].roleName" -o tsv | List custom roles |
az role definition delete --name "ROLE NAME" | Delete custom role (all assignments must be deleted first) |
gh api -X DELETE repos/$REPO/environments/NAME | Delete environment (along with its secrets/variables) |
gh secret delete NAME -R $REPO / gh variable delete NAME -R $REPO | Delete repository-level secret / variable |
gh repo edit $REPO --visibility private --accept-visibility-change-consequences | Switch back to private |
Lab 8: one-step cleanup and verification (about 4 minutes + background deletion)
source ~/gh-lab.env for w in deploy.yml oidc-test.yml infra-whatif.yml infra-apply.yml env-probe.yml; do gh workflow disable $w -R $REPO 2>/dev/null && echo "disabled $w"; done
source ~/gh-lab.env az group delete -n $RG --yes # synchronous wait, about 5–10 minutes az group exists -n $RG for r in "ACA Environment Joiner ($RG)" "Deployment What-If Runner ($RG)"; do az role definition delete --name "$r" 2>/dev/null && echo "deleted role: $r" done az role definition list --custom-role-only true --query "[?contains(roleName, '$RG')].roleName" -o tsv
false deleted role: ACA Environment Joiner (rg-gh-lab) deleted role: Deployment What-If Runner (rg-gh-lab)
If deleting a custom role fails with a message saying assignments still exist, either the resource group deletion has not finished or there are assignments outside the resource group: az role assignment list --role "ROLE" --all find them and delete them.
for e in dev prod infra aks-prod web-staging web-prod; do gh api -X DELETE repos/$REPO/environments/$e 2>/dev/null && echo "env $e deleted"; done for s in AZURE_TENANT_ID AZURE_SUBSCRIPTION_ID AZURE_CLIENT_ID_BUILD AZURE_CLIENT_ID_PLAN; do gh secret delete $s -R $REPO 2>/dev/null; done for v in ACR RG WEB; do gh variable delete $v -R $REPO 2>/dev/null; done gh api repos/$REPO/environments --jq '.total_count'; gh secret list -R $REPO; gh variable list -R $REPO
env dev deleted env prod deleted 0
Whether to delete the workflow files depends on whether you continue to Hour 5. If you switched the repository to public in Module 3, you can switch it back to private now. This course did not create a PAT; if you created one for the lab, revoke it under Settings → Developer settings.
rm -f ~/gh-lab.env /tmp/aca-env-join.json /tmp/whatif-role.json (if you want to keep the variables for a rebuild, you can delete only the ACR name line).Self-test (answer without notes)
1. A job writes environment: prod, and is also triggered on pull_request; what is the suffix of the token sub?
:environment:prod. The environment takes precedence over the event type.
2. For a repository created in 2026-08, what does the sub of a push job on the main branch look like?
repo:OWNER@OWNER_ID/REPO@REPO_ID:ref:refs/heads/main (immutable format), based on sub_claim_prefix and the logs.
3. Why does this course use three deployment identities instead of one?
RBAC is granted per identity; after the split, build can only push images, dev can only change myapp-dev, prod can only change myapp-prod, and each trusts only its corresponding subject.
4. Can a private repository on a Free account use required reviewers?
No (private repositories on Pro/Team cannot either); you need a public repository or Enterprise.
5. When a prod smoke test fails, how does the workflow roll back?
if: failure() step switches traffic back to the old revision (ingress traffic set OLD=100 NEW=0) and deactivates the new revision.
6. Which identity should be checked for an ACR pull 401?
Whether the container app's runtime identity (system-assigned identity) has AcrPull, and whether the registry is configured to use that identity.
7. What is the difference between Bicep what-if and Terraform plan regarding “what is approved is what is executed”?
Terraform can save the plan file and apply it as-is; Bicep what-if cannot be saved, is recalculated at deployment, and must be compared again before apply.
8. After deleting the resource group, which Azure objects still need to be cleaned up manually?
Custom role definitions, role assignments outside the resource group, and app registrations (if used).
Case 1: a lab ACR cost $60 in one year
Problem: After the training ended, learners deleted only the container apps; the ACR Basic registry stayed in the subscription and was billed daily for a year. Approach: Put all lab resources in a separate resource group and apply the course tag; set a budget alert on the subscription; use Azure Policy or a scheduled script to list resource groups older than 7 days with the course tag.
Case 2: a “ghost trust” from a deleted repository
Problem: An audit found that an app registration still has an FIC trusting repo:old-org/legacy-api:environment:prod, while old-org/legacy-api had long since been deleted, and the organization name has been released. Risk: Anyone who registers the same organization and repository names can satisfy this classic subject. Approach: Delete the FIC; for FICs still in use, migrate to immutable subjects; regularly use Graph / az to list the FICs for every GitHub issuer and compare them with existing repositories.
Case 3: a custom role name conflict made the second training cohort fail
Problem: The first training cohort deleted the resource group but did not delete the custom role definitions; when the second cohort ran, az role definition create the role name already existed. Approach: The cleanup script includes role definition deletion; role names include the resource group name or a date.
Common problems during cleanup
(RoleDefinitionHasAssignments) There are existing role assignments referencing role (code: RoleDefinitionHasAssignments)
Cause: The resource group is still being deleted, or there are assignments outside the resource group.
az role assignment list --role "ACA Environment Joiner (rg-gh-lab)" --all -o table
Fix: Wait for az group wait --deleted to complete, or delete the listed assignments and retry.
gh: Not Found (HTTP 404) (when deleting an environment)
Cause: The environment does not exist (the optional lab was not created), which can be ignored; or $REPO is empty.
Fix:echo $REPO Confirm: gh api repos/$REPO/environments --jq '.environments[].name'.
The resource group deletion has not finished for a long time
Cause: Container Apps environment deletion is slow, or the resource has a delete lock.
az lock list -g rg-gh-lab -o table az group show -n rg-gh-lab --query properties.provisioningState
Fix: Remove the lock and retry; if the status is Deleting, be patient.
1. List all custom roles in the subscription whose names contain “rg-gh-lab”, and delete them.
az role definition list --custom-role-only true --query "[?contains(roleName,'rg-gh-lab')].roleName" -o tsv | while read -r r; do az role definition delete --name "$r"; done
2. Confirm the myapp repository has no deployment environments and no secrets starting with AZURE_.
gh api repos/$REPO/environments --jq '.total_count' gh secret list -R $REPO | grep '^AZURE_' || echo "no AZURE_* secrets"
You need to roll out this course's pipeline to 15 services on the team. Provide a checklist for “identity and cost hygiene”.
Identity: per service, split UAMIs by build and by environment; FICs use only the environment or main-branch subjects, in immutable format; client secrets are forbidden; roles are scoped to specific resources; every quarter, run a script to compare FICs against existing repositories and delete orphaned trust. GitHub: prod environment with required reviewers + main only + admin bypass disabled; deployment workflows use concurrency; Actions pinned by SHA. Cost: tag each service's resources with owner / cost-center; non-production ACA minimum replicas 0; one shared ACR (permissions split by repository); Log Analytics with a daily cap and a retention period; budget alerts; lab resource groups with a TTL tag and regular cleanup.
Related videos
No verified video dedicated to “GitHub → Azure lab cleanup and cost hygiene” was found. You can review the OIDC video from Module 2 (to understand why federated credentials need cleaning up), and refer to the official docs below.
Official docs
- Azure Container Apps pricing · Billing in Azure Container Apps
- Create and manage budgets
- Mutable subjects in federated identity credentials
Video storyboard (about 60 seconds)
Visual: a box labeled rg-gh-lab is thrown into the recycle bin, but two “custom role” cards and a GitHub environment icon are still floating outside the box.
Narration: deleting the resource group is only half of cleanup.
Visual: on the meter, the ACR ticks up one step per day, even with no requests at all.
Narration: ACR is billed per day and charges even when idle; with Container Apps at minimum replicas of zero, only logs are billed.
Visual: the four cleanup checklist items are ticked off one by one: stop the workflow, delete the resource group, delete role definitions, clean up GitHub.
Narration: cut off the trigger sources first, then delete cloud resources, and finally clean up tenant-level objects and GitHub configuration, verifying each step.
Command cheat sheet
OIDC and identity
az identity create -g $RG -n id-myapp-prod
az identity show -g $RG -n id-myapp-prod --query "{clientId:clientId, principalId:principalId}"
az identity federated-credential create -g $RG --identity-name id-myapp-prod --name gh-env-prod \
--issuer https://token.actions.githubusercontent.com --audiences api://AzureADTokenExchange \
--subject "$PREFIX:environment:prod"
az identity federated-credential list -g $RG --identity-name id-myapp-prod -o table
gh api repos/$REPO/actions/oidc/customization/sub # sub_claim_prefix / use_immutable_subject
gh api -X PUT repos/$REPO/actions/oidc/customization/sub -F use_default=true -F use_immutable_subject=true
gh api repos/$REPO --jq '.owner.id, .id' # look up the IDs needed for the immutable subject
| Job context | sub suffix |
|---|---|
environment: X (any event) | :environment:X |
| pull_request, no environment | :pull_request |
| branch / tag, no environment | :ref:refs/heads/B / :ref:refs/tags/T |
| prefix | classic repo:OWNER/REPO; immutable repo:OWNER@OID/REPO@RID (new, renamed or transferred from 2026-07-15, or opt-in) |
Workflow snippet
permissions:
contents: read
jobs:
deploy:
runs-on: ubuntu-latest
environment: prod
permissions: { contents: read, id-token: write } # job-level override of the workflow-level setting
concurrency: { group: deploy-prod, cancel-in-progress: false }
steps:
- uses: azure/login@v3 # v3.1.0 = a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 (verified 2026-11-15)
with:
client-id: ${{ secrets.AZURE_CLIENT_ID }} # environment-level secret
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
environments (REST)
gh api -X PUT repos/$REPO/environments/prod --input env.json # reviewers / wait_timer / prevent_self_review / can_admins_bypass gh api -X POST repos/$REPO/environments/prod/deployment-branch-policies -f name=main -f type=branch gh secret set AZURE_CLIENT_ID --env prod -R $REPO --body "$CID" gh api repos/$REPO/actions/runs/$RUN/pending_deployments gh api -X POST repos/$REPO/actions/runs/$RUN/pending_deployments -F "environment_ids[]=$ENV_ID" -f state=approved -f comment="ok"
Container Apps
az acr login --name $ACR az containerapp update -g $RG -n $APP --image $IMG --revision-suffix r$RUN-1-$SHA7 --set-env-vars APP_VERSION=$SHA az containerapp revision set-mode -g $RG -n $APP --mode multiple az containerapp revision list -g $RG -n $APP -o table az containerapp revision show -g $RG -n $APP --revision $REV --query properties.fqdn -o tsv az containerapp ingress traffic set -g $RG -n $APP --revision-weight $OLD=0 $NEW=100 az containerapp revision deactivate -g $RG -n $APP --revision $NEW az containerapp logs show -g $RG -n $APP --type system --tail 50
AKS and App Service
az role assignment create --role "Azure Kubernetes Service Cluster User Role" --scope $AKS_ID … az role assignment create --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp … kubectl auth can-i create deployments -n myapp az webapp deployment slot create -g $RG -n $WEB --slot staging az webapp deployment slot swap -g $RG -n $WEB --slot staging --target-slot production [--action preview|swap|reset] az webapp traffic-routing set -g $RG -n $WEB --distribution staging=15
| Action | Versions (2026-11-15) |
|---|---|
| azure/login | v3.1.0 |
| actions/checkout | v7.0.1 |
| docker/build-push-action · setup-buildx-action · login-action | v7.4.0 · v4.4.1 · v4.8.0 |
| azure/aks-set-context · k8s-deploy · setup-kubectl · use-kubelogin · k8s-bake | v5.0.1 · v7.0.1 · v5.2.0 · v1.3 · v4.1.1 |
| azure/webapps-deploy · bicep-deploy · cli · container-apps-deploy-action | v3.0.8 · v2.5.0 · v3.0.0 · v2 (2023) |
IaC
az deployment group what-if -g $RG -f infra/main.bicep -p acrName=$ACR --validation-level ProviderNoRbac --no-pretty-print az deployment group create -g $RG -f infra/main.bicep -p acrName=$ACR --name gh-$GITHUB_RUN_ID gh pr comment $PR --body-file whatif.md --edit-last || gh pr comment $PR --body-file whatif.md
Troubleshooting quick reference
| Keyword | Layer | First action |
|---|---|---|
| Waiting for review / not allowed to deploy | ① Gate | pending_deployments, branch policy |
| ACTIONS_ID_TOKEN_REQUEST_URL | ② Token | job-level id-token: write |
| AADSTS700213 / 7002138 / 70021 | ③ Authentication | copy the subject claim from the logs → compare with the FIC |
| AADSTS700016 | ③ Authentication | client-id uses clientId, not principalId |
| AADSTS700024 | ③ Authentication | split long jobs / log in again |
| AuthorizationFailed / LinkedAuthorizationFailed | ④ Authorization | read client / action / scope → add the role |
| pull image 401 / ImagePullBackOff | ⑤ Runtime | runtime identity AcrPull + registry configuration |
Cleanup
gh workflow disable deploy.yml -R $REPO az group delete -n rg-gh-lab --yes az role definition delete --name "ACA Environment Joiner (rg-gh-lab)"; az role definition delete --name "Deployment What-If Runner (rg-gh-lab)" for e in dev prod infra; do gh api -X DELETE repos/$REPO/environments/$e; done gh secret list -R $REPO; gh variable list -R $REPO
Capstone lab + graduation quiz
rg-gh-lab (canadacentral) and submit acceptance evidence.cae-gh-lab,myapp-dev (Single) and myapp-prod (Multiple); the runtime identities of both apps have AcrPull, and the ingress target port is changed to 5000.
source ~/gh-lab.env
az containerapp list -g $RG --query "[].{n:name, mode:properties.configuration.activeRevisionsMode, port:properties.configuration.ingress.targetPort}" -o tablesub_claim_prefix to confirm the prefix; run oidc-test and record the subject claim in the logs.
for n in build dev prod plan; do echo "== $n"; az identity federated-credential list -g $RG --identity-name id-myapp-$n --query "[].subject" -o tsv; done
AZURE_CLIENT_ID and APP; use env-probe to prove that a feature branch cannot deploy to prod.ci.yml is a required check in the main ruleset (Hours 1 and 2). Open a PR that edits the README; after CI passes, merge it.on:
push:
branches: [main]
workflow_dispatch:
inputs:
simulate_failure:
description: 'prod smoke test accesses a nonexistent path, used to drill automatic rollback'
type: boolean
default: false
# ... in deploy-prod, change the smoke step to:
- name: Smoke test new revision (0% traffic)
env:
SMOKE_PATH: ${{ inputs.simulate_failure && '/does-not-exist' || '/healthz' }}
run: curl --fail --silent --show-error --retry 3 --retry-delay 5 "https://${{ steps.stage.outputs.revfqdn }}$SMOKE_PATH"
When triggered by push, inputs.simulate_failure is empty, and the expression takes /healthz.
RUN=$(gh run list -w deploy.yml -L 1 --json databaseId -q '.[0].databaseId'); gh run watch $RUN
az containerapp show -g $RG -n $APP_PROD --query "properties.template.containers[0].image" -o tsv
az containerapp revision list -g $RG -n $APP_PROD --query "[].{rev:name, traffic:properties.trafficWeight, active:properties.active}" -o tablegh workflow run deploy.yml --ref main -f simulate_failure=true; sleep 10
RUN=$(gh run list -w deploy.yml -L 1 --json databaseId -q '.[0].databaseId')
# After approval (web UI or pending_deployments API):
gh run watch $RUN; gh run view $RUN --log | grep -E "rolling back|Smoke test" | head
az containerapp revision list -g $RG -n $APP_PROD --query "[].{rev:name, traffic:properties.trafficWeight, active:properties.active}" -o table
X deploy-prod … failure (Smoke test new revision failed, Roll back on failure ran successfully) Rev Traffic Active --------------------------- --------- -------- myapp-prod--r12-1-a1b2c3d 100 True ← the previous good revision still receives all traffic myapp-prod--r13-1-a1b2c3d 0 False ← the failed new revision has been deactivated
infra/main.bicep tags, and take a screenshot of the what-if comment.Open-ended self-test (6 questions)
1. If you want to change the prod release to “publish only when a v* tag is pushed”, how do you change the OIDC and environment configuration?
In the prod environment's deployment policies, add a v* tag (type: tag), and either remove the main branch or keep both; the workflow adds push: tags: ['v*']; the deployment job still uses environment: prod, so the FIC does not need to change (the subject is still environment:prod). This is the benefit of an environment subject over a tag subject: tags differ each time, and FICs do not support wildcards.
2. The company repository was transferred in 2026-10 from team-a to platform organization, and all deployments failed. Write the fix and prevention steps.
After the transfer, the repository uses an immutable subject automatically, and the owner name changed. Fix: copy the new subject claim from the logs, add a new FIC for each identity, and after verification delete the old FICs. Prevention: include repository renames and transfers in change management, and pre-create FICs in advance using gh api repos/… to fetch the IDs; migrate all FICs to the immutable format as early as possible.
3. Why doesn't this course's rollback need to redeploy the old image? What are its prerequisites?
In multiple-revision mode the old revision has been an active revision all along, with traffic at 0 (after switching) or 100 (during pre-release); rollback only changes traffic rules (application-scope configuration, which takes effect immediately). Prerequisites: the old revision is still active and has not been deactivated or cleaned up; the rollback scope is limited to revision-scope changes, and application-scope configuration such as secrets and ingress does not roll back along with it.
4. How do you prove that the “prod identity can only change myapp-prod”?
List its role assignments (scoped to the myapp-prod app + the environment join custom role); in a test job that uses the prod environment, try az containerapp update -n myapp-dev, which should get AuthorizationFailed; also check that the FIC has only one entry, environment:prod.
5. The team wants PR preview environments (one ACA revision or app per PR) to deploy automatically; how would you design the identities and cleanup?
Use a separate preview environment and identity, with the FIC subject set to environment:preview (PR jobs reference that environment; note that fork PRs have no id-token); the identity may only create and delete apps in the preview-dedicated resource group; use revision labels or apps named by PR number; a PR-closed event triggers a cleanup job; a scheduled task deletes preview resources older than N days; do not give PR jobs production-related permissions.
6. Compare this course's push-style pipeline with AKS GitOps in terms of approval and auditing.
Push-style: the approval point is the environment (who approved which run); auditing is in the Actions run records, the Deployments API, and the Azure activity log (distinguished by identity name). GitOps: the approval point is the PR in the manifest repository (ruleset review); auditing is Git history plus reconciler events; cluster write permission is concentrated in the reconciler identity. GitOps naturally records every change in desired state; push-style needs deployment results written back to GitHub separately.
Sources and version notes
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| OIDC subject format | Four forms: environment / pull_request / ref:refs/heads / ref:refs/tags; environment takes precedence; colons are encoded as %3A; the job needs id-token: write; custom templates are available via include_claim_keys | GitHub Docs: OpenID Connect reference |
| Immutable subject | Format repo:OWNER@OWNER_ID/REPO@REPO_ID:…; repositories created, renamed or transferred after 2026-07-15 adopt it automatically; older repositories can opt in at the organization or repository level (UI or REST use_immutable_subject); not applicable to GHES; 2026-06-10 editor's note: the separator changed from - to @ | GitHub Changelog 2026-04-23 · REST: Actions OIDC(sub_claim_prefix) |
| Entra migration guide | Add the new immutable FIC first → opt in → verify → delete the old FIC; risk of subject recycling; flexible FICs must match repository_id / repository_owner_id at the same time | Microsoft Learn (2026-07-28) |
| FIC fields and limits | Each app or UAMI has at most 20; issuer+subject must be unique; wildcards not supported; recommended audiences api://AzureADTokenExchange; name is 3–120 characters and cannot be changed; flexible FICs are in preview | Create a trust relationship |
| azure/login | v3.1.0 (2026-09-10); v3 supported, v2 in maintenance mode, v1 EOL; published as an immutable release; inputs client-id / tenant-id / subscription-id / allow-no-subscriptions / audience / environment / auth-type / mask-client-id; ignored when any OIDC input is set creds; AADSTS700213 / 7002138 troubleshooting (case sensitivity, the pitfall of entering numeric IDs in the portal); v3.1.0 commit a641126d…c906 | Azure/login README and Releases,git ls-remote |
| environments | Required reviewers ≤ 6, any one person approves; prevent self-review; wait timer 1–43,200 minutes and not billed; three branch/tag policy types; admin bypass enabled by default; custom rules are public preview, up to 6 per environment; environment secrets are not readable before approval; plan availability table | Deployments and environments |
| Container Apps revisions | Single (default) / Multiple / Deployment labels (preview); revision scope vs. application scope; suffix rules; 100 inactive revisions kept by default; in Single mode, traffic shifts only after readiness | Update and deploy changes in ACA |
| Container Apps pricing | Consumption: each subscription gets a monthly free grant of 180,000 vCPU-seconds, 360,000 GiB-seconds and 2 million requests; idle rate | ACA pricing |
| App Service deployment slots | Standard / Premium / Isolated; Standard allows 5 slots; 6 swap steps; list of settings that swap or do not swap (managed identities do not swap); swap with preview --action preview|swap|reset; auto swap does not support Linux or containers; warm-up settings | Set up staging environments |
| Bicep what-if | ProviderNoRbac The validation level only checks read permissions (Azure CLI ≥ 2.76); the default Provider-level permissions are the same as for deployment | Bicep deployment what-if · Azure/bicep-deploy |
| Azure Actions versions | aks-set-context v5.0.1 (node24), k8s-deploy v7.0.1 (node24, strategy default basic), setup-kubectl v5.2.0, use-kubelogin v1.3 (node24), k8s-bake v4.1.1, webapps-deploy v3.0.8 (node24), bicep-deploy v2.5.0, azure/cli v3.0.0, container-apps-deploy-action latest v2 (2023-10; action.yml declares node16) | GitHub Releases / Tags API and each repository action.yml |
| Other actions | actions/checkout v7.0.1, docker/build-push-action v7.4.0, setup-buildx-action v4.4.1, login-action v4.8.0, actions/github-script v9.0.0 | GitHub Releases API; versions verified in the course specification |
| Azure CLI | 2.93.0 (released 2026-11-15) | azure-cli releases |
Video verification notes
The following videos had their titles and channels verified through the YouTube oEmbed endpoint (2026-11-15): John Savill's Technical Training, “GitHub Azure AD OIDC Authentication” (XkhkkLBkAT4); Christos Matskas, “GitHub Actions with Azure AD Workload Identity Federation” (u7PcV9ivaAo); Jon Gallant, “Connect to Azure from a GitHub Action with OpenID Connect (OIDC)” (IKuw9T6vZYU), and “Connect to @MicrosoftAzure from a @GitHub Action with OpenID Connect (OIDC) - v2” (r5QdsjjdRDs); Asp.Net Monsters, “GitHub Actions to Azure, without secrets! (#268)” (qSIs7HzgpiA), and “Deploying to Environments with GitHub Actions (#212)” (EOlm3ft0VPo); Coding Night NZ, “Passwordless (OIDC) Authentication from GitHub to Azure and the Graph API for Terraform” (Q5xmGFs7WX4); GitHub, “GitHub Changelog: Manage and deploy environments with GitHub Actions” (T5VZBA92HS0), “Multi-stage deployments in GitHub Actions” (noLED7kKBF4), and “How to integrate deployment protection rules with Honeycomb” (hb4SILCgvjc); Will Velida, “How to update your Azure Container Apps using Revisions” (jFa4Rd-c4wA); Kamal Rathnayake - MVP, “Azure Container Apps - Revisions Explained | Step by Step” (5vPM94kpIO4); MadeForCloud, “Traffic Splitting in Azure Container Apps | Step-by-Step Lab Demo” (k29K-GkJApE); Learn with Jon, “How to deploy your Azure Container Apps using Azure CLI command and GitHub Action | Azure Deployment” (tbj2Nv-Z96Y); Microsoft Reactor, “Kubernetes-Free Microservices: The Azure Container Apps Advantage” (Nom9JtjZ8Js), and “Azure Kubernetes Service deployment pipeline and GitHub Actions” (eIoIj5DlsB8); Microsoft Azure, “Overview of GitHub Actions for Kubernetes” (q6uxmYdm7iA); Houssem Dellai, “Kubelogin to connect to Kubernetes” (XFWphg4EYL0); Anurodh Dharmawat, “Azure App Services - Adding and Swapping Deployment Slots using Azure CLI” (HsnOvraldPQ); SoftWiz Circle, “A Beginner's Guide to Azure App Service Slots: Deploying and Swapping Apps” (LH3a534gKwk); Microsoft Developer, “Testing your Bicep code with GitHub Actins” (uzYMcpeUgWM), and “Automating Azure infrastructure changes with Bicep and GitHub Actions” (P-q_1HLPeY4); Ned in the Cloud, “Using OIDC with GitHub Actions and Terraform” (10ljwwJ3V30); Festive Tech Calendar, “Day 15 - Terraforming with GitHub Actions with Ned Bellavance” (1G0th5szgg0). The oEmbed endpoint does not return durations or publication dates, so durations are not listed on the cards. All videos are in English and were recorded before the immutable subject change; where versions and subject formats are concerned, this course takes precedence. For the AADSTS topic in Module 7 and the cleanup topic in Module 8, no verified dedicated video was found, so storyboards are provided instead.
Voice narration notes
The “Voice” tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time; English terms are read with en-US. Results depend on the voices installed in the operating system. The environment that generated this courseware cannot call a TTS service, so no MP3 is embedded; for offline audio, hand the narration script to a TTS service such as Azure AI Speech.
Known limitations and conservative handling
- IDs, GUIDs, domain names, SHAs, revision names and timestamps in “expected output” are example values.
sub_claim_prefixFields come from the GitHub REST docs; if your environment does not return that field, the course provides a fallback that concatenates the creation time and ID, but renamed or transferred repositories must follow the run logs.- When updating a container app, the environment's
managedEnvironments/join/actionassociation authorization check: this course pre-grants it with a custom role to avoidLinkedAuthorizationFailed; if your tenant has a suitable built-in role containing that operation, you can substitute it. - The meanings of AADSTS700211 / 700212 / 70025 / 700024 are common mappings; the specific wording should follow the exact error message and the Microsoft Entra error code docs. The exact error codes and wording for Container Apps concurrency conflicts follow what is actually returned.
- The minimal custom role for read-only what-if (deployments read / validate / whatIf) references the official
ProviderNoRbacdescription and community examples; the minimal operation set follows the official docs. - Custom deployment protection rules are labeled public preview in the GitHub docs, and their behavior may change; the timeout for waiting approvals follows the official docs.
- Costs are order-of-magnitude estimates without specific unit prices; use the Azure pricing calculator and your region.
- Times, counts and error wording in animations are illustrative, used to explain the mechanism.