Azure DevOps Hour 3: Moving to the Cloud (Azure)

Extend the Lesson 2 CI pipeline into a real CD pipeline: passwordless workload identity federation, Environments with approvals, deploying to Container Apps / AKS / App Service, IaC pipelines and troubleshooting cloud deployments
Azure Pipelines (YAML)AzureContainerApps@1KubernetesManifest@1Entra issuer WIFVerified against learn.microsoft.com · 2026-11
Overall learning objectives
  • Choose a deployment target among Azure Container Apps, AKS, App Service and Functions based on team skills, runtime needs and cost, and explain the boundary between push-style CD and GitOps (pull).
  • Create and explain Workload Identity Federation (WIF) of Azure Resource Manager service connections: automatic or manual, app registration or user-assigned managed identity; read the issuer, subject and audience, and convert legacy secret-based service connections.
  • Use Environments + approvals and checks (approvals, branch control, business hours, Invoke Azure Function / REST API, required templates, exclusive lock) to gate production deployments, and read the deployment history.
  • Build a multi-stage pipeline for myapp: build image → push to ACR → deploy to ACA dev (automatic) → prod (approval) → smoke test → automatic rollback to the previous revision on failure.
  • Master the deployment approaches for AKS (KubernetesManifest@1 + ARM service connection / kubelogin) and App Service (deployment slots + swap), plus the IaC pipelines for Bicep what-if and Terraform plan/apply.
  • Independently locate typical cloud deployment failures: AADSTS700213,AADSTS700024,AuthorizationFailed, unauthorized service connection, approval timeout, ACR 401, and clean up all resources after class.
Prerequisites This lesson builds on Lesson 2 (Azure Pipelines CI): reusing the project myapp-lab, repository myapp and pipeline azure-pipelines.yml. The basics of containers and Azure Container Apps (images, ACR, revisions, managed identity for image pulls) are in the Docker course(Lesson 3), and Kubernetes manifests and AKS are in the Kubernetes course(covered there). This lesson only covers how the pipeline deploys them safely. To compare with GitHub Actions OIDC, see the GitHub course.

1-hour time allocation table

#TimeModuleCore contentAnimations / interactionsLab (project myapp-lab · rg-ado-lab)
0Before classWarm-up and Azure setupResource group, ACR, ACA environment, user-assigned managed identity, free parallel jobs, costs and permissions—One-click lab resource creation
100–05From CI to CD: choosing a deployment architectureACA / AKS / App Service / Functions comparison, push vs GitOps (pull), target architectureDeployment target selector + push / pull flow comparisonDraw the target deployment diagram for myapp
205–14Service connections: workload identity federationARM service connection creation methods, Entra issuer vs legacy issuer, subject format, conversion, how tasks obtain tokens, why not use client secretsCore animation: OIDC token exchange (toggle failures such as subject mismatch)Manually create a WIF service connection with a managed identity
314–21Environments, approvals and checksEnvironments, deployment jobs, execution order of the 5 check types, exclusive lock (lockBehavior), deployment historyCheck gating flow simulatormyapp-dev / myapp-prod + approvals + branch control
421–30Deploying to Azure Container AppsDocker@2 / az acr build push, AzureContainerApps@1, revisions and traffic, smoke test and rollbackRevision traffic switching + rollback simulationMulti-stage pipeline dev → prod
530–38Deploying to AKS and App ServiceKubernetesManifest@1, ARM connection vs Kubernetes connection, kubelogin, deployment slots and swapSlot swap animation(optional) App Service slot swap
638–45IaC pipelines (Bicep / Terraform)Bicep what-if, Terraform plan → approval → apply of saved plan, OIDC environment variablesPlan / apply gating and stale plan demoBicep what-if pipeline
745–54Troubleshooting cloud deploymentsAADSTS700213 / 700024 / 700211, AuthorizationFailed, unauthorized service connection, approval timeout, ACR 401Error classifier + interactive troubleshooting treeFault injection and fixes
854–60Cost, cleanup and self-testCost breakdown, free allowances, budget alerts, cleanup order (including federated credentials and service connections)Cost estimatorFull cleanup
—After classCheat sheet · Capstone labmyapp multi-stage CI/CD → ACR → ACA (dev automatic, prod with approval) → smoke test → rollback → cleanupFinal quiz, 12 questionsCapstone lab

Knowledge Coverage Matrix

Target skillModuleKey commands / objectsLabQuiz
Choose the Azure deployment target for a workloadm1ACA / AKS / App Service / Functions decision table✓✓
Create and diagnose WIF service connectionsm2az identity federated-credential create, issuer / subject,azureSubscription:✓✓
Using the service connection identity in scriptsm2 m6AzureCLI@2 + addSpnToEnvironment ($idToken)✓✓
Gate production deployments with environments and checksm3deployment: + environment:, Approvals and checks,lockBehavior✓✓
Build, push the image and deploy to ACAm4Docker@2,az acr build,AzureContainerApps@1,az containerapp ingress traffic set✓✓
Automatic rollback after smoke test failurem4 finalrunOnce.on.failure, revision weights✓✓
Deploy to AKS (no long-lived tokens)m5KubernetesManifest@1 + connectionType: azureResourceManager,kubeloginRead✓
App Service slot deployment and swapm5AzureWebApp@1 (slotName),AzureAppServiceManage@0 (Swap Slots)Optional✓
IaC plan → approval → applym6az deployment group what-if,terraform plan -out / apply tfplan✓✓
Locate identity / permission / authorization / registry errorsm7AADSTS error codes,az role assignment list, yamlauthz✓✓
Estimate costs and fully clean upm8az group delete, delete service connections and federated credentials, budget✓✓

What this lesson does not cover

TopicReasonWhere to learn
AWS deployment (ECR / ECS / EKS / Lambda, AWS OIDC)Belongs to the next lessonLesson 4
Deeper extends templates, canary / rolling deployment strategies, templating multi-environment promotionThis lesson only uses runOnceLesson 5 (multi-stage and deployment strategies)
Organization-level governance of protected resources, Key Vault variable groups, scaling required templatesThis lesson only demonstrates a single checkLesson 6 (governance and security)
Terraform itself (providers, state, modules)Belongs to the Terraform courseTerraform 8-hour course(Lesson 3 Azure, Lesson 5 CI/CD)
Writing Helm charts, Argo CD / Flux GitOps detailsBelongs to the Helm courseHelm 8-hour course
Networking, scaling and probe details for Container Apps / AKSAlready covered in the Docker / K8s coursesDocker course Lesson 3,K8s course

How to use this courseware

10 pages per module
Concepts · Diagrams · Animations · Commands · Labs · Real-world cases · Troubleshooting · Quiz · Voice · Video. Read Concepts / Diagrams / Animations first to build a mental model, then do the Labs.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress, stored in this browser's localStorage (key ado60-part3-progress-v1).
Chinese voice
The “Voice” tab uses the browser's built-in Web Speech API (en-US) to read the narration aloud; without a Chinese voice pack the narration can still be read or passed to a TTS tool.
Version notes (verified 2026-11-15)① Newly created WIF service connections use the Microsoft Entra issuer by default (https://login.microsoftonline.com/<tenant-id>/v2.0), with a subject of the form <Entra prefix>/sc/<organization ID>/<service connection ID>; the legacy Azure DevOps issuer (https://vstoken.dev.azure.com/<organization ID>, subject sc://<organization>/<project>/<service connection>) is deprecated,retires on 2027-07-01 (applies to Azure public cloud, single-tenant apps or managed identities; sovereign clouds and multi-tenant apps are excluded). ② The free allowance for Microsoft-hosted agents (private projects: 1 parallel job, 1 hour per run, 1,800 minutes per month) requires setting up billing for the organization (linking an Azure subscription); after that it takes effect automatically. ③ Public projects are retired; existing public projects will become private in 2027. ④ Azure Pipelines may automatically disable ARM service connections that have not been used for 100 days.

Module 0 · Warm-up and Azure setup

Connect the Lesson 2 CI project to Azure: resource group, ACR, Container Apps environment, user-assigned managed identity
Before class ≈ 15 minutescanadacentralIncurs a small amount of Azure cost
Prerequisites
  • Lessons 1–2 completed: Azure DevOps organization (dev.azure.com), project myapp-lab, Azure Repos repository myapp (including the Docker course's app.py,Dockerfile, Flask listening on 5000,/healthz returns ok, reads APP_VERSION), and the Lesson 2 CI pipeline azure-pipelines.yml.
  • An Azure subscription, and you have rights on the subscription (or at least on the resource group rg-ado-lab) with Owner, or Contributor + User Access Administrator (needed to create role assignments). Being able to create app registrations in Entra ID is better; if not, that is fine, this lesson defaults to user-assigned managed identity.
  • In the Azure DevOps project you need to be Project Administrators, or at least have the administrator role on service connections / environments.
  • Locally or in Cloud Shell: Azure CLI 2.6x+ (az version),containerapp extension,azure-devops extension (installed in Lesson 1).

How this lesson connects to the previous one

Lesson 2 already hasHow this lesson reuses it
CI stage: pytest + docker buildkeep as Build stage, and append after it Push,DeployDev,DeployProd
variable group myapp-commonAdd ACR_NAME,RG,ACA_ENV and other non-secret variables (no longer needs any Azure secrets)
Microsoft-hosted pool ubuntu-latestcontinue using (the image includes Azure CLI and Docker); without free parallel jobs, use the Lesson 2 self-hosted agent

Unified variables (all later commands use them)

cat > ~/ado3.env <<'EOF'
export RG=rg-ado-lab
export LOC=canadacentral
export ACR=acrmyapp$RANDOM          # globally unique, only lowercase letters and digits, 5–50 characters
export ACA_ENV=cae-myapp
export APP_DEV=ca-myapp-dev
export APP_PROD=ca-myapp-prod
export ID_NAME=id-ado-myapp          # user-assigned managed identity used by the service connection
export PULL_ID_NAME=id-myapp-pull    # identity the Container App uses to pull images
export ADO_ORG=https://dev.azure.com/<your organization>
export ADO_PROJECT=myapp-lab
export SC_NAME=sc-azure-myapp
EOF
source ~/ado3.env && echo "ACR=$ACR"     # note the generated ACR name and hard-code it in ado3.env so it does not change next time

Note:$RANDOM It changes on every source; after the first run, please change ACR= to the actual value.

One-time creation of lab resources (about 5 minutes)

source ~/ado3.env
az login                                  # can be omitted in Cloud Shell
az account show --query "{sub:name, id:id, tenant:tenantId}" -o table
az extension add --name containerapp --upgrade
az provider register -n Microsoft.App --wait
az provider register -n Microsoft.OperationalInsights --wait

az group create -n $RG -l $LOC -o table
az acr create -g $RG -n $ACR --sku Basic -o table          # admin user not enabled
az containerapp env create -g $RG -n $ACA_ENV -l $LOC -o table   # automatically creates a Log Analytics workspace

# 1) service connection identity (the pipeline calls ARM with this identity)
az identity create -g $RG -n $ID_NAME -o table
# 2) Container App image-pull identity (runtime, separate from the pipeline identity)
az identity create -g $RG -n $PULL_ID_NAME -o table
PULL_ID=$(az identity show -g $RG -n $PULL_ID_NAME --query id -o tsv)
PULL_PRINCIPAL=$(az identity show -g $RG -n $PULL_ID_NAME --query principalId -o tsv)
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment create --assignee-object-id $PULL_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role AcrPull --scope $ACR_ID -o none
printf 'export PULL_ID=%s\nexport ACR_ID=%s\n' "$PULL_ID" "$ACR_ID" >> ~/ado3.env
Location       Name
-------------  ----------
canadacentral  rg-ado-lab
NAME            RESOURCE GROUP    LOCATION       SKU    LOGIN SERVER
--------------  ----------------  -------------  -----  ------------------------
acrmyapp21877   rg-ado-lab        canadacentral  Basic  acrmyapp21877.azurecr.io

Push a bootstrap image and create the dev / prod Container Apps

source ~/ado3.env
cd ~/myapp                                   # Azure Repos repository cloned in Lessons 1–2
az acr build -r $ACR -t myapp:bootstrap .    # cloud build; if unavailable: docker build + az acr login + docker push
sleep 60                                     # wait for the AcrPull role assignment to take effect (RBAC propagation can take a few minutes)
for APP in $APP_DEV $APP_PROD; do
  az containerapp create -g $RG -n $APP --environment $ACA_ENV \
    --image $ACR.azurecr.io/myapp:bootstrap \
    --target-port 5000 --ingress external \
    --user-assigned $PULL_ID --registry-server $ACR.azurecr.io --registry-identity $PULL_ID \
    --env-vars APP_VERSION=bootstrap \
    --cpu 0.25 --memory 0.5Gi --min-replicas 0 --max-replicas 2 -o none
done
az containerapp revision set-mode -g $RG -n $APP_PROD --mode multiple   # prod uses multiple-revision mode for a 0% traffic pre-release and rollback
az containerapp list -g $RG --query "[].{name:name, fqdn:properties.configuration.ingress.fqdn}" -o table

dev keeps the default single-revision mode (traffic switches automatically once the new revision is ready); prod uses multiple-revision mode, and Module 4 demonstrates 'new revision at 0% traffic → smoke test → shift to 100%'. --min-replicas 0 Scale to zero when idle to save costs.

Microsoft-hosted parallel jobs

Free allowance Private projects: 1 Microsoft-hosted parallel job, up to 1 hour per run, 1,800 minutes per month; requires Organization settings → Billing after linking an Azure subscription it takes effect automatically (official docs, 2026-06). Self-hosted: 1 free parallel job (plus 1 for each active Visual Studio Enterprise subscriber), no time limit. While waiting for the allowance, use the Lesson 2 self-hosted agent (pool: name: Default). Note: runs waiting for approval do not occupy a parallel job.

Costs, permissions and security (read before doing)

ResourceEstimated cost (lab 2–3 hours)Notes
ACR BasicBilled per day, on the order of about 0.17 USD per dayBilling stops after the resource group is deleted
Container Apps (consumption plan)Each subscription gets 180,000 vCPU-seconds, 360,000 GiB-seconds and 2 million requests free each month; this lab usually stays within the free allowanceWith min-replicas 0, idle time is almost free
Log AnalyticsBilled by ingestion volume; lab usage is usually < 1 USDEnvironment created automatically
Managed identities, RBAC, federated credentialsFreebut must be cleaned up to avoid leftover permissions
(optional) App Service S1, AKSBilled hourly, noticeably more expensiveModule 5 optional, delete immediately after completion

Unit prices vary by region and over time; refer to the Azure pricing calculator for current prices. It is recommended to set a 10 USD budget alert on the subscription (Module 8). Security risk: The service connection identity holds rg-ado-lab Contributor on the resource group, which is equivalent to “can do anything in this resource group”. Authorize only the pipelines that need it, and do not tick “Grant access permission to all pipelines”.

Self-check checklist

Module 1 · From CI to CD: choosing a deployment architecture

00:00 – 05:00 · First choose 'where to deploy and who pushes', then write the pipeline
5 minutesACA · AKS · App Service · Functions★★★★☆ Architecture decision
Learning objectives
  • Compare ACA, AKS, App Service and Functions across 6 dimensions (runtime shape, whether a Kubernetes API is needed, scale to zero, operational effort, network isolation, cost model).
  • Explain the difference between push-style CD (the pipeline holds cloud credentials and calls ARM / kube-apiserver directly) and GitOps (an in-cluster agent pulls the desired state from Git), and each one's security boundary.
  • Draw this lesson's target architecture for myapp: Azure Repos → Azure Pipelines → ACR → ACA (dev / prod), and mark which identity each hop uses.
Prerequisites: Lesson 2's stage / job / step; ACA basics from the Docker course. Importance: ★★★★☆

What: what a CD pipeline actually does

CI produces deployable artifacts (a container image plus manifests / IaC); CD turns the artifact into a running version in an environment in a controlled way. Control covers three things: Identity (who may change cloud resources, Module 2),Gating (under what conditions changes are allowed, Module 3),Rollback (how to recover when a change breaks things, Module 4).

Why: why the choice of deployment target shapes the pipeline

  • Deploying to ACA / App Service / Functions: the pipeline calls ARM API (a task or az command); only an ARM service connection is needed.
  • Deploying to AKS: in addition to ARM, you also have to talk to kube-apiserver , which involves Kubernetes RBAC, Entra integration and network reachability for private clusters.
  • Typical cost of picking the wrong target: maintaining an AKS cluster upgrade for a stateless API, or forcing App Service on a system that needs a custom Operator.

How: comparison of four deployment targets (myapp perspective)

DimensionAzure Container AppsAKSApp ServiceAzure Functions
Runtime unitContainer (revision = immutable snapshot)Pod / Deployment, any K8s workloadCode package or container (Web App for Containers)Function (event-triggered), can also be containerized
Kubernetes APINot exposed (underlying platform is managed)Fully exposedNoneNone
ScalingKEDA rules, can scale to 0HPA / KEDA / cluster autoscaling, configured by youManual or automatic scaling by instance plan, cannot go to 0Automatic by event; consumption plan can go to 0
Release mechanismRevisions + traffic weights / labelsRolling update, canary (self-built or via mesh)Deployment slots + swap (Standard and above)Deployment slots (on some plans)
Operational effortLowHigh (version upgrades, node pools, add-ons)LowLow
Pipeline taskAzureContainerApps@1 or AzureCLI@2KubernetesManifest@1,HelmDeploy@1AzureWebApp@1 / AzureWebAppContainer@1AzureFunctionApp@2
Suitable forMicroservices, APIs, background workers; want containers without managing a clusterPlatform teams; need CRDs / Operators / service mesh / fine-grained networkingTraditional web apps; need slot swap and built-in authenticationEvent-driven, short tasks, glue code

Push-style (push) CD vs GitOps (pull)

Push-style (this lesson's main thread)GitOps (Flux / Argo CD)
Who makes the changeThe pipeline agent calls ARM / kubectlA controller in the cluster continuously pulls from Git and reconciles
Where the credentials areAzure DevOps service connection (WIF, short-lived tokens)Inside the cluster; the pipeline only needs to write to Git (and push images)
DriftOnly overwritten at deployment time; later manual changes are not correctedContinuously corrects drift
GatingEnvironments approvals and checks (Module 3)Git PR approval + branch policy
Applies toAny Azure service (ACA, App Service, Functions, AKS)Mainly Kubernetes (Flux extension for AKS)

When: how to choose

  • The team has no dedicated platform engineer and the app is a stateless HTTP / queue consumer → ACA (this lesson's main thread).
  • Already have an AKS platform shared by multiple teams and need GitOps → AKS + Flux / Argo CD; the pipeline builds the image and updates the image tag in Git (Helm course, Lesson 5).
  • Legacy .NET / Java web app that needs 'warm up, then switch instantly' → App Service deployment slots.
  • Scheduled tasks, small functions triggered by Blob / queues → Functions.
Common misconceptions① 'GitOps needs no CI credentials at all': the pipeline still has to push images to ACR (needs AcrPush) and write to Git. ② 'ACA is a small AKS, so you can use kubectl': ACA does not expose the Kubernetes API. ③ 'App Service slots are free': slots share the instances of the same App Service plan as production and need the Standard tier or above. ④ 'Push-style CD is always insecure': with WIF, least privilege and environment checks, credentials are short-lived and gated on the resource, so the risk is controllable.

Architecture diagram: myapp target deployment for this lesson

Azure Reposmyapp · main Azure Pipelines Build → Push → DeployDev → DeployProd Service connection sc-azure-myapp (WIF) Environments: myapp-dev / myapp-prod prod: approval + branch control + exclusive lock Microsoft Entra IDFederated credential → access token ACR acrmyappXXXXmyapp:$(Build.BuildId)Pipeline identity: AcrPushPull identity: AcrPull ACA environment cae-myapp (canadacentral) ca-myapp-devSingle-revision modeAuto-deploys on every main build ca-myapp-prodMultiple-revision modeNew revision 0% → smoke test → 100% Azure Resource ManagerRBAC: rg-ado-lab pull (managed identity)
Figure 1-1: the two identities are separate: the pipeline identity (changes resources, pushes images) and the runtime pull identity (read-only on ACR)

Comparison diagram: push-style vs GitOps

Push-style (Azure Pipelines → target) Git commit PipelineHolds short-lived token ARM / AKS Changes are pushed from outside in; gate = environment checks GitOps (in-cluster controller pulls) PipelinePush image + update Git Config repository Flux / Argo CD(inside AKS) Controller pulls and continuously reconciles; gate = PR approval
Figure 1-2: push-style suits all Azure PaaS; GitOps is mainly for Kubernetes

Flow diagram: the four stages of this lesson's pipeline

Buildpytest · docker build PushACR (WIF service connection) DeployDevenv myapp-dev · no checks DeployProdenv myapp-prod · approval
Figure 1-3: only the main branch enters Deploy; PR builds only run Build

Interactive: deployment target selector

Tick your workload's characteristics and the selector gives a weighted recommendation (the rules match the comparison table on the Concepts tab; for teaching reference only).

Step-by-step animation: one push-style deployment vs one GitOps deployment

Click 'Play'.

Commands to check the current state before choosing

CommandPurposeNotes
az containerapp env list -o tableList ACA environmentsThe environment is the network and logging boundary
az containerapp show -g $RG -n $APP_PROD --query properties.configuration.activeRevisionsModeCheck revision modeSingle / Multiple (label mode is in preview)
az aks list -o tableIs there an existing AKS platform?Reuse it first when a platform team exists
az appservice plan list --query "[].{n:name,sku:sku.name}" -o tableApp Service plan and tierDeployment slots require Standard or above
az devops invoke --area distributedtask --resource environments ...Query environments (REST)The more common way is the Web UI: Pipelines → Environments
source ~/ado3.env
az containerapp list -g $RG \
  --query "[].{name:name, mode:properties.configuration.activeRevisionsMode, fqdn:properties.configuration.ingress.fqdn}" -o table
Name           Mode      Fqdn
-------------  --------  ------------------------------------------------------------
ca-myapp-dev   Single    ca-myapp-dev.kindpond-1a2b3c4d.canadacentral.azurecontainerapps.io
ca-myapp-prod  Multiple  ca-myapp-prod.kindpond-1a2b3c4d.canadacentral.azurecontainerapps.io

How to verify: The two apps are in the same environment, so their FQDN suffix is the same. Common errors:'containerapp' is misspelled → install the extension. Production use: In CD design reviews, first list the existing targets and release mechanisms.

Lab 1: draw and confirm the myapp deployment topology (about 4 minutes)

Goal: confirm that both the dev and prod targets are reachable, and record the FQDNs in the variable group for later stages. Cost: almost zero.
Get the FQDN
source ~/ado3.env
DEV_FQDN=$(az containerapp show -g $RG -n $APP_DEV --query properties.configuration.ingress.fqdn -o tsv)
PROD_FQDN=$(az containerapp show -g $RG -n $APP_PROD --query properties.configuration.ingress.fqdn -o tsv)
curl -s -o /dev/null -w "%{http_code}\n" https://$DEV_FQDN/
200
Write to variable group myapp-common (non-secret variables, referenced in the pipeline as $(ACR_NAME) , etc.)
az devops configure --defaults organization=$ADO_ORG project=$ADO_PROJECT
VG=$(az pipelines variable-group list --group-name myapp-common --query "[0].id" -o tsv)
for kv in "ACR_NAME=$ACR" "RG=$RG" "ACA_ENV=$ACA_ENV" "APP_DEV=$APP_DEV" "APP_PROD=$APP_PROD" "PULL_ID=$PULL_ID"; do
  az pipelines variable-group variable create --group-id $VG --name ${kv%%=*} --value "${kv#*=}" -o none
done
az pipelines variable-group variable list --group-id $VG -o table

If the Lesson 2 variable group was not created: az pipelines variable-group create --name myapp-common --variables RG=$RG.

Draw Figure 1-1 on paper (or a whiteboard), marking three identities: pipeline → Entra (federated credential), pipeline → ARM (Contributor), Container App → ACR (AcrPull).
Cleanup: this lab did not create any new resources.

Case 1: moving back from AKS to ACA reduced operational effort

Background: A 6-person team ran 12 stateless APIs on self-managed AKS, spending a week each quarter on cluster upgrades, node images and ingress controller patches.

Approach: After evaluation they found no use of CRDs or meshes, so they migrated to ACA; releases changed from Helm to AzureContainerApps@1 + revision traffic. KEDA rules were kept (natively supported by ACA).

Lesson learned: Decide based on whether you need the Kubernetes API, not on whether you might need it someday.

Case 2: push-style + GitOps hybrid

Background: The platform team uses Flux to manage shared components on AKS, while the application teams want to keep Azure Pipelines approvals.

Approach: After prod approval passes, the pipeline does only two things: pushes images to ACR and commits an image tag change to the config repository (the PR is auto-merged). Flux performs the actual deployment. Approval records live in the Environments deployment history; change records live in Git.

Case 3: App Service slots solve cold starts

Background:.NET app startup takes 90 seconds; direct deployment showed users a 503.

Approach: Deploy to staging slot → warm-up requests → swap (Module 5). Before the swap, App Service sends warm-up requests to the target slot's instances, so there is no cold start after switching.

Common issues in the selection and architecture stage

No matching deployment slot / slots are not supported for the App Service plan SKU

Cause: Free / Shared / Basic tiers do not support deployment slots.

az appservice plan show -g $RG -n <plan> --query sku

Fix: Upgrade to Standard (S1) or Premium; or switch to ACA revision traffic.

ACA app: kubectl cannot connect / cannot find kubeconfig

Cause: ACA does not expose the Kubernetes API.

Fix: Use az containerapp logs show,az containerapp exec,az containerapp revision list; workloads that need kubectl should choose AKS.

In a GitOps environment, the pipeline's deployment gets reverted after it runs

Cause: Flux / Argo CD continuously reconcile the desired state in Git; direct kubectl apply changes made by the pipeline are treated as drift.

Fix: Pick one: the pipeline changes only Git, or exclude that namespace from GitOps management.

dev deployment succeeds, but prod deployment reports “resource not found”

Cause: The prod resources were not created through IaC, or are in another subscription / resource group, while the service connection's scope only covers the dev resource group.

az containerapp show -g rg-ado-lab -n ca-myapp-prod --query id -o tsv

Fix: Create the environments with IaC first (Module 6); use different service connections for different subscriptions.

Command-line questions
1. Write a command that lists the revision mode of all Container Apps in a resource group.
az containerapp list -g rg-ado-lab --query "[].{n:name,m:properties.configuration.activeRevisionsMode}" -o table
2. How do you confirm whether an App Service plan can use deployment slots?
az appservice plan show -g rg-ado-lab -n plan-myapp --query "sku.{tier:tier,name:name}"

Slots are supported when the tier is Standard, the Premium series or Isolated (Free / Shared / Basic are not supported).

Scenario analysis questions
A company has 40 microservices: 5 need custom Operators and 35 are ordinary HTTP APIs; there are only 2 platform engineers. How should the deployment targets and CD approach be designed?

Put the 5 Operator-dependent services on a small AKS cluster (consider AKS Automatic) using Flux GitOps; put the 35 HTTP APIs on ACA using push-style deployment from Azure Pipelines plus revision traffic. Both groups are gated through the same WIF service connections and Environments approvals. This limits the Kubernetes operations footprint to where it is truly needed.

Verified teaching videos

▶
AKS vs App Service vs Container Apps: Which Service Should You Choose? — Brayan Ortiz
English · Comparison of three container hosting targets
▶
Azure Container Apps (ACA) vs Azure Container Instances (ACI) vs Azure Kubernetes Service (AKS) — MadeForCloud
English · Container service selection
▶
DevOps Master Class - Introduction — John Savill's Technical Training
English · DevOps overview series entry

The titles and channels above were verified via the YouTube oEmbed endpoint (2026-11-15); duration and publish dates are not returned by oEmbed and are not listed. The videos were recorded before this lesson, so for product details follow this lesson and the official docs.

Official docs

Video storyboard

Shot 1 · 0:00–0:20
Visual: the end of a CI pipeline is an image icon, with a question mark pointing to four cloud icons.
Narration: after CI produces the image, CD must answer three questions: where to deploy, with which identity, and who approves.
Shot 2 · 0:20–1:00
Visual: four columns of cards for ACA, AKS, App Service and Functions, with comparison dimensions lighting up row by row.
Narration: the most important question is whether you need the Kubernetes API. If not, prefer ACA or App Service.
Shot 3 · 1:00–1:40
Visual: split screen; on the left, a pipeline arrow pushes into the cloud; on the right, an in-cluster controller pulls from Git.
Narration: push-style means the pipeline holds a short-lived token and deploys directly; GitOps means an in-cluster controller pulls and continuously corrects drift.
Shot 4 · 1:40–2:10
Visual: the lesson's architecture diagram appears layer by layer, with the three identity connections flashing.
Narration: this lesson's myapp uses push-style deployment to Container Apps: the pipeline identity changes resources, and the runtime identity only pulls images.
or score ≥ 70% in the “Quiz” tab

Module 2 · Service connections: workload identity federation

05:00 – 14:00 · No Azure secrets are stored in the pipeline any more: Azure DevOps issues an OIDC token, and Entra exchanges it for a short-lived access token using the federated credential
9 minutesEntra issuer (new default)★★★★★ Core of this lesson
Learning objectives
  • State the recommended ways to create an ARM service connection: App registration (automatic) + WIF,managed identity (create a WIF credential for an existing user-assigned managed identity),app registration or managed identity (manual), and the permissions each one needs.
  • Read the three elements of a federated credential: issuer,subject,audience (api://AzureADTokenExchange), and distinguish the new Entra issuer from the deprecated Azure DevOps issuer (retires 2027-07-01).
  • Explain a token exchange: the task requests an ID token from Azure DevOps → submits it with client_assertion to Entra → Entra validates it → returns an access token → calls ARM → ARM authorizes according to RBAC.
  • Convert a legacy secret-based service connection to WIF (revertible within 7 days), and know which cases the conversion tool cannot handle.
  • Use the service connection in AzureCLI@2,AzureWebApp@1,AzureContainerApps@1 and similar tasks; in a script, get addSpnToEnvironment via $idToken and pass it to tools such as Terraform.
Prerequisites: Lesson 1 project permissions; basic OAuth2 / JWT concepts (explained in this module). Importance: ★★★★★

What: what a service connection is

A service connection is a protected resource in an Azure DevOps project that stores how to connect to an external system as a given identity. An ARM service connection stores: the tenant ID, the identity's client ID (the appId of the app registration or the clientId of the managed identity), the scope (subscription / management group / ML workspace, optionally a resource group), and the authentication scheme. In YAML it is referenced by name: azureSubscription: sc-azure-myapp (a service connection cannot be specified with a variable).

Why: why client secrets are no longer used

IssueClient secret (service principal key)Workload identity federation (WIF)
Exposure surfaceA long-lived password is stored in Azure DevOps; scripts echo, logs and third-party tasks can all leak itThere is no long-lived secret to leak; the ID token exists only briefly within one job
ExpiryWhen the secret expires, all pipelines fail (AADSTS7000215: Invalid client secret provided)No rotation needed
TraceabilityWhoever obtains the key can log in from anywhereThe token's subject is bound to a specific service connection and can only be issued by Azure DevOps
Official recommendationKept only for backward compatibilityRecommended: create everything new with WIF; try converting the old ones first

How: creation methods and required permissions

MethodWho creates the identityRequired permissionsApplies to
App registration (automatic) + Workload identity federationAzure DevOps creates the app registration, federated credential and role assignment for youSubscription Owner; can create app registrations in EntraFastest path for individuals / small teams (not applicable to Azure Stack, US Gov)
Managed identity (create a WIF credential for an existing user-assigned managed identity)You create the UAMI in advance; Azure DevOps automatically adds the federated credentialCan modify that UAMI; can assign rolesUse when you have no app registration permissions; this lesson defaults to
App registration or Managed identity (manual)You create the identity, federated credential and role assignments yourselfAzure DevOps: service connection administrator; Azure: Managed Identity Contributor (or Federated Credential Contributor) + role assignment permissionCross-tenant, separated permissions, automation (scripts / Terraform must use creationMode: Manual)
Other (not recommended)App registration + secret, agent-assigned managed identity (self-hosted VM), publish profile — kept only for compatibility and edge cases

Three elements of a federated credential (must match the values shown in Azure DevOps exactly)

FieldMicrosoft Entra issuer (default for new connections)Azure DevOps issuer (deprecated, retires 2027-07-01)
Issuerhttps://login.microsoftonline.com/<Entra tenant ID>/v2.0https://vstoken.dev.azure.com/<organization ID>
Subject<Entra prefix>/sc/<organization ID>/<service connection ID> (the prefix is generated by Entra, of the form /eid1/c/pub/t/…/a/…, the value shown on the service connection edit page is authoritative)sc://<organization name>/<project name>/<service connection name>
Audienceapi://AzureADTokenExchange
Who the token can be exchanged withOnly Microsoft Entra access tokens can be exchangedCan be exchanged with Entra or other identity providers (such as AWS)
Impact of renamingsubject uses IDs; organization / project / connection Renaming does not break trustAfter renaming the organization, project or connection, the subject no longer matches → AADSTS700213 / AADSTS70021

Deprecation scope: connections using single-tenant apps or managed identities WIF service connections in Azure public cloud; sovereign clouds and multi-tenant apps (signInAudience: AzureADMultipleOrgs) are out of this scope and continue to use the Azure DevOps issuer. Affected connections are flagged in the list and configuration UI; select Update Convert.

How tasks use service connections

  • Built-in Azure tasks (AzureCLI@2,AzurePowerShell@5,AzureWebApp@1,AzureContainerApps@1,AzureResourceManagerTemplateDeployment@3,KubernetesManifest@1,Docker@2 , etc.) all support WIF: the task requests an ID token and exchanges it for an access token automatically at runtime. AzureFileCopy requires v6,Kubernetes requires v1,KubernetesManifest requires v1.
  • AzureCLI@2: the task first runs az login --service-principal --federated-token … (requires Azure CLI 2.30+) with the federated token, then runs your script; inside the script, az commands run directly under the service connection identity.
  • Third-party tools (Terraform, Pulumi, azd): in AzureCLI@2 set addSpnToEnvironment: true, so the script can read $servicePrincipalId,$tenantId,$idToken (with WIF, idToken is provided instead of a secret), and then pass it to the tool (Module 6).
  • Marketplace extension tasks require the publisher to support WIF, otherwise they report Identity not found / Could not fetch access token for Azure.

When: which identity type to choose

  • If you can create app registrations and deploy only one subscription → the automatic method is fastest.
  • If the enterprise prohibits ordinary users from creating app registrations, or identities must be centrally managed by the Azure team → user-assigned managed identity (automatic or manual).
  • Need IaC to manage service connections (Terraform azuredevops provider / scripts) → manual mode, in order: identity → service connection (obtain issuer/subject) → federated credential → role assignment.
  • dev and prod use different service connections and identities: the prod identity has permissions only on the prod resource group, and approval / required template checks are added on the service connection (Module 3).
Common misconceptions① 'WIF tokens can be used anywhere': the ID token's audience is fixed to api://AzureADTokenExchange, and it can only be used for exchange with Entra; the subject is bound to one service connection. ② 'After conversion the service connection name is unchanged, so the pipeline needs no changes': correct, the YAML does not need modifying; but custom scripts that read servicePrincipalKey steps will break and must switch to idToken. ③ 'Managed identities can only be used by Azure VMs': a user-assigned managed identity can also serve as a WIF identity; where the agent runs is irrelevant. ④ 'A service connection needs the Owner role to deploy': follow least privilege; this lesson only needs resource group Contributor plus AcrPush on ACR.

Sequence diagram: one WIF token exchange

Task on the agent Azure DevOps Microsoft Entra ID ARM ① request ID token (job token + service connection ID) ② return JWT: iss / sub / aud=api://AzureADTokenExchange ③ POST /oauth2/v2.0/token client_id + client_assertion=JWT (jwt-bearer) ④ look up the identity's federated credentialissuer match? subject match?audience match? signature valid?not expired? tenant policy allows? ⑤ access token (aud=https://management.azure.com, short-lived) ⑥ PUT …/containerApps/ca-myapp-dev Authorization: Bearer … ⑦ RBAC check passes → 200/201; otherwise 403 AuthorizationFailed
Figure 2-1 In Entra issuer mode, the ID token's issuer is your tenant; a mismatch on any item in ④ returns an AADSTS7002xx error

Object relationship diagram: who points to whom

Service connection sc-azure-myapp scheme: WorkloadIdentityFederation tenantid · serviceprincipalid(clientId) scope: subscription / rg-ado-lab → generates issuer + subject Check: approvals / required templates UAMI id-ado-myapp clientId · principalId Federated credential fic-ado-myapp: issuer = value given by the service connection subject = value given by the service connection audience = api://AzureADTokenExchange Azure RBAC Contributor @ rg-ado-lab AcrPush @ acrmyappXXXX (principalId is the assignee)
Figure 2-2 Two-way relationship: the service connection references the identity (clientId), and the identity's federated credential references the service connection (subject), so the service connection must be created before the federated credential

Flowchart: the 5 manual steps (order must not change)

① Create UAMIget clientId ② Create service connection (draft)get issuer/subject ③ Add federated credentialOther issuer ④ Role assignmentContributor / AcrPush ⑤ Finish setupVerify and save
Figure 2-3 from the official 'Set a workload identity service connection' (manual) flow

Core animation: workload identity federation token exchange

Choose the issuer type first, then the scenario, and then play. The highlighted box is the component handling the current request; the terminal shows the real request / log / error visible at that step. JWT contents are illustrative (decoded, IDs redacted).

Issuer:
Scenario:
AzureCLI@2Agent (in job) Azure DevOpsOIDC token issuance ID token (JWT)iss / sub / aud Microsoft Entra IDValidate federated credential UAMI id-ado-myappFederated credential fic-ado-myapp Access tokenaud=management.azure.com Azure Resource ManagerRBAC: rg-ado-lab
Ready.
Key observations Switch to 'Azure DevOps (deprecated)' and then pick 'subject mismatch': the old-format subject contains the organization / project / connection names, and renaming any of them causes a mismatch; the Entra format uses IDs, so renaming has no effect.

Core commands and YAML

Command / syntaxPurposeKey parameters / notes
az identity create -g $RG -n $ID_NAMECreate a user-assigned managed identityNote clientId (for the service connection) and principalId (for the role assignment)
az devops service-endpoint create --service-endpoint-configuration sc.jsonCreate a service connection with a scriptscheme: WorkloadIdentityFederation,creationMode: Manual; output workloadIdentityFederationIssuer / Subject
az identity federated-credential createAdd a federated credential to the UAMI--issuer,--subject,--audiences api://AzureADTokenExchange
az ad app federated-credential create --id APPID --parameters cred.jsonAdd a federated credential to the app registrationApp registration method
az role assignment create --assignee-object-id … --assignee-principal-type ServicePrincipalGrant RBACUse principalId and explicitly specify the type to avoid graph query delay
az devops service-endpoint list --query "[].{n:name,s:authorization.scheme}"Inventory which connections still use secretsServicePrincipal = secret/certificate,WorkloadIdentityFederation = WIF
AzureCLI@2 + addSpnToEnvironment: trueGet identity information in a scriptEnvironment variables servicePrincipalId,tenantId,idToken
source ~/ado3.env
CLIENT_ID=$(az identity show -g $RG -n $ID_NAME --query clientId -o tsv)
PRINCIPAL_ID=$(az identity show -g $RG -n $ID_NAME --query principalId -o tsv)
SUB_ID=$(az account show --query id -o tsv); TENANT_ID=$(az account show --query tenantId -o tsv)
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role Contributor --scope /subscriptions/$SUB_ID/resourceGroups/$RG -o none
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role AcrPush --scope $ACR_ID -o none
printf 'export CLIENT_ID=%s\nexport PRINCIPAL_ID=%s\nexport SUB_ID=%s\nexport TENANT_ID=%s\n' $CLIENT_ID $PRINCIPAL_ID $SUB_ID $TENANT_ID >> ~/ado3.env
source ~/ado3.env
PROJECT_ID=$(az devops project show -p $ADO_PROJECT --query id -o tsv)
cat > sc.json <<EOF
{
  "data": { "subscriptionId": "$SUB_ID", "subscriptionName": "$(az account show --query name -o tsv)",
            "environment": "AzureCloud", "scopeLevel": "Subscription", "creationMode": "Manual" },
  "name": "$SC_NAME", "type": "AzureRM", "url": "https://management.azure.com/",
  "authorization": { "scheme": "WorkloadIdentityFederation",
                     "parameters": { "tenantid": "$TENANT_ID", "serviceprincipalid": "$CLIENT_ID" } },
  "isShared": false, "isReady": true,
  "serviceEndpointProjectReferences": [ { "projectReference": { "id": "$PROJECT_ID", "name": "$ADO_PROJECT" }, "name": "$SC_NAME" } ]
}
EOF
az devops service-endpoint create --service-endpoint-configuration sc.json --query authorization.parameters -o json
{
  "serviceprincipalid": "00001111-aaaa-2222-bbbb-3333cccc4444",
  "tenantid": "aaaabbbb-0000-cccc-1111-dddd2222eeee",
  "workloadIdentityFederationIssuer": "https://login.microsoftonline.com/aaaabbbb-0000-cccc-1111-dddd2222eeee/v2.0",
  "workloadIdentityFederationIssuerType": "EntraID",
  "workloadIdentityFederationSubject": "/eid1/c/pub/t/…/a/…/sc/<organization ID>/<service connection ID>"
}
SC_ID=$(az devops service-endpoint list --query "[?name=='$SC_NAME'].id" -o tsv)
ISSUER=$(az devops service-endpoint show --id $SC_ID --query authorization.parameters.workloadIdentityFederationIssuer -o tsv)
SUBJECT=$(az devops service-endpoint show --id $SC_ID --query authorization.parameters.workloadIdentityFederationSubject -o tsv)
az identity federated-credential create -g $RG --identity-name $ID_NAME --name fic-ado-myapp \
  --issuer "$ISSUER" --subject "$SUBJECT" --audiences api://AzureADTokenExchange -o table
az identity federated-credential list -g $RG --identity-name $ID_NAME --query "[].{n:name,iss:issuer,sub:subject}" -o table
steps:
- task: AzureCLI@2
  displayName: Who am I
  inputs:
    azureSubscription: sc-azure-myapp      # service connection name (cannot be a variable)
    scriptType: bash
    scriptLocation: inlineScript
    addSpnToEnvironment: true              # exposes servicePrincipalId / tenantId / idToken
    inlineScript: |
      az account show --query "{user:user.name, type:user.type, sub:name}" -o table
      echo "clientId=$servicePrincipalId tenant=$tenantId idToken length=${#idToken}"   # do not echo the token itself
      az containerapp list -g $(RG) -o table
User                                  Type              Sub
------------------------------------  ----------------  ----------------
00001111-aaaa-2222-bbbb-3333cccc4444  servicePrincipal  Contoso Lab Sub
clientId=00001111-aaaa-2222-bbbb-3333cccc4444 tenant=aaaabbbb-… idToken length=1342

How to verify:user.type For servicePrincipal,user.name , equals the managed identity's clientId. Common errors: Federated credential was created on the wrong identity (clientId mismatch) → AADSTS70025 or AADSTS700213. Production use: Add a 'Who am I' step at the start of every deployment pipeline, so that when troubleshooting you can see at a glance which identity is in use.

Lab 2: create a WIF service connection with a managed identity and verify it (about 8 minutes)

Goal and environment: create sc-azure-myapp (UAMI id-ado-myapp, scope subscription, role only in rg-ado-lab), authorize it for the myapp pipeline, and run one 'Who am I'. Cost: 0.
Role assignment: run segment 1 of the 'Commands' tab (Contributor @ rg-ado-lab, AcrPush @ ACR).
Create the service connection (choose one)
  • Web UI: Project settings → Service connections → New service connection → Azure Resource Manager → Identity type: App registration or Managed identity (manual) → Credential: Workload identity federation → enter tenant ID → Next → copy Issuer and Subject identifier → enter subscription, Application (client) ID = UAMI clientId → do not tick Grant access permission to all pipelines → Keep as draft.
  • CLI: run segment 2 of the 'Commands' tab.
Add federated credential: run segment 3 (or in the Azure portal: managed identity → Settings → Federated credentials → Add credential → Other issuer → paste Issuer / Subject → Type: choose Explicit subject identifier). Back to the Azure DevOps draft → Finish setup → Verify and save.
N              Iss                                                                  Sub
-------------  -------------------------------------------------------------------  ---------------------------------
fic-ado-myapp  https://login.microsoftonline.com/aaaabbbb-…/v2.0                   /eid1/c/pub/t/…/sc/…/…
Authorize for the pipeline: service connection → ⋮ → Security → Pipeline permissions → + → select the myapp pipeline. (You can also click Permit on the run page during the first run.).
Verify: create a new branch feature/whoami, at azure-pipelines.yml end with the temporary job from segment 4 of the 'Commands' tab, and run that branch manually. The log should show servicePrincipal and the two Container Apps.
Fault drill: delete the federated credential and run again, then record the error (it should be AADSTS70025 or “no matching federated identity record”), then re-run segment 3 to restore it.
az identity federated-credential delete -g $RG --identity-name $ID_NAME -n fic-ado-myapp --yes
Cleanup: keep the service connection and identity for later modules; delete the feature/whoami branch. For full cleanup see Module 8.

Case 1: key expiry caused all releases to fail on Friday night

Symptom: 40 pipelines failed at the same time with AADSTS7000215: Invalid client secret provided. The secret of the automatically created service connection expired, and nobody received an alert.

Handling: On the service connection page, select Convert (when the key has expired, the UI offers a conversion option), which restores service within minutes; then use the official PowerShell script to batch-convert all creationMode=Automatic connections used by single projects. After conversion, you can Revert revert within 7 days.

Limits: Manually created connections (Azure DevOps has no permission to modify their credentials) and connections shared across projects cannot use the conversion tool; add federated credentials through the manual process.

Case 2: all deployments failed after the project was renamed

Symptom: After renaming the project from Shop to Commerce , the old-style manually created WIF connection reports AADSTS70021: No matching federated identity record found … Assertion Subject: sc://contoso/Commerce/sc-prod.

Cause: The subject of the old Azure DevOps issuer contains the project name, while the federated credential on the UAMI is still sc://contoso/Shop/sc-prod.

Handling: Update the connection to the Entra issuer and update the federated credential with the new issuer / subject (the subject is based on IDs, so future renames will not affect it).

Case 3: enterprise prohibits creating app registrations

Symptom: Automatic creation reports Insufficient privileges to complete the operation in Microsoft Graph.

Handling: The Azure team creates the UAMI in a controlled subscription (managed by Terraform) and grants Managed Identity Federated Credential Contributor to the platform pipeline; application teams create service connections using manual mode, and the platform pipeline adds the federated credentials. No Entra administrator is needed throughout.

Common errors and fixes

AADSTS700213: No matching federated identity record found for presented assertion subject

Cause: There is no federated credential, or the federated credential's subject does not match the sub in the ID token (a character was missed when copying, an old-format name was changed, or it was created on a different identity).

az devops service-endpoint show --id $SC_ID --query "authorization.parameters.{iss:workloadIdentityFederationIssuer,sub:workloadIdentityFederationSubject,client:serviceprincipalid}"
az identity federated-credential list -g $RG --identity-name $ID_NAME --query "[].{iss:issuer,sub:subject,aud:audiences[0]}" -o json

Fix: Compare the issuer / subject on both sides character by character; if they differ, delete and recreate the federated credential.

AADSTS700211: No matching federated identity record found for presented assertion issuer

Cause: Issuer mismatch. Common when the connection was switched from the Azure DevOps issuer to the Entra issuer, but the federated credential on the identity is still https://vstoken.dev.azure.com/… (it is not updated automatically if Azure DevOps did not create the identity).

Fix: Edit and save the service connection to get the current issuer, then add a federated credential with the new value (old and new can coexist; delete the old one after the transition).

AADSTS700024: Client assertion is not within its valid time range

Cause: The ID token (client assertion) has a very short validity period. The script did a lot of work first (e.g. a build of more than 10 minutes) before requesting the access token for the first time; or a long job exceeded about 1 hour, so the access token expired and had to be exchanged again.

Fix (official recommendations): Put the commands that need the token at the start of the script (the token is cached); for jobs longer than 1 hour, switch to 'WIF + managed identity' (managed identity tokens last about 24 hours); or split the long task into several steps.

AADSTS70025: Client application has no configured federated identity credentials

Cause: No federated credential exists on the identity corresponding to the clientId referenced by the service connection.

Fix: Confirm that serviceprincipalid is the UAMI's clientId (not principalId / objectId), and add a federated credential on that identity.

AADSTS700223 / AADSTS700238: workload identity federation is constrained or disabled

Cause: Tenant policy restricts WIF (disabled, or only specific issuers / identity types are allowed).

Fix: Ask an Entra administrator to allow your organization's issuer, or switch to a managed identity as the federated identity.

UnrecognizedArgumentError: unrecognized arguments: --federated-token

Cause: The Azure CLI on the self-hosted agent is too old (WIF requires 2.30+).

az version --query '"azure-cli"'

Fix: Upgrade the Azure CLI on the agent and restart the agent service.

Identity not found / Could not fetch access token for Azure

Cause: A task version that does not support WIF is used (such as AzureFileCopy@4,KubernetesManifest@0) or a Marketplace task.

Fix: Upgrade the major task version (AzureFileCopy@6, KubernetesManifest@1, Kubernetes@1), or switch to AzureCLI@2 script implementation.

Command-line questions
1. Write a command that lists the ARM service connections in the project that still use a secret (non-WIF).
az devops service-endpoint list --query "[?type=='azurerm' && authorization.scheme=='ServicePrincipal'].{name:name, mode:data.creationMode}" -o table

creationMode For Automatic connections used only in this project, you can use Convert directly; for Manual ones, add federated credentials through the manual process.

2. Add a federated credential to the app registration (appId=APPID), with issuer/subject set to $ISSUER / $SUBJECT respectively.
cat > cred.json <<EOF
{ "name": "fic-for-sc", "issuer": "$ISSUER", "subject": "$SUBJECT", "audiences": ["api://AzureADTokenExchange"] }
EOF
az ad app federated-credential create --id APPID --parameters cred.json
Scenario analysis questions
Security team requirement: the prod deployment identity must be fully isolated from dev, and no one editing the YAML should be able to give a PR build prod permissions. How would you design this?

① Two UAMIs: id-ado-dev (dev resource group Contributor),id-ado-prod (prod resource group Contributor), each with one WIF service connection. ② sc-azure-prod authorize only the release pipeline, and add to the service connection branch control (refs/heads/main),required template and approval checks, which sit on the resource so editing the YAML cannot bypass them. ③ The prod deployment job is placed only in the condition: eq(variables['Build.SourceBranch'], 'refs/heads/main') stage. ④ Do not tick 'Grant access permission to all pipelines' on either connection. ⑤ Monitor changes to service connections and checks using audit logs (Lesson 6).

Verified teaching videos

▶
Azure DevOps Workload Identity Federation with Azure Overview. NO MORE SECRETS! — John Savill's Technical Training
English · token flow, creating a new connection, converting an old connection, managed identity (recorded before the switch to the Entra issuer; the issuer/subject format follows this lesson)
▶
Workload Identity Protection with Azure AD Identity Protection — John Savill's Technical Training
English · Extension: risk protection for workload identities

The titles and channels above were verified via the YouTube oEmbed endpoint (2026-11-15).

Official docs

Video storyboard

Shot 1 · 0:00–0:25
Visual: a key (client secret) is stuck to the pipeline, then a red 'expired' stamp appears on the key.
Narration: in the past, pipelines logged in to Azure with a long-lived client secret, which can leak and expire.
Shot 2 · 0:25–1:05
Visual: the task asks Azure DevOps for a pass (JWT), with iss, sub and aud written on it.
Narration: with workload identity federation, the task first requests a short-lived ID token from Azure DevOps; the token states who issued it, which service connection it represents, and who it is for.
Shot 3 · 1:05–1:45
Visual: the Entra gatekeeper compares the pass with the register (federated credential) item by item, and three checkmarks light up in turn.
Narration: Entra checks whether the issuer, subject and audience exactly match the federated credential on the identity; the signature and validity period must also pass, and then it issues an access token.
Shot 4 · 1:45–2:15
Visual: the access token enters ARM, and on the RBAC table the Contributor row lights up green. In another scene, the subject differs by one letter and the gatekeeper shows a red light, AADSTS700213.
Narration: any mismatch is rejected. The most common causes are a copy error in the subject, or a rename.
Shot 5 · 2:15–2:40
Visual: the old-format sc://org/project/sc is crossed out and replaced with the Entra format.
Narration: new connections use the Entra issuer by default; the old Azure DevOps issuer retires on July 1, 2027, so convert early.
or score ≥ 70% in the “Quiz” tab

Module 3 · Environments, approvals and checks

14:00 – 21:00 · Gates are written on the resource rather than in the YAML: anyone editing the pipeline cannot bypass the checks
7 minutes5 check types · lockBehavior★★★★★ Essential for production
Learning objectives
  • Understand what an Environment is: a logical collection of deployment targets + a protected resource + deployment history; be able to write deployment in a job to reference it.
  • Name the 5 categories of checks and their execution order: static checks → pre-check approval → dynamic checks → post-check approval → exclusive lock.
  • Configure approvals (approvers, instructions, no self-approval, timeout, deferred approval), branch control (refs/heads/main), business hours, Invoke Azure Function / REST API, required templates.
  • Use exclusive locks and lockBehavior: sequential | runLatest to prevent concurrent deployments, and read the deployment history and bypass records.
Prerequisites: Lesson 2 stage / job; Module 2 service connections. Importance: ★★★★★

What: Environments and deployment jobs

Environment is a project-level resource in Azure Pipelines that represents “a deployment target” (such as myapp-prod), which can optionally be linked to a Kubernetes namespace or VM resource. It provides three things: ① protected resource— you can configure approvals and checks on it; ② deployment history— each deployment is linked to its runs, commits and work items; ③ the target of a deployment job (- deployment: + environment:).

regular jobdeployment job
- job: X- deployment: X + environment: myapp-prod + strategy (runOnce / rolling / canary)
checks out source code by defaultdoes not check out by default, and downloads the pipeline artifacts of the current run by default
no deployment historyrecords deployment history in the environment; checks on the environment are evaluated before the stage starts
—runOnce provides lifecycle hooks: preDeploy,deploy,routeTraffic,postRouteTraffic,on: failure / success

Why: why gates are placed on resources

Approvals and checks are not defined in YAML, but are configured by the resource administrator in the web UI. Anyone who edits the YAML (including the PR author) cannot delete or change them. Checks can be configured on: environments, service connections, repositories, variable groups, secure files, agent pools. Before a stage starts, all checks on all resources it uses must pass.

How: the 5 categories and their execution order (official)

OrderCategoryChecks includedKey points
1Static checksBranch control,Required template,Evaluate artifactCan be decided at compile time; if it fails, the stage fails
2Pre-check approvalPre-check approvalsManual approval is obtained before the dynamic checks
3Dynamic checksApprovals,Invoke Azure Function,Invoke REST API,Business hours,Query Azure Monitor alertsRetried at the “evaluation interval” until timeout
4Post-check approvalPost-check approvalsApproval after the dynamic checks pass
5Exclusive lockExclusive lockAcquired last, so only one stage uses the resource at a time

Within a category, checks run in creation order; you can see the order on the Approvals and checks tab. The optional ServiceNow Change Management check requires installing an extension.

Key behavior of each check

CheckBehaviorTimeout / failure result
ApprovalsUsers or groups (any one member of the group can approve); can include instructions; can prevent approvers from approving runs they triggered themselves; the approver list is fixed when the check starts; supports deferred approval (specify when it takes effect)Not approved before timeout → stage marked as skipped; rejected → terminal failure
Branch controlAllowed branch list must use full names refs/heads/main; can require the branch to be protected (at least one policy); can set behavior when protection status is unknown; validates all associated resources in the runMismatch → stage fails
Business hoursOnly allows through within the time window; if the stage has not started when the window ends, it is withdrawn and re-evaluated the next dayTimeout → fails
Invoke Azure Function / REST APICalls your service to decide whether to allow; can be synchronous (polls at the “evaluation interval”) or asynchronous callback (recommended); since Sprint 215 can access user-defined variablesTimeout → stage is skipped
Query Azure Monitor alertsPasses only if no alert rules are active at evaluation timeTimeout → fails
Required templatePipeline must extends use templates specified by repository / ref / pathNot satisfied → run fails
Evaluate artifactRuns custom policy against container image metadataFailure → stage fails
Exclusive lockOnly one stage allowed on the same resource at a time; used with YAML lockBehaviorsee table below

lockBehavior

ValueMeaningApplies to
runLatest (default)Only the latest run acquires the lock; earlier queued runs are canceledEnvironments with frequent commits where only the latest version matters (dev/test)
sequentialAll runs acquire the lock in orderEnvironments where every version must be deployed; database migrations

When: what to configure for each environment

EnvironmentRecommended checks
myapp-devNone, or only exclusive lock (runLatest)
myapp-prodBranch control (main, requires protection) + approval (release manager group, self-approval prohibited, 24-hour timeout) + business hours (weekdays 9–17) + exclusive lock (sequential)
Service connection sc-azure-prodRequired template + branch control (prevents other pipelines from using the prod connection directly)
Common misconceptions① “Writing in YAML approval:” — YAML has no approval syntax; approvals can only be configured on resources. ② “Approval timeout = failure” — when an approval times out, the stage is skipped, and the stage can be retried. ③ “Holding a parallel job while waiting for approval” — it does not occupy one; no agent runs while checks are waiting. ④ “Setting branch control to main is enough” — you must write refs/heads/main. ⑤ “A regular job that references a service connection triggers environment approval” — environment checks only apply to deployment jobs that reference that environment; checks on a service connection apply to any stage that references it.

Flowchart: checks pipeline before a stage starts

Stage queuedConditions met ① Static checksBranch controlRequired templateEvaluate artifact ② Pre-check approvalPre-check ③ Dynamic checksApprovalsAzure FunctionREST APIBusiness hoursAzure Monitor alerts ④ Post-check approvalPost-check ⑤ LockExclusive Run Any terminal rejection → stage does not run; not all checks pass before timeout → skipped / failed (depending on check type)
Figure 3-1: the 5 categories defined officially; within a category, creation order

Structure diagram: resources used by a stage and their respective checks

stage DeployProddeployment job · environment: myapp-prod Environment myapp-prodBranch control · Approvals · Business hours · Exclusive lock Service connection sc-azure-myappRequired template (optional) Variable group myapp-common(no checks)
Figure 3-2: before a stage starts, checks on all protected resources it uses are aggregated

Timeline: runLatest vs sequential

runLatest Run #101 deploys while holding the lock #102 waiting → canceled #103 (latest) acquires the lock sequential #101 holds the lock #102 acquires in turn #103 acquires in turn The lock is released after the stage using the resource completes
Figure 3-3: lockBehavior can be set at pipeline or stage level; defaults to runLatest if omitted

Interactive: checks gate flow simulator

Select a scenario and play it, and observe the state of stage DeployProd at each category of check. Scenarios follow the official behavior: branch mismatch fails, approval timeout skips, business hours wait, runLatest cancels old runs.

Select a scenario and play it.

YAML: deployment job + environment

stages:
- stage: DeployProd
  dependsOn: DeployDev
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  lockBehavior: sequential          # used with the “exclusive lock” check on the environment
  jobs:
  - deployment: Prod
    environment: myapp-prod         # if it does not exist, it is created automatically on the first run (requires appropriate permissions)
    pool: { vmImage: ubuntu-latest }
    strategy:
      runOnce:
        deploy:
          steps:
          - script: echo "Deploying $(Build.BuildId) to prod"
        on:
          failure:
            steps:
            - script: echo "rollback here"
ActionLocation / commandDescription
Create environmentPipelines → Environments → New environment (Resource: None)Or created automatically on first run; you can also call REST distributedtask/environments
Add checkEnvironment → ⋮ → Approvals and checks → +Requires the Administrator role on that environment
View deployment historyEnvironment → Deployments TabRuns, commits and work items for each deployment
Approve / rejectRun page → Review → Approve / Reject / DeferCan also be reached from the email notification
Bypass checksRun page → Bypass checkResource administrators only; the bypasser is recorded (approvals, business hours, Function and REST checks can be bypassed)
Retry a timed-out stageRun page → Rerun stageThe stage can be retried after an approval or check times out
source ~/ado3.env
echo '{"name":"myapp-prod","description":"myapp production (ACA)"}' > env.json
az devops invoke --area distributedtask --resource environments \
  --route-parameters project=$ADO_PROJECT --http-method POST --in-file env.json \
  --api-version 7.1 --query "{id:id,name:name}" -o table
az devops invoke --area distributedtask --resource environments \
  --route-parameters project=$ADO_PROJECT --api-version 7.1 --query "value[].name" -o tsv
Id    Name
----  ----------
3     myapp-prod
myapp-dev
myapp-prod

How to verify: Two environments appear on the Environments page. Common errors: If the environment name already exists, POST returns an error → query the existing environment instead. If the az devops invoke area/resource name is not available in your extension version, create it in the web UI directly. Production use: Environments and checks can also be managed as code via the Terraform azuredevops provider (Lesson 6).

lockBehavior: runLatest
stages:
- stage: DeployDev
  jobs:
  - deployment: Dev
    environment: myapp-dev
    strategy: { runOnce: { deploy: { steps: [ { script: echo dev } ] } } }

Lab 3: configure approvals, branch control and exclusive lock for myapp-prod (about 7 minutes)

Goal: two environments; 3 checks on prod; verify that feature branches are blocked and main waits for approval. Cost: 0 (waiting for approval does not occupy a parallel job).
Create environments: Pipelines → Environments → New environment → Name myapp-dev, Resource None → Create; create the same way myapp-prod (or use the REST approach on the “Commands” tab).
Configure prod checks: myapp-prod → ⋮ → Approvals and checks →
  • Branch control: Allowed branches = refs/heads/main; tick Verify branch protection (Lesson 1 already configured branch policies on main).
  • Approvals: Approvers = yourself (for the lab) or a group; Instructions = “check dev smoke test results”; Timeout = 1 hour (for the lab). In production, it is recommended to turn off “Allow approvers to approve their own runs”.
  • Exclusive lock.
Write a minimal deployment pipeline to verify the gates: in feature/gates branch, create pipelines/gates-demo.yml:
trigger: none
lockBehavior: sequential
stages:
- stage: DeployDev
  jobs:
  - deployment: Dev
    environment: myapp-dev
    pool: { vmImage: ubuntu-latest }
    strategy: { runOnce: { deploy: { steps: [ { script: echo "dev $(Build.SourceBranch)" } ] } } }
- stage: DeployProd
  dependsOn: DeployDev
  jobs:
  - deployment: Prod
    environment: myapp-prod
    pool: { vmImage: ubuntu-latest }
    strategy: { runOnce: { deploy: { steps: [ { script: echo "prod $(Build.SourceBranch)" } ] } } }
git checkout -b feature/gates && mkdir -p pipelines && $EDITOR pipelines/gates-demo.yml
git add pipelines/gates-demo.yml && git commit -m "gates demo" && git push -u origin feature/gates
az pipelines create --name gates-demo --yaml-path pipelines/gates-demo.yml --repository myapp \
  --repository-type tfsgit --branch feature/gates --skip-first-run
az pipelines run --name gates-demo --branch feature/gates -o table
Observe the feature branch: DeployDev succeeds, DeployProd shows Branch control check fails.
Branch control   ✗  Failed
  The branch refs/heads/feature/gates is not in the list of allowed branches: refs/heads/main
Merge to main and run again: after merging via PR az pipelines run --name gates-demo --branch main. DeployProd shows “Waiting for review”; approve it in Review, and the stage runs. Open myapp-prod → Deployments to see this deployment and its associated commits.
(Optional) exclusive lock: trigger two main runs in a row; the second run's DeployProd shows waiting for the lock; because it is sequential, the second continues after the first completes. Change lockBehavior to runLatest and repeat, and observe the earlier run being canceled.
Cleanup: keep the two environments and checks for use in Module 4; you may delete the gates-demo pipeline: az pipelines delete --id $(az pipelines show --name gates-demo --query id -o tsv) --yes.

Case 1: the “surprise release” after 5 PM on Friday

Problem: The approver approved at 16:55 on Friday, but deployment only started at 17:30 (after queuing), so the on-call staff had gone home when the failure occurred.

Approach: Add a business hours check on the prod environment (Monday–Thursday 9:00–16:00). Stages that have not started when the window ends have their business-hours approval withdrawn and are re-evaluated the next day. Emergency fixes are bypassed by a resource administrator Bypass, and the bypasser is recorded in the checks panel.

Case 2: change freeze check with Invoke REST API

Problem: The company has a unified change calendar (freeze periods, major events).

Approach: Add an Invoke REST API check on the prod environment, calling the internal /freeze?service=myapp, returning {"allowed": true} before the stage proceeds; implemented with the officially recommended asynchronous callback pattern, so the decision is a terminal state.

Case 3: service connection “borrowed” by another pipeline

Problem: A pipeline from another team referenced the prod service connection (because Grant access permission to all pipelines was ticked when it was created).

Approach: Remove the blanket authorization and grant access one pipeline at a time; add a Required template check on the service connection, so only pipelines that extend the company deployment template can use it; add a Branch control check that allows only main. In the audit log, filter by ServiceEndpoint to trace historical usage.

Common errors and fixes

The branch refs/heads/feature/x is not in the list of allowed branches

Cause: The branch control check failed. It may also be that the allowed list was written as main instead of refs/heads/main.

Fix: Run from main; correct the allowed list to full names; if Verify branch protection is ticked, confirm that main has at least one branch policy.

Stage DeployProd was skipped (approval timed out)

Cause: The approval was not completed within the timeout, so the stage was marked as skipped.

Fix: On the run page, Rerun stage; adjust the timeout; set approvers to a group instead of an individual; use deferred approval.

Checks never started / The checks defined didn't start

Cause (official FAQ): Checks are evaluated only after the stage's conditions are met; or the stage does not actually use this resource (for example, it uses a regular job instead of a deployment job); or the check was added after the run started.

Fix: Confirm that the stage contains environment: myapp-prod; re-run.

Run keeps showing Waiting… but no one receives an approval notification

Cause: It is waiting on an exclusive lock or business hours, not an approval; or approver notification settings have been turned off.

Fix: Open the Checks panel to see which check it is; check User settings → Notifications.

Pipeline does not extend from the required template

Cause: A required template check is configured on the resource, but the pipeline does not have extends: template: …@templates.

Fix: Switch to extending the company template (Lesson 5); confirm the repository, ref and path match what is entered in the check.

Command line / YAML exercises
1. Write a stage that runs only on the main branch, deploys to myapp-prod, acquires the exclusive lock in sequence, and runs a rollback script on failure.
- stage: DeployProd
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  lockBehavior: sequential
  jobs:
  - deployment: Prod
    environment: myapp-prod
    strategy:
      runOnce:
        deploy: { steps: [ { script: ./deploy.sh } ] }
        on:
          failure: { steps: [ { script: ./rollback.sh } ] }
2. Use the CLI to list all environment names in the project.
az devops invoke --area distributedtask --resource environments --route-parameters project=myapp-lab --api-version 7.1 --query "value[].name" -o tsv
Scenario analysis
The team complains: 30 commits a day have piled up 30 runs waiting for prod approval, and approvers have to click through them one by one. How can this be improved?

① Use an exclusive lock on the prod environment + lockBehavior: runLatest, earlier queued runs are canceled and only the latest is kept; ② change prod deployment to be triggered by tag or manually (decouple release cadence from commit cadence); ③ no approval for dev/test; use automated checks (Azure Monitor alerts, REST quality gates) instead of manual approval; ④ set approvers to a group and use deferred approval to schedule releases for off-peak hours.

Verified instructional videos

▶
Azure DevOps Environments: Checks and Gates DEEP DIVE — CoderDave
English · walkthrough of environment checks
▶
Environments and approvals in Azure DevOps — Azure Infrastructure, Security & DevOps Series
English · introduction to environments and approvals
▶
Azure Pipelines · 10/10 · Enterprise Gates: Approvals and Checks — DevStoriesEU
English · enterprise gating
▶
Manual Approvals and Checks before Deployment | Azure Pipeline | Azure Devops | An IT Professional — An IT Professional
English · configuring manual approvals

The titles and channels above were verified through the YouTube oEmbed API (2026-11-15).

Official docs

Video storyboard script

Shot 1 · 0:00–0:20
Visual: a lock beside a YAML file; the key hangs on the “Environment” icon rather than on the YAML.
Narration: approvals and checks are configured on resources; anyone who edits the YAML cannot delete them.
Shot 2 · 0:20–1:10
Visual: five gates lined up in order: static checks, pre-check approval, dynamic checks, post-check approval, exclusive lock.
Narration: before a stage starts, checks are evaluated across five categories in order: first branch control and required templates, then approvals and dynamic checks, and finally the exclusive lock is acquired.
Shot 3 · 1:10–1:40
Visual: the feature-branch cart is stopped by a red light at the first gate; when the approval clock runs out, the cart turns gray and shows skipped.
Narration: a branch mismatch fails immediately; an approval timeout skips the stage, and it can be retried.
Shot 4 · 1:40–2:10
Visual: three carts queue through the lock; with runLatest the first two disappear, with sequential they pass through one after another.
Narration: the exclusive lock prevents concurrent deployments; runLatest keeps only the latest run, and sequential deploys each run in order.
or score ≥ 70% on the “Quiz”

Module 4 · Deploy to Azure Container Apps

21:00 – 30:00 · images go into ACR; dev deploys automatically; the new prod revision gets 0% traffic first and switches once the smoke test passes; automatic rollback on failure
9 minutesAzureContainerApps@1 · az containerapp★★★★★ Core thread of this lesson
Learning objectives
  • Push images to ACR in two ways: Docker@2 + Docker Registry service connection (ACR, WIF), or AzureCLI@2 + az acr build; know the permissions each one requires.
  • Use AzureContainerApps@1 the two modes of (build and push from source / deploy an existing image), and know when to switch to az containerapp update for finer-grained control.
  • Understand revisions, revision modes (Single / Multiple / label preview), revision-scope and application-scope changes, and traffic weights.
  • Implement with runOnce lifecycle hooks: deploy (0% new revision) → routeTraffic (smoke test + shift traffic) → postRouteTraffic (verification) → on.failure (rollback).
Prerequisites: Modules 2 and 3; Docker course Lesson 3 (ACA, pulling images with managed identity). Importance: ★★★★★

What: two ways to push images

Docker@2 (buildAndPush)az acr build (in AzureCLI@2 )
Where it is builtAgent's local DockerACR Tasks cloud build (agent does not need Docker)
Service connectionDocker Registry Type → Azure Container Registry; authentication can be Service Principal, Managed Identity or Workload Identity federationARM service connection (WIF)
Permissions required for the identityOn ACR AcrPushcan run ACR tasks (e.g., Contributor on the registry); AcrPush is not enough
Advantagescan take advantage of agent caching, multi-stage builds, BuildKitSimpler agent setup; build logs are traceable in ACR
NotemacOS Microsoft-hosted agents do not have DockerSome subscription types may not be able to use ACR Tasks; in that case use Docker@2 instead

What: AzureContainerApps@1 task

Official task AzureContainerApps@1 (Azure Container Apps Deploy) has two usage modes:

  • Build and push: provide appSourcePath + acrName. If the source has a Dockerfile, it uses docker build; otherwise Oryx++ Builder (pack CLI) generates the image. If acrUsername/acrPassword is not provided, use az acr login to get a token.
  • Deploy an existing image: provide imageToDeploy (including the ACR login server).
  • Other inputs: azureSubscription (alias connectedServiceNameARM, required),containerAppName,resourceGroup,containerAppEnvironment,targetPort,ingress (external / internal / disabled),environmentVariables (space-separated key=value,secretref: references secrets),yamlConfigPath,runtimeStack,kind (functionapp),disableTelemetry. There are no output variables.
  • If no name is provided, defaults are generated (app ado-task-app-<build-id>-<build-number>, resource group <app>-rg) —always specify them explicitly in production; otherwise a resource group and environment will be created silently.
  • Requires Azure CLI on the agent; build scenarios require Docker; telemetry is sent by default (disableTelemetry: true to turn off).

Why: why prod uses revisions + traffic

A revision is an application's immutable snapshot. Changes under properties.template (image, container configuration, scaling rules, revision suffix) are revision-scope change, which creates a new revision; changes under properties.configuration (secret values, revision mode, ingress, traffic rules, labels, registry credentials, Dapr) are application-scope change, which applies to all revisions and does not create a new revision.

Revision modeBehaviorUsage in this lesson
Single (default)Traffic is shifted from the old revision only after the new revision is ready (provisioned successfully, scaled to the same replica count as the old revision, probes pass); on failure, traffic stays on the old revision; the old revision is automatically deactivateddev
MultipleMultiple revisions are active at the same time; traffic weights are assigned manually; you decide when to deactivate themprod: 0% staging → smoke test → 100%
Deployment labels (preview)Gives revisions label names such as dev / staging / prod, used for traffic switching and simpler rollbackAwareness is enough

By default up to 100 inactive revisions are retained; inactive revisions are not billed; they can be reactivated at any time — this is the fastest rollback method on ACA.

How: the four hooks for prod

runOnce hookWhat it doesCommand
deployPins traffic to the current revision, then creates a new revision (suffix b$(Build.BuildId)), the new revision gets 0%az containerapp ingress traffic set --revision-weight OLD=100,az containerapp update --revision-suffix
routeTrafficSmoke-tests the new revision's own FQDN; switches to 100% after it passesaz containerapp revision show --query properties.fqdn,scripts/smoke.sh
postRouteTrafficVerifies the version number once more on the public FQDNscripts/smoke.sh https://$FQDN $(tag)
on: failureIf any hook fails: traffic switches back to the previous active revision and the new revision is deactivatedaz containerapp revision deactivate

Note: each lifecycle hook runs as a separate job; hooks do not share working directories or regular variables. So the new revision name is computed with a deterministic rule ($(APP_PROD)--b$(Build.BuildId)) is computed; the rollback script instead finds the “previous active revision” by querying the revision list. Deployment jobs do not check out by default, so hooks that need repository scripts must write - checkout: self.

When: choose the task or the CLI

  • Simple scenarios (dev, single revision) → AzureContainerApps@1, a few lines of YAML.
  • Need precise control over revision suffix, traffic weights, labels, rollback → AzureCLI@2 + az containerapp.
  • Extensive configuration (probes, scaling, multiple containers) → yamlConfigPath or Bicep (Module 6), with the image tag passed in as a parameter.
Common misconceptions① “Changing secrets creates a new revision” — secrets are application-scope and do not create a new revision; the revision must be restarted to read the new value. ② “In multiple-revision mode the new revision automatically gets traffic” — if the traffic rule is latestRevision: true, the new revision gets that weight once it is ready; to do a 0% pre-release, you must first pin traffic to the specific revision name. ③ “Deploying with the latest tag is enough” — the same tag does not trigger a new revision and cannot be rolled back; use immutable tags (BuildId or Git SHA). ④ “Enabling the ACR admin user is the easiest” — use managed identity + AcrPull for pulling, and WIF identity + AcrPush for pushing.

Flowchart: myapp multi-stage pipeline

BuildpytestPR and main Pushaz acr buildmyapp:$(Build.BuildId) DeployDevAzureContainerApps@1+ smoke test DeployProd (approvals · branch control · lock) deploy: pin old revision 100% → new revision 0% routeTraffic: smoke test new revision FQDN → shift to 100% postRouteTraffic: verify version on public FQDN on.failure: switch back to old revision + deactivate new revision(runs when any hook fails) Push / Deploy run only on main Immutable image tag: $(Build.BuildId)
Figure 4-1: the prod stage does not start if dev fails; if any prod hook fails, rollback is automatic

State diagram: changes in prod revisions and traffic

Before deployment ca-myapp-prod--b101 100% After deploy --b101 100% --b102 0% (only the revision FQDN is accessible) After switch --b101 0% (retained, can be rolled back) --b102 100% After rollback --b101 100% --b102 deactivated
Figure 4-2: rollback only changes application-scope traffic rules, takes effect within seconds, and does not require re-pulling the image

Permissions diagram: each identity covers its own part

id-ado-myapp (pipeline WIF)Contributor @ rg-ado-labAcrPush @ ACR (when using Docker@2) ACR acrmyappXXXXadmin user: disabledmyapp:101, 102, … id-myapp-pull (runtime)AcrPull @ ACRattached to two Container Apps
Figure 4-3: push and pull permissions are separated; even if the app is compromised, images cannot be overwritten

Interactive: revision traffic switching and rollback

Simulates one release of ca-myapp-prod (multiple-revision mode). You can choose to let the smoke test pass or fail, or inject “error rate rises after release” after the switch.

Ready.

Push image (choose one)

- task: AzureCLI@2
  displayName: Build & push with ACR Tasks
  inputs:
    azureSubscription: sc-azure-myapp
    scriptType: bash
    scriptLocation: inlineScript
    inlineScript: |
      az acr build -r $(ACR_NAME) -t myapp:$(Build.BuildId) -t myapp:main --no-logs . \
        && az acr repository show-tags -n $(ACR_NAME) --repository myapp --top 3 --orderby time_desc -o tsv
- task: Docker@2
  displayName: Build & push with Docker
  inputs:
    containerRegistry: sc-acr-myapp      # Docker Registry service connection, type Azure Container Registry, auth WIF
    repository: myapp
    command: buildAndPush
    Dockerfile: Dockerfile
    tags: |
      $(Build.BuildId)
      main

Deploy to dev: AzureContainerApps@1

- task: AzureContainerApps@1
  displayName: Deploy to ca-myapp-dev
  inputs:
    azureSubscription: sc-azure-myapp
    imageToDeploy: $(ACR_NAME).azurecr.io/myapp:$(Build.BuildId)
    containerAppName: $(APP_DEV)          # always specify explicitly; otherwise a new app named ado-task-app-… is created
    resourceGroup: $(RG)
    containerAppEnvironment: $(ACA_ENV)
    environmentVariables: APP_VERSION=$(Build.BuildId)
    disableTelemetry: true

The app already exists and managed-identity pulling is already configured (Module 0), so do not pass acrName; the task updates the existing app. If the app is being created for the first time, also add targetPort: '5000',ingress: external.

Core az containerapp commands

CommandPurposeDescription
az containerapp update -g RG -n APP --image IMG --revision-suffix b123 --set-env-vars APP_VERSION=123Create a new revisionSuffix starts with a lowercase letter and contains only lowercase letters, digits and -, ≤ 64 chars
az containerapp revision list -g RG -n APP -o tableList revisions, weights, status--all including inactive
az containerapp ingress traffic set -g RG -n APP --revision-weight A=100 B=0Set traffic weightsmultiple-revision mode; must sum to 100
az containerapp ingress traffic show -g RG -n APPView traffic rulesMay appear latestRevision: true entries
az containerapp revision show -g RG -n APP --revision R --query properties.fqdnRevision-specific FQDNused for smoke tests at 0% traffic
az containerapp revision activate / deactivate --revision RActivate / deactivate revisionsDeactivated revisions are not billed
az containerapp revision label add --label canary --revision RAdd labels to revisions (separate URL)Labels can be moved between revisions
az containerapp logs show -g RG -n APP --revision R --tail 50View logs--type system View system events such as image pulls
#!/usr/bin/env bash
# Usage: scripts/smoke.sh https://FQDN EXPECTED_VERSION
set -euo pipefail
URL=$1; EXPECT=$2; code=000
for i in $(seq 1 20); do                      # up to 2 minutes: a revision scaled to 0 needs a cold start
  code=$(curl -s -o /dev/null -w '%{http_code}' "$URL/healthz" || true)
  [ "$code" = "200" ] && break
  echo "attempt $i: /healthz -> $code"; sleep 6
done
[ "$code" = "200" ] || { echo "##vso[task.logissue type=error]healthz failed ($code)"; exit 1; }
body=$(curl -s "$URL/"); echo "$body"
echo "$body" | grep -q "\[$EXPECT\]" || { echo "##vso[task.logissue type=error]expected version $EXPECT"; exit 1; }
echo "smoke OK: $URL is version $EXPECT"
attempt 1: /healthz -> 000
[1234] Hello from ca-myapp-dev--5k2qz9h-7c9d6f5b8-x2k4p, hits=N/A (redis not connected)
smoke OK: https://ca-myapp-dev.kindpond-1a2b3c4d.canadacentral.azurecontainerapps.io is version 1234

Common errors: Forgetting chmod +x scripts/smoke.sh (in the pipeline, use bash scripts/smoke.sh to avoid it). Production use: The smoke script should check the version number, so that “the old revision is still responding” is not mistakenly treated as success.

Lab 4: myapp multi-stage pipeline dev → prod (about 12 minutes; can be finished after class)

Goal: after a commit to main, automatically Build → Push → DeployDev (smoke test) → DeployProd (approval → 0% new revision → smoke test → 100%). Cost: ACR Tasks are billed by build duration (see the ACR pricing page) plus a small amount of ACA runtime; usually less than US$1.
Commit the smoke test script: add the scripts/smoke.sh from the “Commands” tab to the repository.
Replace azure-pipelines.yml (keep the test steps from Lesson 2):
trigger:
  branches: { include: [ main ] }
pr:
  branches: { include: [ main ] }

parameters:
- name: failSmoke                # tick when running manually, to rehearse rollback
  type: boolean
  default: false

variables:
- group: myapp-common            # ACR_NAME RG ACA_ENV APP_DEV APP_PROD
- name: tag
  value: $(Build.BuildId)
- name: isMain
  value: $[eq(variables['Build.SourceBranch'], 'refs/heads/main')]

pool: { vmImage: ubuntu-latest }

stages:
- stage: Build
  jobs:
  - job: Test
    steps:
    - script: |
        python -m pip install -r requirements.txt pytest
        python -m pytest -q || echo "no tests yet"
      displayName: Unit tests

- stage: Push
  dependsOn: Build
  condition: and(succeeded(), eq(variables.isMain, true))
  jobs:
  - job: Push
    steps:
    - task: AzureCLI@2
      displayName: az acr build
      inputs:
        azureSubscription: sc-azure-myapp
        scriptType: bash
        scriptLocation: inlineScript
        inlineScript: az acr build -r $(ACR_NAME) -t myapp:$(tag) --no-logs .

- stage: DeployDev
  dependsOn: Push
  jobs:
  - deployment: Dev
    environment: myapp-dev
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: AzureContainerApps@1
            inputs:
              azureSubscription: sc-azure-myapp
              imageToDeploy: $(ACR_NAME).azurecr.io/myapp:$(tag)
              containerAppName: $(APP_DEV)
              resourceGroup: $(RG)
              containerAppEnvironment: $(ACA_ENV)
              environmentVariables: APP_VERSION=$(tag)
              disableTelemetry: true
          - task: AzureCLI@2
            displayName: Smoke test dev
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                FQDN=$(az containerapp show -g $(RG) -n $(APP_DEV) --query properties.configuration.ingress.fqdn -o tsv)
                bash scripts/smoke.sh "https://$FQDN" "$(tag)"

- stage: DeployProd
  dependsOn: DeployDev
  lockBehavior: sequential
  variables:
    newRev: $(APP_PROD)--b$(tag)
  jobs:
  - deployment: Prod
    environment: myapp-prod
    strategy:
      runOnce:
        deploy:
          steps:
          - task: AzureCLI@2
            displayName: New revision at 0%
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                set -euo pipefail
                CUR=$(az containerapp ingress traffic show -g $(RG) -n $(APP_PROD) -o json \
                      | jq -r 'map(select(.weight>0)) | max_by(.weight) | .revisionName // empty')
                [ -z "$CUR" ] && CUR=$(az containerapp show -g $(RG) -n $(APP_PROD) --query properties.latestReadyRevisionName -o tsv)
                echo "current revision: $CUR"
                az containerapp ingress traffic set -g $(RG) -n $(APP_PROD) --revision-weight $CUR=100 -o none
                az containerapp update -g $(RG) -n $(APP_PROD) \
                  --image $(ACR_NAME).azurecr.io/myapp:$(tag) \
                  --set-env-vars APP_VERSION=$(tag) --revision-suffix b$(tag) -o none
                for i in $(seq 1 30); do
                  ST=$(az containerapp revision show -g $(RG) -n $(APP_PROD) --revision $(newRev) --query properties.provisioningState -o tsv)
                  echo "provisioning: $ST"; [ "$ST" = "Provisioned" ] && exit 0
                  [ "$ST" = "Failed" ] && exit 1; sleep 10
                done; exit 1
        routeTraffic:
          steps:
          - checkout: self
          - task: AzureCLI@2
            displayName: Smoke new revision, then shift 100%
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                set -euo pipefail
                RFQDN=$(az containerapp revision show -g $(RG) -n $(APP_PROD) --revision $(newRev) --query properties.fqdn -o tsv)
                FAIL="${{ parameters.failSmoke }}"; PATH_SUFFIX=""
                [ "${FAIL,,}" = "true" ] && PATH_SUFFIX="/does-not-exist"
                bash scripts/smoke.sh "https://$RFQDN$PATH_SUFFIX" "$(tag)"
                az containerapp ingress traffic set -g $(RG) -n $(APP_PROD) --revision-weight $(newRev)=100 -o table
        postRouteTraffic:
          steps:
          - checkout: self
          - task: AzureCLI@2
            displayName: Verify public FQDN
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              inlineScript: |
                FQDN=$(az containerapp show -g $(RG) -n $(APP_PROD) --query properties.configuration.ingress.fqdn -o tsv)
                bash scripts/smoke.sh "https://$FQDN" "$(tag)"
        on:
          failure:
            steps:
            - task: AzureCLI@2
              displayName: Roll back to previous revision
              inputs:
                azureSubscription: sc-azure-myapp
                scriptType: bash
                scriptLocation: inlineScript
                inlineScript: |
                  set -uo pipefail
                  OLD=$(az containerapp revision list -g $(RG) -n $(APP_PROD) -o json \
                        | jq -r --arg n "$(newRev)" '[.[] | select(.name != $n and .properties.active == true)]
                                                       | sort_by(.properties.createdTime) | last | .name // empty')
                  echo "rolling back to: ${OLD:-<none>}"
                  [ -n "$OLD" ] && az containerapp ingress traffic set -g $(RG) -n $(APP_PROD) --revision-weight $OLD=100 -o table
                  az containerapp revision deactivate -g $(RG) -n $(APP_PROD) --revision $(newRev) || true
                  echo "##vso[task.logissue type=warning]prod rolled back to $OLD"

Notes: failSmoke is a runtime parameter (a checkbox in the Run pipeline panel); when the template expands, ${{ parameters.failSmoke }} is replaced with True / False, the script uses ${FAIL,,} to do a lowercase comparison. A parameter is used instead of a queue-time variable because the organization may have enabled “limit variables that can be set at queue time”.

Create the pipeline and authorize: if the pipeline already exists (Lesson 2), committing triggers it; on the first run, DeployDev / DeployProd will prompt “This pipeline needs permission to access a resource before this run can continue” → View → Permit (service connections, environments, variable groups).
Observe dev: verify that the smoke test output in the DeployDev log shows smoke OK … is version <BuildId>.
Approve prod: DeployProd shows Waiting → Review → Approve. You should see the deploy, routeTraffic and postRouteTraffic jobs succeed in turn.
az containerapp revision list -g $RG -n $APP_PROD --query "[].{name:name,active:properties.active,weight:properties.trafficWeight}" -o table
Name                         Active    Weight
---------------------------  --------  --------
ca-myapp-prod--5x9w2kq       True      0
ca-myapp-prod--b1234         True      100
Rehearse rollback: manually run main (Run pipeline) and tick the parameter failSmoke. After approval, routeTraffic fails, the on.failure job runs, traffic stays on the previous revision, and the new revision is deactivated.
Cleanup: keep the resources until the comprehensive lab ends; inactive revisions are not billed.

Case 1: the latest tag causes “deployment succeeded but version unchanged”

Problem: Each pipeline run pushes myapp:latest and az containerapp update --image myapp:latest, the revision template does not change, no new revision is created, and the old replicas keep running the old image.

Approach: Use immutable tags ($(Build.BuildId) or Git SHA), lock release tags in ACR (az acr repository update --write-enabled false, see the Docker course); the smoke test verifies the version number.

Case 2: the task silently created a resource group

Problem: Someone copied the official minimal example and only provided appSourcePath and acrName, so every build generated ado-task-app-… an app and …-rg a resource group and a new environment.

Approach: Explicitly specify containerAppName,resourceGroup,containerAppEnvironment; scope the service connection and RBAC to the existing resource group (without a subscription-level Contributor role, a new resource group cannot be created).

Case 3: rollback took only 8 seconds

Problem: The new version only exposed a memory leak 30 minutes later.

Approach: Because prod uses multiple-revision mode and keeps the previous revision, the on-call engineer ran az containerapp ingress traffic set --revision-weight <old revision>=100, and traffic switched back immediately; an old revision scaled to 0 needs a cold start, so for prod's min-replicas is set to 1.

Common errors and fixes

unauthorized: authentication required / denied: requested access to the resource is denied (pushing to ACR)

Cause: The pipeline identity does not have AcrPush (Docker@2), or lacks permission to run ACR tasks (az acr build); the Docker Registry service connection points to a different ACR.

az role assignment list --assignee $CLIENT_ID --scope $ACR_ID -o table

Fix: Grant AcrPush (or Contributor for ACR Tasks) and wait a few minutes for RBAC to take effect. See Module 7.

Revision status Provisioning failed / Activation failed: ImagePullBackOff / unauthorized

Cause: The Container App's pull identity does not have AcrPull, or the registry is not configured with a managed identity.

az containerapp show -g $RG -n $APP_PROD --query properties.configuration.registries
az containerapp logs show -g $RG -n $APP_PROD --type system --tail 30

Fix:az containerapp registry set -g $RG -n $APP_PROD --server $ACR.azurecr.io --identity $PULL_ID.

Failed to set traffic weights: weights do not sum to 100 / single-revision mode does not support weights (error codes and wording follow the actual CLI output)

Cause:--revision-weight The sum is not 100, or weights are set in single-revision mode.

Fix:az containerapp revision set-mode --mode multiple; ensure the sum is 100.

Smoke test keeps returning 000 / 404, but the app is actually healthy

Cause: The revision scaled to 0 is cold-starting; or targetPort does not match the port the app listens on (myapp listens on 5000); or the public FQDN was accessed for a 0% revision.

az containerapp show -g $RG -n $APP_PROD --query properties.configuration.ingress.targetPort

Fix: Extend retries; correct targetPort; use the revision FQDN or label URL for the new revision.

OLD is empty in on.failure, so rollback did not run

Cause: The old revision has already been deactivated (single-revision mode deactivates the old revision automatically), or this is the first deployment.

Fix: Use multiple-revision mode for prod; if necessary, az containerapp revision activate --revision <name> before switching traffic (up to 100 inactive revisions are retained).

Command-line exercises
1. Split ca-myapp-prod's traffic 90/10 between revisions --b101 and --b102.
az containerapp ingress traffic set -g rg-ado-lab -n ca-myapp-prod \
  --revision-weight ca-myapp-prod--b101=90 ca-myapp-prod--b102=10
2. Find the 3 most recent myapp tags pushed to ACR.
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 3 -o tsv
Scenario analysis
Prod shows no problems 5 minutes after release, but the error rate rises 30 minutes later. How can your pipeline be improved so it detects this and rolls back automatically?

① Add an observation period in postRouteTraffic: e.g., first 10% traffic (--revision-weight new=10 old=90), wait and query Azure Monitor / Application Insights metrics, then raise to 100%; ② or add a “Query Azure Monitor alerts” check on the prod environment for the next release; ③ keep the previous revision and set min-replicas ≥ 1 so rollback has no cold start; ④ have an alert trigger a run of traffic set old=100 the pipeline (manual or automated).

Verified instructional videos

▶
Azure Container Apps Revisions, Traffic Splitting, Scale to Zero and Managed Identity (AI-200) — Infra2AI
English · revisions, traffic splitting, scale to 0, managed identity
▶
How to send 20% of traffic to a new version on Azure Container Apps — Ehsan Tatasadi
English · proportional traffic shifting
▶
Implement Azure Container Apps | AZ-204 | Episode 15 — Microsoft Learn
English · ACA implementation overview
▶
Azure Container Apps Tutorial #01 - Getting Started — Kamal Rathnayake - MVP
English · getting started

The titles and channels above were verified through the YouTube oEmbed API (2026-11-15). No verified video specifically demonstrating AzureContainerApps@1 + environment approvals was found; refer to this lesson's lab instead.

Official docs

Video storyboard script

Shot 1 · 0:00–0:30
Visual: four stage blocks light up in turn; the image drops into ACR from the Push step.
Narration: the myapp pipeline tests first, then builds an image with an immutable tag in ACR, then deploys dev, and finally deploys prod.
Shot 2 · 0:30–1:10
Visual: a second revision card appears in prod; the traffic bar shows 100 / 0.
Narration: prod uses multiple-revision mode. The new revision goes live with zero traffic first and can only be reached through its own address.
Shot 3 · 1:10–1:40
Visual: the smoke test gets a green check; the traffic bar slides to 0 / 100.
Narration: the smoke test checks the health endpoint and version number; once it passes, all traffic is switched to the new revision.
Shot 4 · 1:40–2:10
Visual: the smoke test gets a red cross; on.failure flashes; traffic stays on the old revision; the new revision turns gray.
Narration: if any step fails, the failure hook switches traffic back to the previous revision and deactivates the new one; rollback takes only seconds.
or score ≥ 70% on the “Quiz”

Module 5 · Deploy to AKS and App Service

30:00 – 38:00 · the same WIF service connection, two targets: Kubernetes manifests and App Service deployment slots
8 minutesKubernetesManifest@1 · AzureWebAppContainer@1★★★★☆ Optional lab (incurs cost)
Learning objectives
  • Use KubernetesManifest@1 + connectionType: azureResourceManager to deploy to AKS, and understand why it suits private clusters and clusters with local accounts disabled better than the “Kubernetes service connection (Azure Subscription option)”.
  • On an Entra ID–integrated AKS cluster, use kubelogin convert-kubeconfig -l azurecli to let scripts use the service connection identity non-interactively; know which Azure RBAC roles are needed.
  • Understand App Service deployment slots: deploy to staging → warm up → swap → swap back if needed; distinguish settings that are “sticky” to the slot from settings that are swapped with the code.
  • Use AzureWebAppContainer@1 (or AzureWebApp@1) to deploy to a slot, and use AzureAppServiceManage@0 to run Swap Slots.
Prerequisites:K8s course(Deployment, Service, kubeconfig); Modules 2–4. Importance: ★★★★☆

What: three ways to connect to AKS

MethodHow it worksAdvantagesLimitations
KubernetesManifest@1 + ARM service connection (connectionType: azureResourceManager)At runtime, the WIF identity gets cluster credentials from ARM and issues a short-lived token for each task.No cluster access is needed when creating the service connection; supports private clusters (the agent must be able to reach the network); supports disabling local accountsThe agent must be able to reach the API server
Kubernetes service connection (KubeConfig / Service Account / Azure Subscription)Stores a kubeconfig or ServiceAccount tokenWorks with any Kubernetes cluster (non-AKS)The Azure Subscription option requires cluster access at creation time; since K8s 1.24, long-lived tokens are no longer generated by default, so it may hang at “Loading namespaces”
AzureCLI@2 + az aks get-credentials + kubeloginConverts the kubeconfig in the script to use the Azure CLI login sessionFull control (any helm or kubectl command)You must handle rollout status checks yourself

KubernetesManifest@1 key points (official reference, 2026-09)

  • action: deploy (default) / bake (helm, kompose, kustomize rendering, output manifestsBundle) / createSecret / patch / scale / promote / reject / delete.
  • containers: replaces matching images in the manifest with full names including tags / digests (artifact substitution); imagePullSecrets injected automatically.
  • Automatically checks rollout status (rolloutStatusTimeout, seconds, default 0); adds traceable annotations to objects (azure-pipelines/org,azure-pipelines/project,azure-pipelines/pipeline,azure-pipelines/execution,azure-pipelines/jobName etc.).
  • strategy: canary + trafficSplitMethod: pod | smi + percentage: create -baseline and -canary variants, then promote or reject (see Lesson 5 for details).
  • Official FAQ note: kubelogin non-interactive login for Entra RBAC clusters “will be supported in a future update”; therefore on Entra-integrated clusters, use the ARM connection type, or in AzureCLI@2 the script, run kubelogin convert-kubeconfig yourself.

Permissions required by AKS (WIF identity)

Cluster authorization modeRequired roles
Entra ID authentication + Azure RBAC for KubernetesAzure Kubernetes Service Cluster User Role (get user kubeconfig) + Azure Kubernetes Service RBAC Writer (scope can go down to the namespace)
Entra ID authentication + Kubernetes RBACCluster User Role + in-cluster RoleBinding that binds this identity's objectId / group
Local accounts (not recommended)Cluster Admin Role (useClusterAdmin: true) — equivalent to a cluster administrator
Pulling ACR imagesCluster kubelet identity AcrPull (az aks update --attach-acr)

What: App Service deployment slots

A deployment slot is a separate instance under the same App Service app (it has its own hostname, such as myapp-web-staging.azurewebsites.net), and the production slot shares the same App Service plan. It requires the Standard, Premium or Isolated tier. When swapping, App Service first applies the target slot's settings to the source slot's instances and warms them up (configurable via applicationInitialization), and once all instances are ready, switches routing — users see no impact; rollback is simply another swap.

Swapped with the codeSticky to the slot (not swapped)
Regular app settings, connection strings (not marked as slot settings), handler mappings, public certificates, WebJobs contentMarked as Deployment slot setting app settings / connection strings, custom domains, TLS bindings, scaling settings, IP restrictions, managed identities, etc. (see the official docs for the full list)

When: how to choose

  • AKS: prefer the ARM connection type; when you need Helm release management, use HelmDeploy@1 (supports Azure service connections) or in AzureCLI@2 the script, run helm (Helm course).
  • App Service: never deploy directly to the production slot; deploy to staging first, then swap after the smoke test. Database schema changes must be backward compatible, because old and new versions briefly coexist before and after the swap.
Common misconceptions① “useClusterAdmin is convenient” — it bypasses Entra and Kubernetes RBAC; disable it in production and consider disabling local accounts. ② “Slots have their own compute resources” — they share plan instances, so staging load affects production. ③ “A swap swaps all settings” — values marked as slot settings are not swapped. ④ “A failed swap gets stuck halfway” — the swap switches routing only after warm-up succeeds; if warm-up fails, the operation aborts and production is unaffected.

Architecture diagram: authentication chain from pipeline to AKS

KubernetesManifest@1azureResourceManager Entra (WIF)Access token ARMlistClusterUserCredential AKS API serverEntra token (aud = AKS server app)Azure RBAC: RBAC Writer @ ns myappapply → rollout status Each task gets a short-lived token; for private clusters, the agent must be able to reach the API server over the network (self-hosted / Managed DevOps Pools)
Figure 5-1: the ARM connection type defers “cluster access” until runtime

Flowchart: App Service slot swap

Deploy to stagingNew image / package Smoke test staging URL-staging.azurewebsites.net Apply target slot settings+ warm up all instances Switch routingZero downtime Need to roll back?Swap again After the swap, the old version stays in the staging slot, serving as a ready-made rollback target
Figure 5-2: if warm-up fails, the swap aborts and the production slot is unchanged

Comparison diagram: “rollback” on AKS vs App Service

AKSkubectl rollout undo deploy/myapp (ReplicaSet history)or redeploy the previous image tag (recommended, traceable) App Serviceaz webapp deployment slot swap (swap again)seconds; the old version is already warmed up in staging
Figure 5-3: rollback methods for the three targets: ACA traffic weights, AKS rollout, App Service swap

Step-by-step animation: App Service deployment slot swap (including failure and rollback)

production slot
v1 · myapp-web.azurewebsites.net
Settings: DB=prod (slot setting)
staging slot
(empty) · myapp-web-staging.azurewebsites.net
Settings: DB=staging (slot setting)
Ready.

AKS: KubernetesManifest@1 (ARM connection type)

- deployment: Aks
  environment: myapp-aks          # can also be an environment with a Kubernetes resource
  strategy:
    runOnce:
      deploy:
        steps:
        - checkout: self
        - task: KubernetesManifest@1
          displayName: Deploy to AKS
          inputs:
            action: deploy
            connectionType: azureResourceManager
            azureSubscriptionConnection: sc-azure-myapp
            azureResourceGroup: rg-ado-lab
            kubernetesCluster: aks-ado-lab
            namespace: myapp
            manifests: |
              k8s/deployment.yaml
              k8s/service.yaml
            containers: $(ACR_NAME).azurecr.io/myapp:$(Build.BuildId)
            rolloutStatusTimeout: '300'

AKS: AzureCLI@2 + kubelogin (Entra-integrated cluster)

- task: AzureCLI@2
  inputs:
    azureSubscription: sc-azure-myapp
    scriptType: bash
    scriptLocation: inlineScript
    inlineScript: |
      set -euo pipefail
      az aks get-credentials -g rg-ado-lab -n aks-ado-lab --overwrite-existing
      kubelogin convert-kubeconfig -l azurecli      # uses the current az login session (i.e., the service connection identity)
      kubectl -n myapp set image deploy/myapp myapp=$(ACR_NAME).azurecr.io/myapp:$(Build.BuildId)
      kubectl -n myapp rollout status deploy/myapp --timeout=180s || { kubectl -n myapp rollout undo deploy/myapp; exit 1; }
CommandPurposeNotes
az aks create -g RG -n aks-ado-lab --enable-aad --enable-azure-rbac --disable-local-accounts --attach-acr $ACRCreate a cluster with Entra + Azure RBACParameters follow az aks create --help as the source of truth.
az role assignment create --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myappNamespace-level write permissiontogether with Cluster User Role
kubelogin convert-kubeconfig -l azurecliNon-interactive loginMicrosoft-hosted ubuntu images usually include kubelogin; if not, az aks install-cli
kubectl get deploy myapp -o jsonpath='{.metadata.annotations}'View the azure-pipelines/* traceability annotationsadded by KubernetesManifest

App Service: deploy to a slot and swap

source ~/ado3.env
az appservice plan create -g $RG -n plan-myapp --is-linux --sku S1 -o none
az webapp create -g $RG -p plan-myapp -n myapp-web-$RANDOM \
  --deployment-container-image-name $ACR.azurecr.io/myapp:bootstrap -o table   # note the app name
az webapp deployment slot create -g $RG -n <app name> --slot staging -o table
az webapp config appsettings set -g $RG -n <app name> --settings WEBSITES_PORT=5000 -o none
az webapp config appsettings set -g $RG -n <app name> --slot staging --settings WEBSITES_PORT=5000 -o none
az webapp config appsettings set -g $RG -n <app name> --slot-settings ENVIRONMENT=prod -o none     # slot setting (sticky)
# ACR pull: enable managed identity and grant AcrPull separately for the production slot and the staging slot (each slot has its own identity configuration)
- task: AzureWebAppContainer@1
  displayName: Deploy to staging slot
  inputs:
    azureSubscription: sc-azure-myapp
    appName: $(WEBAPP_NAME)
    deployToSlotOrASE: true
    resourceGroupName: $(RG)
    slotName: staging
    containers: $(ACR_NAME).azurecr.io/myapp:$(Build.BuildId)
- script: bash scripts/smoke.sh "https://$(WEBAPP_NAME)-staging.azurewebsites.net" "$(Build.BuildId)"
  displayName: Smoke staging
- task: AzureAppServiceManage@0
  displayName: Swap staging -> production
  inputs:
    azureSubscription: sc-azure-myapp
    Action: Swap Slots
    WebAppName: $(WEBAPP_NAME)
    ResourceGroupName: $(RG)
    SourceSlot: staging
    SwapWithProduction: true
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --target-slot production
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --action preview   # first apply target settings and warm up
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --action swap      # complete
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --action reset     # cancel preview

How to verify: After the swap, the production URL returns the new version number, and the staging URL returns the old version number. Common errors: The container listens on 5000 but has not set WEBSITES_PORT → the container startup probe times out. Production use: Slots + swap is the standard zero-downtime approach for App Service. Task input names follow the official task reference.

Lab 5 (optional): App Service deployment slot swap (about 10 minutes; S1 plan is billed hourly)

Goal and cost: create an S1 Linux plan + Web App + staging slot, deploy two versions, swap and roll back. S1 is billed hourly; once finished,delete the plan immediately. If you have no budget, just read through, or use the free ACA revision lab (Module 4) instead.
Create resources: run the “one-time creation” from the “Commands” tab. Enable system-assigned identity for both slots and grant AcrPull:
WEBAPP=<app name>
for SLOT in "" "--slot staging"; do
  PID=$(az webapp identity assign -g $RG -n $WEBAPP $SLOT --query principalId -o tsv)
  az role assignment create --assignee-object-id $PID --assignee-principal-type ServicePrincipal --role AcrPull --scope $ACR_ID -o none
  az webapp config set -g $RG -n $WEBAPP $SLOT --generic-configurations '{"acrUseManagedIdentityCreds": true}' -o none
done
Deploy v2 to staging and smoke test
az acr build -r $ACR -t myapp:v2 ~/myapp --no-logs
az webapp config container set -g $RG -n $WEBAPP --slot staging --container-image-name $ACR.azurecr.io/myapp:v2 -o none
az webapp config appsettings set -g $RG -n $WEBAPP --slot staging --settings APP_VERSION=v2 -o none
curl -s https://$WEBAPP-staging.azurewebsites.net/
[v2] Hello from 4f6c1a2b3d9e, hits=N/A (redis not connected)

Note: APP_VERSION is not marked as a slot setting, so it moves to the production slot with the swap.

Swap: az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --target-slot production, then curl both URLs separately: production should be v2, staging should be bootstrap.
Rollback: run the same swap command again; production returns to bootstrap.
(Read-only) Connect the pipeline: put the pipeline snippet from the “Commands” tab into a DeployWebApp stage; use the environment myapp-web-prod and add approval.
Cleanup (required)
az webapp delete -g $RG -n $WEBAPP
az appservice plan delete -g $RG -n plan-myapp --yes

Read-only lab: AKS deployment checklist

  • Cluster: Entra authentication + Azure RBAC,--disable-local-accounts,--attach-acr.
  • Identity: id-ado-myapp Gets Cluster User Role + RBAC Writer on namespace myapp .
  • Pipeline: KubernetesManifest@1 (connectionType: azureResourceManager,containers replaces the image tag,rolloutStatusTimeout).
  • Private cluster: use a self-hosted agent or Managed DevOps Pools that can reach the VNet (Lesson 7).
  • Cleanup: az aks delete -g $RG -n aks-ado-lab --yes --no-wait (AKS nodes are billed hourly).

Case 1: Kubernetes service connection stuck at “Loading namespaces”

Problem: The team created a Kubernetes service connection (Azure Subscription option) for a private AKS cluster, and the UI kept spinning; another connection to a public cluster was created successfully, but the pipeline reported “Could not find any secret associated with the service account”.

Cause (official note): This option requires access to the cluster at creation time; since K8s 1.24, long-lived ServiceAccount tokens are no longer generated by default.

Approach: Switch to KubernetesManifest@1 with the connectionType: azureResourceManager, reusing the WIF service connection; tokens are issued per task with short lifetimes; private clusters use an agent inside the VNet.

Case 2: a slot setting caused production to connect to the test database

Problem: The staging connection string was not marked as a slot setting, so after the swap production connected to the staging database.

Approach: Mark all environment-specific settings (database, key references, telemetry key) as Deployment slot setting; in the pipeline, use az webapp config appsettings list --slot staging to check slotSetting: true.

Case 3: useClusterAdmin flagged in an audit

Problem: To get things working quickly, the pipeline used useClusterAdmin: true, which is equivalent to granting the pipeline cluster administrator permissions.

Approach: Enable --disable-local-accounts, switch to namespace-scoped Azure RBAC roles; track listClusterAdminCredential calls in the audit log.

Common errors and fixes

error: You must be logged in to the server (Unauthorized) / devicecode interactive prompt hangs

Cause: The kubeconfig for an Entra-integrated cluster uses interactive device-code login; the pipeline cannot respond interactively.

Fix: In AzureCLI@2 run kubelogin convert-kubeconfig -l azurecli; or use the ARM connection type with KubernetesManifest@1.

Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "<objectId>" cannot patch resource "deployments" … in the namespace "myapp"

Cause: The WIF identity lacks Kubernetes-level permissions (Azure RBAC or RoleBinding).

az role assignment list --assignee $CLIENT_ID --all -o table | grep -i kubernetes

Fix: Grant Azure Kubernetes Service RBAC Writer (namespace scope) or create a RoleBinding.

Unable to connect to the server: dial tcp … i/o timeout (private cluster)

Cause: Microsoft-hosted agents cannot reach the private API server.

Fix: Use a self-hosted agent inside the VNet / Managed DevOps Pools; or az aks command invoke (suitable for a small number of commands).

Container didn't respond to HTTP pings on port: 80, failing site start

Cause: App Service probes port 80 by default; myapp listens on 5000.

Fix: Set WEBSITES_PORT=5000 (set it on both the production and staging slots).

Swap failed: Failed to swap … warm-up / Cannot swap slots because the site is not running

Cause: The warm-up request to the source slot failed or the app is not running; the swap operation aborts and the production slot is left unchanged.

Fix: Check the staging logs (az webapp log tail --slot staging), fix the issue and retry; configure applicationInitialization the health path.

Command-line exercises
1. Grant the identity write permission on the AKS namespace myapp (Azure RBAC mode).
AKS_ID=$(az aks show -g rg-ado-lab -n aks-ado-lab --query id -o tsv)
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp
az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role "Azure Kubernetes Service Cluster User Role" --scope $AKS_ID
2. Set DB_CONN as a slot setting on the production slot (it does not move with the swap).
az webapp config appsettings set -g rg-ado-lab -n $WEBAPP --slot-settings DB_CONN="@Microsoft.KeyVault(SecretUri=…)"
Scenario analysis
A new version of an App Service app includes a database column rename. How can you release it safely with slot swaps?

Use a two-step “expand-contract” approach: version N+1 is compatible with both old and new columns (add the new column first, write to both), and is swapped live; once no rollback is needed, version N+2 drops the old column. Because old and new versions coexist before and after the swap, and rollback means swapping back to the old version, every release must be compatible with the previous version's database schema.

Verified instructional videos

▶
Deploy to Azure Kubernetes (AKS) from Azure DevOps with Azure Pipelines | Build LIVE with Me — CoderDave
English · hands-on: deploying to AKS from a pipeline
▶
Deploy to Azure Kubernetes Service (AKS) and Container Registry (ACR) using Azure DevOps Pipelines — Andrei Barbu - courscape com
English · ACR + AKS
▶
How to use Deployment Slots in Azure App Service | Azure Tips & Tricks — Microsoft Azure
English · deployment slots
▶
How to use Deployment Slots in Azure App Service for Containers | Azure Tips and Tricks — Microsoft Azure
English · deployment slots for containerized apps

The titles and channels above were verified through the YouTube oEmbed API (2026-11-15). Some videos use the older Kubernetes service connection method; for authentication, follow this lesson.

Official docs

Video storyboard script

Shot 1 · 0:00–0:30
Visual: one service connection icon splits into two lines, one to AKS and one to App Service.
Narration: the same workload identity federation service connection can deploy to Kubernetes or to App Service.
Shot 2 · 0:30–1:10
Visual: the KubernetesManifest task gets a short-lived cluster token from ARM at runtime.
Narration: choose the Azure Resource Manager connection type; the task gets a short-lived token for each step at runtime, and it also works with private clusters and clusters with local accounts disabled.
Shot 3 · 1:10–1:50
Visual: two slot cards; the new version enters staging first, and after the warm-up indicator turns green the two cards swap positions.
Narration: App Service deploys to the staging slot first; after warm-up completes, routing is swapped, so users notice no downtime; to roll back, swap again.
Shot 4 · 1:50–2:10
Visual: settings with a lock icon stay in their original slot.
Narration: values marked as slot settings do not move with the swap; environment settings such as database connections must be marked.
or score ≥ 70% on the “Quiz”

Module 6 · Infrastructure as Code pipelines (Bicep / Terraform)

38:00 – 45:00 · preview changes first, review them manually, then apply the “reviewed version” of the changes
7 minuteswhat-if · plan -out★★★★☆ Essential for the platform
Learning objectives
  • Build a “what-if → approval → deployment create” pipeline for Bicep, and understand what-if's Create / Modify / Delete / NoChange / Ignore results.
  • Build a “plan -out → publish plan artifact → approval → apply that plan” pipeline for Terraform; understand why apply must use the saved plan, and what “Saved plan is stale” means.
  • In AzureCLI@2 , hand the WIF identity over to Terraform (ARM_USE_OIDC,ARM_OIDC_TOKEN=$idToken), and understand the impact of token lifetime.
  • Keep responsibilities clear: the IaC pipeline manages “environments and configuration”, and the application pipeline manages “image versions”, so they do not overwrite each other.
Prerequisites: Modules 2–3; for Terraform basics, see Terraform 8-hour course(Lesson 3 Azure,Lesson 5 CI/CD). Importance: ★★★★☆

What: the standard shape of an IaC pipeline

StageBicepTerraform
Validateaz bicep build,az deployment group validate, linter (bicepconfig.json)terraform fmt -check,validate, tflint
Previewaz deployment group what-ifterraform plan -out=tfplan
ReviewEnvironment approval (paste the what-if summary in the approval instructions)Environment approval (plan output / summary)
Applyaz deployment group create or AzureResourceManagerTemplateDeployment@3terraform apply tfplan (no re-plan)
StateARM itself is the state (deployment history)Remote backend (Azure Storage + lock)

Why: why apply the reviewed plan

  • The approver reviews the plan or what-if output. If the apply stage re-plans, the code or state may have changed in the meantime, so what actually runs is not the change the approver saw.
  • A saved Terraform plan is bound to the state snapshot taken when it was created. If the state changes in the meantime, apply refuses to run (Saved plan is stale) — this is a safeguard, not a failure.
  • Bicep has no saved plan file: a difference can still appear between what-if and create. Run both in the same job on the same commit, and use the what-if result as the basis for approval. For high-risk environments, run what-if again before apply to compare.

How: how identity is passed to IaC tools

ToolApproach
Bicep / ARMAzureCLI@2 directly in az deployment … (already signed in with the service connection identity); or AzureResourceManagerTemplateDeployment@3 (supports WIF and takes .bicep files directly)
Terraform (azurerm)AzureCLI@2 + addSpnToEnvironment: true, export ARM_CLIENT_ID=$servicePrincipalId,ARM_TENANT_ID=$tenantId,ARM_SUBSCRIPTION_ID,ARM_OIDC_TOKEN=$idToken,ARM_USE_OIDC=true; the backend is configured the same way use_oidc = true,use_azuread_auth = true
Terraform (alternative)The Microsoft DevLabs Terraform extension task supports WIF service connections. Newer azurerm versions can also request tokens directly by referencing the Azure DevOps service connection ID (check the provider docs for parameter names).

Token lifetime:$idToken is a short-lived client assertion. When Terraform requests access tokens several times during a run, an expired idToken causes an error AADSTS700024 (Module 7). Mitigations: split long-running applies; use the provider's option to request a fresh ID token from Azure DevOps on demand; or switch to a managed identity service connection (officially recommended for jobs longer than about 1 hour).

When: what goes in IaC and what goes in the app pipeline

IaC pipeline (changes rarely, needs review)App pipeline (changes frequently)
Resource groups, ACR, ACA environment, Container App ingress / scaling / identity / secret references, RBAC, Log AnalyticsImage tags, revision suffixes, traffic weights

To avoid conflicts, default the image parameter in IaC to the image currently running (first read it with az containerapp show and pass it in), or in Terraform use template[0].container[0].image with lifecycle { ignore_changes = [...] }.

Common misconceptions① “What-if shows what will happen” — what-if has known noise (some properties show as Modify but do not actually change) and blind spots (Ignore). When reviewing, focus on Delete and key properties. ② “A plan file can be published as an artifact freely” — a plan may contain sensitive values, and anyone with read access to the project can download pipeline artifacts; restrict project permissions or encrypt the storage. ③ “Terraform needs a client secret” — the azurerm and azuread providers support OIDC. ④ “Complete mode is cleaner for IaC deployments” — Complete mode deletes resources that are not in the template, so misuse can remove resources created by hand or managed by other pipelines.

Flow: Terraform plan → approval → apply

Plan stageinit · validateplan -out=tfplan Pipeline artifacttfplan + lock file+ plan.txt summary Environment myapp-infraApproval (review plan.txt)Exclusive lock sequential Apply stageDownload artifactapply tfplan Remote stateBlob + lease lock Both stages authenticate through AzureCLI@2 + the WIF service connection (ARM_USE_OIDC)
Figure 6-1: the approval covers the plan in the artifact

Illustration: change types in what-if output

+ Create ~ Modify - Delete = NoChange * Ignore Resource-level Delete mainly appears in Complete mode (Incremental mode does not delete resources outside the template) Ignore: the resource exists but is not in the template, or it is outside the what-if evaluation scope Other types such as Deploy (when the specific change cannot be predicted) also exist; follow the actual output
Figure 6-2: when reviewing what-if, prioritize Delete and Modify on networking, identity, and data

Responsibility diagram

infra pipeline (Bicep / Terraform)environment · ingress · scaling · identity · secret references · RBACEnvironment myapp-infra: approval + exclusive lock app pipeline (Module 4)image tags · revisions · trafficEnvironment myapp-dev / myapp-prod
Figure 6-3: the two pipelines change different properties, so IaC does not revert the image to an old version

Step-by-step animation: IaC gates and the “stale plan”

Choose a scenario and play it.

Bicep: infra/app.bicep (creates a separate ca-myapp-iac demo app)

param location string = resourceGroup().location
param envName string = 'cae-myapp'
param appName string = 'ca-myapp-iac'
param image string
param acrServer string
param pullIdentityId string

resource env 'Microsoft.App/managedEnvironments@2024-03-01' existing = {
  name: envName
}

resource app 'Microsoft.App/containerApps@2024-03-01' = {
  name: appName
  location: location
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: { '${pullIdentityId}': {} }
  }
  properties: {
    managedEnvironmentId: env.id
    configuration: {
      activeRevisionsMode: 'Single'
      ingress: { external: true, targetPort: 5000 }
      registries: [ { server: acrServer, identity: pullIdentityId } ]
    }
    template: {
      containers: [ {
        name: 'myapp'
        image: image
        resources: { cpu: json('0.25'), memory: '0.5Gi' }
        env: [ { name: 'APP_VERSION', value: 'iac' } ]
      } ]
      scale: { minReplicas: 0, maxReplicas: 2 }
    }
  }
}

output fqdn string = app.properties.configuration.ingress.fqdn
source ~/ado3.env
az bicep build --file infra/app.bicep
az deployment group what-if -g $RG -f infra/app.bicep \
  -p image=$ACR.azurecr.io/myapp:bootstrap acrServer=$ACR.azurecr.io pullIdentityId=$PULL_ID
Resource and property changes are indicated with this symbol:
  + Create

The deployment will update the following scope:
Scope: /subscriptions/…/resourceGroups/rg-ado-lab
  + Microsoft.App/containerApps/ca-myapp-iac [2024-03-01]
  …
Resource changes: 1 to create.

Bicep pipeline: infra-pipeline.yml

trigger:
  branches: { include: [ main ] }
  paths: { include: [ infra/* ] }
variables: [ { group: myapp-common } ]
pool: { vmImage: ubuntu-latest }
stages:
- stage: WhatIf
  jobs:
  - job: WhatIf
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: sc-azure-myapp
        scriptType: bash
        scriptLocation: inlineScript
        inlineScript: |
          set -euo pipefail
          IMG=$(az containerapp show -g $(RG) -n ca-myapp-iac --query "properties.template.containers[0].image" -o tsv 2>/dev/null || echo "$(ACR_NAME).azurecr.io/myapp:bootstrap")
          echo "##vso[task.setvariable variable=IMG;isOutput=true]$IMG"
          az deployment group what-if -g $(RG) -f infra/app.bicep \
            -p image=$IMG acrServer=$(ACR_NAME).azurecr.io pullIdentityId=$(PULL_ID) | tee whatif.txt
          grep -q "to delete" whatif.txt && echo "##vso[task.logissue type=warning]what-if contains deletes"
          true
      name: wi
- stage: Deploy
  dependsOn: WhatIf
  condition: and(succeeded(), eq(variables['Build.SourceBranch'], 'refs/heads/main'))
  variables:
    IMG: $[ stageDependencies.WhatIf.WhatIf.outputs['wi.IMG'] ]
  jobs:
  - deployment: Deploy
    environment: myapp-infra          # approval + exclusive lock
    strategy:
      runOnce:
        deploy:
          steps:
          - checkout: self
          - task: AzureResourceManagerTemplateDeployment@3
            inputs:
              deploymentScope: Resource Group
              azureResourceManagerConnection: sc-azure-myapp
              action: Create Or Update Resource Group
              resourceGroupName: $(RG)
              location: canadacentral
              templateLocation: Linked artifact
              csmFile: infra/app.bicep
              overrideParameters: -image $(IMG) -acrServer $(ACR_NAME).azurecr.io -pullIdentityId $(PULL_ID)
              deploymentMode: Incremental

Terraform: plan / apply snippet (OIDC)

terraform {
  backend "azurerm" {
    resource_group_name  = "rg-tfstate"
    storage_account_name = "sttfstateXXXX"
    container_name       = "tfstate"
    key                  = "myapp.tfstate"
    use_oidc             = true
    use_azuread_auth     = true     # access Blob with the Entra identity (the identity needs Storage Blob Data Contributor)
  }
}
provider "azurerm" {
  features {}
  use_oidc = true                   # or use only the ARM_USE_OIDC environment variable
}
- stage: Plan
  jobs:
  - job: Plan
    steps:
    - task: AzureCLI@2
      inputs:
        azureSubscription: sc-azure-myapp
        scriptType: bash
        scriptLocation: inlineScript
        addSpnToEnvironment: true
        workingDirectory: tf
        inlineScript: |
          set -euo pipefail
          export ARM_CLIENT_ID=$servicePrincipalId ARM_TENANT_ID=$tenantId \
                 ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) \
                 ARM_OIDC_TOKEN=$idToken ARM_USE_OIDC=true
          terraform init -input=false
          terraform plan -input=false -out=tfplan -detailed-exitcode || [ $? -eq 2 ]
          terraform show -no-color tfplan > plan.txt
    - publish: tf
      artifact: tfplan                 # includes tfplan, .terraform.lock.hcl, plan.txt (watch for sensitive information)
- stage: Apply
  dependsOn: Plan
  jobs:
  - deployment: Apply
    environment: myapp-infra
    strategy:
      runOnce:
        deploy:
          steps:
          - download: current
            artifact: tfplan
          - task: AzureCLI@2
            inputs:
              azureSubscription: sc-azure-myapp
              scriptType: bash
              scriptLocation: inlineScript
              addSpnToEnvironment: true
              workingDirectory: $(Pipeline.Workspace)/tfplan
              inlineScript: |
                set -euo pipefail
                export ARM_CLIENT_ID=$servicePrincipalId ARM_TENANT_ID=$tenantId \
                       ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) \
                       ARM_OIDC_TOKEN=$idToken ARM_USE_OIDC=true
                terraform init -input=false
                terraform apply -input=false tfplan

Notes:-detailed-exitcode Exit code 2 means there are changes (not an error). Downloaded artifacts do not keep file permissions or .terraform directories, so in Apply, re-run init. The Terraform version and provider parameter details follow the Terraform courseand the official docs.

Lab 6: Bicep what-if → approval → deploy (about 8 minutes)

Goal: create with the pipeline ca-myapp-iac, see the what-if output before approval. Cost: close to zero (min-replicas 0).
Create environment myapp-infra and add approval + exclusive lock (same steps as Module 3).
Commit the files: infra/app.bicep and pipelines/infra-pipeline.yml (Commands tab), then:
az pipelines create --name myapp-infra --yaml-path pipelines/infra-pipeline.yml \
  --repository myapp --repository-type tfsgit --branch main
Review: open the WhatIf job log and confirm that only + Create … ca-myapp-iac; approve in the Review of the Deploy stage (the approval notes say “what-if: 1 to create”).
Verify
az deployment group list -g $RG --query "[0].{name:name,state:properties.provisioningState,ts:properties.timestamp}" -o table
FQDN=$(az containerapp show -g $RG -n ca-myapp-iac --query properties.configuration.ingress.fqdn -o tsv); curl -s https://$FQDN/
Name    State      Ts
------  ---------  --------------------------------
app     Succeeded  2026-11-15T10:42:07.123456+00:00
[iac] Hello from ca-myapp-iac--1a2b3c4-…, hits=N/A (redis not connected)
Change one property and run again: change maxReplicas to 3 and commit; what-if shows ~ Modify and the property difference; it takes effect after approval again.
Cleanup: az containerapp delete -g $RG -n ca-myapp-iac --yes; delete the myapp-infra pipeline (optional).

Case 1: Complete mode deleted the Log Analytics workspace

Problem: Someone changed deploymentMode to Complete to “clean up” resources outside the template, which deleted another team's Log Analytics workspace in the same resource group.

Approach: Keep Incremental mode; manage each resource group with only one IaC set; when what-if shows Delete, the pipeline outputs a warning and the approval notes must list it. Azure Deployment Stacks can provide safer “managed deletion” (for reference).

Case 2: plan was approved two hours later, and apply failed

Problem: apply reports Saved plan is stale. Meanwhile, another pipeline changed the same state.

Approach: Add the sequential exclusive lock to the environment so only one pipeline runs plan/apply against the same state; when rejected, rerun plan. Also set an approval timeout to avoid approving a stale plan.

Case 3: IaC reverted the image to bootstrap

Problem: After every infra pipeline run, prod went back to the image hard-coded in the template.

Approach: Take the image parameter from the currently running value (for example, using the IMG read logic in this lesson's Bicep pipeline), or in Terraform ignore_changes; only the app pipeline changes the image version.

Common errors and fixes

Error: Saved plan is stale

Cause: The state was changed after the plan was saved (another apply, or manual import/state operations).

Fix: Rerun the Plan stage; configure the IaC environment with the sequential exclusive lock.

Error building ARM Config: … OIDC token … / AADSTS700024: Client assertion is not within its valid time range

Cause:$idToken Expired (Terraform requests a token again after a long run).

Fix: Shorten each apply; use the provider's option to request a new ID token from Azure DevOps (see the azurerm docs); or use a managed identity service connection.

Error: Failed to get existing workspaces: … AuthorizationPermissionMismatch (backend)

Cause:use_azuread_auth = true When using Entra auth, the identity needs the Storage Blob Data Contributor (data-plane role); Contributor is not enough.

az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role "Storage Blob Data Contributor" --scope $(az storage account show -n sttfstateXXXX --query id -o tsv)
InvalidTemplateDeployment / The template deployment 'app' is not valid according to the validation procedure

Cause: A parameter is missing or has the wrong type, the API version does not support a property, or the referenced existing resource does not exist.

az deployment group validate -g $RG -f infra/app.bicep -p image=… acrServer=… pullIdentityId=…
az deployment operation group list -g $RG -n app --query "[?properties.provisioningState=='Failed'].properties.statusMessage"
what-if shows the same Modify every time, but nothing changes after deployment

Cause: Known what-if noise (service-side defaults, format normalization).

Fix: Write the service-side defaults explicitly in the template; during review, focus on Delete and key properties; follow the Bicep / ARM what-if release notes.

Command-line questions
1. Use what-if to output only a change summary (without property details).
az deployment group what-if -g rg-ado-lab -f infra/app.bicep -p @params.json --result-format ResourceIdOnly
2. Write the environment variables that let Terraform use WIF inside AzureCLI@2.
export ARM_CLIENT_ID=$servicePrincipalId ARM_TENANT_ID=$tenantId \
       ARM_SUBSCRIPTION_ID=$(az account show --query id -o tsv) \
       ARM_OIDC_TOKEN=$idToken ARM_USE_OIDC=true    # requires addSpnToEnvironment: true
Scenario analysis
The platform team requires that any Terraform change needs two approvals, and that apply never uses a plan the approver has not reviewed. Design the pipeline.

The Plan stage generates tfplan + plan.txt and publishes it as an artifact; the Apply stage is a deployment job targeting environment infra-prod configure approval (the approver is a group requiring at least 2 people; to enforce multiple approvers, configure two approval checks or use the multiple-approver setting, as shown in the UI), branch control for main, and the sequential exclusive lock; Apply only downloads and runs the same run's tfplan, without re-planning; if any state change makes the plan stale, it fails and must be rerun. Add a required template check on the service connection so that only the standard IaC template can use the prod identity.

Verified teaching videos

▶
Deploy Bicep with Azure DevOps Pipelines... from scratch! — Chris Fulstow
English · Bicep pipeline from scratch
▶
Azure DevOps Pipelines and Bicep — Travis Roberts
English · Bicep and pipelines
▶
Azure DevOps Pipelines with Terraform and Stages — Travis Roberts
English · Terraform multi-stage
▶
Manual Approval | Azure DevOps Environments for Terraform (YAML) — Luke Byrne (AI Luke)
English · Terraform approvals

The titles and channels above were verified through the YouTube oEmbed API (2026-11-15). Some videos use client secret authentication; follow this lesson's WIF / OIDC approach.

Official docs

Video storyboard script

Shot 1 · 0:00–0:30
Visual: a “change preview” scroll unrolls, showing plus, tilde, and minus signs.
Narration: the infrastructure pipeline previews changes first: Bicep uses what-if, Terraform uses plan.
Shot 2 · 0:30–1:10
Visual: the plan file is put into an artifact box; the approver stamps it after review, and the box is delivered unchanged to apply.
Narration: the approver approves the plan inside the artifact; apply runs only that plan and does not re-plan.
Shot 3 · 1:10–1:40
Visual: another pipeline quietly changes the state, and apply shows a red light with “Saved plan is stale.”
Narration: if the state is changed in the meantime, Terraform refuses to run the stale plan; this is a safeguard.
Shot 4 · 1:40–2:10
Visual: two pipelines each manage one set of properties: environment configuration and image version.
Narration: the infrastructure pipeline manages the environment and the app pipeline manages the image, so they do not overwrite each other.
or score ≥ 70% on the Quiz

Module 7 · Troubleshooting cloud deployments in practice

45:00 – 54:00 · Locate faults by layer: pipeline authorization → checks → token exchange → ARM authorization → registry / runtime → application
9 minutesAADSTS · AuthorizationFailed · 401★★★★★ Hands-on
Learning objectives
  • Place any cloud deployment failure into one of six layers, and state the first diagnostic command for each layer.
  • Read and fix: AADSTS700213 (subject mismatch),AADSTS700211 (issuer mismatch),AADSTS700024 (assertion expired),AADSTS70025,AADSTS7000215.
  • Fix AuthorizationFailed (missing RBAC / wrong scope / propagation delay), a service connection not authorized for the pipeline (yamlauthz), a disabled service connection, approval timeout, and ACR 401 (push and pull).
  • Complete one fault-injection drill using the interactive troubleshooting tree.
Prerequisites: Modules 2–4. Importance: ★★★★★

What: the six-layer model

LayerWhere it happensTypical signalsFirst diagnostic
L1 Pipeline compilation and authorizationBefore the run starts…could not be found. The service connection does not exist, has been disabled or has not been authorized for use; “This pipeline needs permission to access a resource”Service connection → Security → Pipeline permissions; check whether it is disabled
L2 Approvals and checksBefore the stage startsWaiting for review, Branch control failed, stage skippedChecks panel on the run page
L3 Token exchange (Entra)Sign-in step of the Azure taskAADSTS7002xx,AADSTS70025,AADSTS7000215Compare the issuer / subject / clientId of the service connection and the federated credential
L4 ARM authorizationWhen calling ARMAuthorizationFailed, 403,ResourceGroupNotFound,SubscriptionNotFoundaz role assignment list --assignee <clientId> --all
L5 Data plane / runtimeACR, ACA revisions, AKS APIACR 401 unauthorized, revision Provisioning failed, ImagePull failureaz containerapp logs show --type system, ACR role
L6 ApplicationSmoke test000 / 5xx / version mismatchRevision FQDN, targetPort, application logs

Why: why use layers

The same “deployment failed” message can come from any layer. Problems in L1–L2 make no Azure calls at all (so they do not appear in the Azure activity log); L3 problems appear in the Entra sign-in logs (service principal sign-ins); L4 appears in the Azure activity log; L5–L6 appear in resource logs. Layering lets you go straight to the right log to find evidence.

How: quick reference for the 8 most common errors

ErrorLayerRoot causeFix
AADSTS700213 … presented assertion subjectL3Federated credential subject does not match the token sub, or no credential existsRebuild the federated credential using the subject shown for the service connection
AADSTS700211 … presented assertion issuerL3Issuer mismatch (issuer has switched to Entra)Add a federated credential for the current issuer
AADSTS700024 Client assertion is not within its valid time rangeL3ID token expired (the script requests a token only after running for a long time, or the job runs longer than about 1 hour)Move token-related commands earlier; use a managed identity connection; split the job
AuthorizationFailed … does not have authorization to perform actionL4Identity lacks the role, wrong scope, or the new assignment has not propagated yetAssign the minimum role at the correct scope, then wait a few minutes
…has not been authorized for use … aka.ms/yamlauthzL1Service connection not authorized for this pipeline / disabled / name misspelledPermit, or add it under Pipeline permissions; re-enable it
stage skipped (approval timed out)L2Approval not completed within the timeoutRerun stage; change the approver to a group; adjust the timeout
ACR push unauthorized: authentication requiredL5Pipeline identity has no AcrPush / ACR Tasks permission; the connection points to a different registryGrant AcrPush (or Contributor for az acr build)
ACA revision pull fails (unauthorized)L5Runtime identity has no AcrPull / the registry is not configured to use a managed identityaz containerapp registry set --identity + AcrPull

Note: if the ACR uses the “RBAC Registry + ABAC Repository Permissions” permission model, legacy roles such as AcrPush / AcrPull no longer apply, and you must use the Container Registry Repository role series instead; follow the official ACR docs. A service connection unused for 100 days may be disabled automatically (visible in the audit log).

When: which log to check and when

LogWhat to look forCommand / location
Pipeline logs (system.debug=true)Internal task requests and detailed az command outputSet a variable at run time system.debug to true
Entra sign-in logs (service principal sign-ins)AADSTS errors, issuer, clientEntra admin center → Sign-in logs → Service principal / Managed identity sign-ins
Azure activity logWho did what to a resource and when, AuthorizationFailedaz monitor activity-log list -g rg-ado-lab --offset 1h
Azure DevOps audit logChanges to and disabling of service connections / checksOrganization settings → Auditing
ACA system / console logsImage pulls, probes, crashesaz containerapp logs show --type system|console
Common misconceptions① “An AADSTS error means an RBAC problem” — AADSTS happens before the token is obtained (L3), and RBAC comes after (L4). ② “Rerun right after adding a role should fix it” — RBAC propagation can take a few minutes, and group memberships cached in the token must also be refreshed. ③ “Grant access permission to all pipelines solves authorization issues” — it does, but it also lets every pipeline use this identity, so authorize pipelines one by one. ④ “AcrPull is enough to push images” — pushing requires AcrPush.

Layer diagram: from “run starts” to “smoke test passes”

L1 Pipeline compilation and resource authorization · yamlauthz · service connection disabled · name spelling L2 Approvals and checks · branch control · approval timeout (skipped) · exclusive lock · business hours L3 Token exchange · AADSTS700213 / 700211 / 700024 / 70025 / 7000215 / 700223 L4 ARM authorization · AuthorizationFailed · scope · propagation delay L5 Data plane / runtime · ACR 401 · revision pull failure · AKS Forbidden L6 Application · smoke test 000/5xx · targetPort · version mismatch
Figure 7-1 Troubleshoot top-down: if an upper layer fails, the layers below never run

Reference diagram: where to find evidence when an error occurs

Pipeline logsL1 and L2, allError text for L3–L6system.debug Entra sign-in logsL3: service principal /managed identity sign-in failuresError codes and issuer Azure activity logL4: write operations andAuthorizationFailedcaller = clientId Resource logsL5 L6: ACA system /console, ACR logsLog Analytics
Figure 7-2 L1/L2 problems leave no trace on the Azure side

Sequence diagram: where AuthorizationFailed occurs

Token exchange succeeds (L3 ✓)az login completed PUT containerApps/…Bearer token ARM RBAC evaluationNo Microsoft.App/*/write 403AuthorizationFailed
Figure 7-3: seeing AuthorizationFailed means the identity signed in correctly; the problem is only the role and scope

Interactive: error classifier

Paste an error from the pipeline (or click an example). The classifier uses keywords to identify the layer and gives a first diagnostic step and a fix. The rules are based on the official troubleshooting docs and match only the errors covered in this lesson.

Waiting for input.

Troubleshooting command list

LayerCommandPurpose
L1az devops service-endpoint show --id $SC_ID --query "{ready:isReady,disabled:isDisabled,shared:isShared}"Whether the connection is ready / disabled (check the actual output for field names)
L1az devops invoke --area pipelinePermissions --resource pipelinePermissions --route-parameters project=$ADO_PROJECT resourceType=endpoint resourceId=$SC_ID --api-version 7.1-previewSee which pipelines are authorized to use this connection (REST; check the API docs for the route)
L3az devops service-endpoint show --id $SC_ID --query authorization.parametersissuer / subject / clientId
L3az identity federated-credential list -g $RG --identity-name $ID_NAME -o tableFederated credentials
L4az role assignment list --assignee $CLIENT_ID --all -o tableAll role assignments of the identity
L4az monitor activity-log list -g $RG --offset 2h --query "[?status.value=='Failed'].{op:operationName.value,who:caller,st:subStatus.value}" -o tableFailed ARM operations
L5az acr check-health -n $ACR --yesACR connectivity and authentication self-check
L5az containerapp logs show -g $RG -n $APP --type system --tail 50Image pulls, revision events
L5az containerapp show -g $RG -n $APP --query properties.configuration.registriesWhether the registry uses a managed identity
L6az containerapp revision list -g $RG -n $APP -o tableRevision status, weights
#!/usr/bin/env bash
source ~/ado3.env
echo "== L3 service connection vs federated credential"
az devops service-endpoint show --id $(az devops service-endpoint list --query "[?name=='$SC_NAME'].id" -o tsv) \
  --query "authorization.parameters.{client:serviceprincipalid,iss:workloadIdentityFederationIssuer,sub:workloadIdentityFederationSubject}" -o yaml
az identity federated-credential list -g $RG --identity-name $ID_NAME --query "[].{iss:issuer,sub:subject}" -o yaml
echo "== L4 role assignments of $CLIENT_ID"
az role assignment list --assignee $CLIENT_ID --all --query "[].{role:roleDefinitionName,scope:scope}" -o table
echo "== L5 pull identity on apps"
for A in $APP_DEV $APP_PROD; do az containerapp show -g $RG -n $A --query "{app:name,reg:properties.configuration.registries[0]}" -o json; done
echo "== L5 AcrPull holders"
az role assignment list --scope $ACR_ID --query "[].{role:roleDefinitionName,who:principalName}" -o table
== L4 role assignments of 00001111-aaaa-2222-bbbb-3333cccc4444
Role         Scope
-----------  ---------------------------------------------------------------------------
Contributor  /subscriptions/…/resourceGroups/rg-ado-lab
AcrPush      /subscriptions/…/resourceGroups/rg-ado-lab/providers/Microsoft.ContainerRegistry/registries/acrmyapp21877

Lab 7: fault injection and fixes (about 10 minutes)

Notes: inject only one fault at a time, run the pipeline, locate the problem with the troubleshooting tree on the Troubleshooting tab, fix it, then do the next one. Cost: close to zero. Can be done in pairs, one person injects faults and the other troubleshoots.
Fault A: service connection not authorized (L1): Service connection → Security → Pipeline permissions → remove the myapp pipeline → run.
There was a resource authorization issue: "The pipeline is not valid. Job Dev: Step AzureContainerApps input
connectedServiceNameARM references service connection sc-azure-myapp which could not be found. The service connection
does not exist, has been disabled or has not been authorized for use. For authorization details, refer to https://aka.ms/yamlauthz."

Fix: on the run page, click Authorize resources / Permit, or re-add the pipeline permission.

Fault B: subject mismatch (L3)

First, obtain again the first three lines from the “Commands” section 3 of Module 2: $SC_ID,$ISSUER,$SUBJECT.

source ~/ado3.env
az identity federated-credential delete -g $RG --identity-name $ID_NAME -n fic-ado-myapp --yes
az identity federated-credential create -g $RG --identity-name $ID_NAME -n fic-ado-myapp \
  --issuer "$ISSUER" --subject "${SUBJECT}x" --audiences api://AzureADTokenExchange -o none   # deliberately adds an extra x

Expected: AADSTS700213: No matching federated identity record found for presented assertion subject (the wording may include an AADSTS70021 prefix description). Fix: rebuild the $SUBJECT with the correct value.

Fault C: missing RBAC (L4)
az role assignment delete --assignee $CLIENT_ID --role Contributor --scope /subscriptions/$SUB_ID/resourceGroups/$RG
(AuthorizationFailed) The client '00001111-aaaa-…' with object id 'aaaaaaaa-bbbb-…' does not have authorization to perform
action 'Microsoft.App/containerApps/write' over scope '/subscriptions/…/resourceGroups/rg-ado-lab/providers/Microsoft.App/containerApps/ca-myapp-dev'
or the scope is invalid. If access was recently granted, please refresh your credentials.

Fix: reassign Contributor (or a smaller custom role), wait 1–5 minutes, then rerun.

Fault D: approval timeout (L2): set the myapp-prod approval timeout to 1 minute (for the lab), run the pipeline, and do not approve. Expected: DeployProd shows Skipped. Fix: restore the timeout, then Rerun stage.
Fault E: runtime pull failure (L5)
az role assignment delete --assignee $(az identity show -g $RG -n $PULL_ID_NAME --query principalId -o tsv) --role AcrPull --scope $ACR_ID

Expected: in the deploy hook of DeployProd, the new revision's provisioningState becomes Failed (or stays unprovisioned for a long time), and the system logs show that the image pull is not authorized; on.failure the rollback runs. Fix: reassign AcrPull. Note: running replicas are not affected; only new revisions fail to pull.

Wrap-up: run scripts/doctor.sh Confirm that all roles and federated credentials are restored, then run the full pipeline once more successfully.

Case 1: after the organization was renamed, all deployments failed with AADSTS70021

Symptom: The organization was renamed from contoso-old to contoso, and all manually created legacy WIF connections failed, with the error showing Assertion Subject as sc://contoso/….

Diagnosis: L3; Entra sign-in logs show the issuer and subject; the federated credential still uses the old organization name.

Fix: Bulk-update to the Entra issuer (subject is based on the ID), and rebuild the federated credentials with the new values; future renames will no longer have an effect.

Case 2: “it worked yesterday” — the service connection was disabled automatically

Symptom: A disaster-recovery pipeline that runs once per quarter reported “…has been disabled or has not been authorized for use”.

Diagnosis: L1; the audit log has a service connection disabled event (official note: ARM service connections unused for 100 days may be disabled automatically).

Fix: Project settings → Service connections → re-enable it; for infrequently used pipelines, schedule a monthly run (only a “Who am I” validation).

Case 3: AuthorizationFailed appears only in prod

Symptom: dev works, but prod reports AuthorizationFailed, with the scope in a different subscription.

Diagnosis: L4; the prod resources are in a different subscription, but the service connection's identity has a role only in the dev subscription.

Fix: Create a separate service connection and identity for prod, grant the role only on the prod resource group, and use different azureSubscription per stage in the YAML.

Interactive troubleshooting tree

Start from the symptom, answer the questions step by step, and get the diagnosis and fix commands.

Additional common errors

AADSTS7000215: Invalid client secret provided

Legacy secret-based connection, secret expired. Fix: convert to WIF (Module 2).

AADSTS700016: Application with identifier '…' wasn't found

Identity deleted or the clientId is wrong. Fix: confirm that serviceprincipalid is the clientId of an existing identity.

AADSTS70052: The identity must be a managed identity, a single tenant app, or a service account

The Entra issuer does not support multi-tenant app registrations. Fix: signInAudience: AzureADMyOrg, one connection per tenant.

(ResourceGroupNotFound) Resource group 'rg-ado-lab' could not be found.

The service connection points to another subscription, or the resource group has been deleted. Fix: az account show (in AzureCLI@2) to confirm the subscription.

Command-line questions
1. Write a command that lists the failed ARM operations and their callers in rg-ado-lab over the past 2 hours.
az monitor activity-log list -g rg-ado-lab --offset 2h \
  --query "[?status.value=='Failed'].{time:eventTimestamp,op:operationName.value,caller:caller}" -o table
2. How do you quickly confirm whether a managed identity has AcrPull on the ACR?
az role assignment list --scope $ACR_ID --assignee $(az identity show -g rg-ado-lab -n id-myapp-pull --query principalId -o tsv) -o table
Scenario analysis
Pipeline log: AzureCLI@2 runs tests for the first 12 minutes, then az storage blob upload fails with AADSTS700024. Why did the earlier az commands work? How do you fix it?

Before the script starts, AzureCLI@2 has already completed az login with the ID token. But some commands need an access token for another resource (such as Storage), and at that point the CLI uses the client assertion again to exchange for a token, while the ID token has already expired. Official guidance: move commands that need tokens (such as storage operations) to the start of the script so the token is cached; or split testing and upload into two steps / two tasks (each task obtains a fresh ID token); for jobs longer than about 1 hour, use a managed identity service connection.

Verified teaching videos

▶
Azure DevOps Workload Identity Federation with Azure Overview. NO MORE SECRETS! — John Savill's Technical Training
English · Review the token flow and understand where L3 errors come from
▶
Azure DevOps Environments: Checks and Gates DEEP DIVE — CoderDave
English · L2 check behavior

The titles and channels above were verified through the YouTube oEmbed API (2026-11-15). No verified video was found that specifically explains troubleshooting AADSTS700213 / AuthorizationFailed; use this page's troubleshooting tree and the official troubleshooting docs.

Official docs

Video storyboard script

Shot 1 · 0:00–0:25
Visual: a cross-section of a six-story building, with red alarm lights flashing on different floors.
Narration: a cloud deployment failure can be split into six layers: pipeline authorization, checks, token exchange, resource manager authorization, registry and runtime, and the application itself.
Shot 2 · 0:25–1:00
Visual: the AADSTS error card lands on the third floor, and the AuthorizationFailed card lands on the fourth floor.
Narration: errors starting with AADSTS happen when the token is obtained; AuthorizationFailed means sign-in succeeded and only a role is missing.
Shot 3 · 1:00–1:40
Visual: the troubleshooting tree expands level by level and finally gives one fix command.
Narration: use the troubleshooting tree to narrow down from the symptom step by step; each leaf gives a diagnostic command and a fix.
Shot 4 · 1:40–2:10
Visual: icons for four kinds of logs: pipeline, Entra sign-in, activity log, resource log.
Narration: the value of layering is finding evidence in the right log: problems in the first two layers cannot be found in Azure at all.
or score ≥ 70% on the Quiz

Module 8 · Cost, cleanup and self-test

54:00 – 60:00 · Know where the money goes, and delete everything in the right order (including identities, federated credentials, and service connections)
6 minutesBudget · cleanup checklist★★★★☆ Required
Learning objectives
  • List the resources in this lesson that incur charges and how they are billed: ACR (per day), ACA (per vCPU-second / GiB-second / request, including the free allowance), Log Analytics (per ingestion), App Service (per plan instance-hour), AKS (node VM hours), and Microsoft-hosted parallel jobs.
  • Use the cost estimator to estimate the cost of one lab run, and set a budget alert on the subscription.
  • Clean up in order: the Azure DevOps side (pipelines / environments / service connections / variables) and the Azure side (resource groups, identities, role assignments, federated credentials), and check for leftover permissions.
Prerequisites: Modules 0–7. Importance: ★★★★☆

What: the cost structure of this lesson

ResourceBilling methodScale in this lessonCost-saving tips
Azure Container Registry BasicFixed daily fee + storage overage; ACR Tasks billed by build duration1 registry, a few imagesDelete at the end of the lab; in production use retention policies / purge
Azure Container Apps (consumption plan)vCPU-seconds and GiB-seconds at active / idle rates + request count; the first 180,000 vCPU-seconds, 360,000 GiB-seconds, and 2 million requests per subscription per month are free3 apps, 0.25 vCPU / 0.5 GiB, min 0min-replicas 0; deactivate old revisions (inactive revisions are not billed)
Log AnalyticsBilled per GB ingested (for plans with a free ingestion allowance, check the pricing page)Very smallSet a daily cap; delete the resource group
App Service S1 (optional)Billed per plan instance-hour; slots share instances1 instanceDelete the plan right after finishing
AKS (optional reading)Node VM hours + disks + LB; control plane tier is billed separately—Delete or stop the cluster when not in use
Azure DevOpsThe first 5 Basic users are free; Microsoft-hosted parallel jobs have a free allowance of 1,800 minutes per month (billing must be linked)1 parallel jobWaiting for approval does not use a parallel job
Managed identities, RBAC, federated credentials, service connectionsFree—but leftover permissions are a security risk

Why: why cleanup order matters

  • Deleting the resource group first also deletes the UAMI inside it (and its federated credentials), but the service connection in Azure DevOps remains, and the UI keeps showing a “broken” connection. Conversely, if you delete the service connection first, the identity and roles in Azure remain —both sides must be deleted.
  • A service connection created manually is not deleted by Azure DevOps together with the identity you created yourself; for an app registration created by the automatic method, check under Entra “App registrations” after deletion whether it was removed with the connection.
  • Role assignments at subscription or other scopes are not deleted with the resource group and need to be checked separately.
  • After a resource group is deleted, the Log Analytics workspace may stay in soft-deleted state for a while, which affects recreating one with the same name (follow the official documentation).

How: cleanup checklist

#LocationObjectCommand
1Azure DevOpsDisable / delete lab pipelines (gates-demo, myapp-infra)az pipelines delete --id … --yes
2Azure DevOpsEnvironments myapp-dev / myapp-prod / myapp-infraPipelines → Environments → ⋮ → Delete
3Azure DevOpsService connections sc-azure-myapp (and sc-acr-myapp)az devops service-endpoint delete --id $SC_ID --yes
4Azure DevOpsVariables such as ACR_NAME in the variable groupaz pipelines variable-group variable delete
5AzureRole assignments at subscription or other scopesaz role assignment list --assignee $CLIENT_ID --all
6AzureResource group rg-ado-lab (ACR, ACA, environment, Log Analytics, UAMI and its federated credentials)az group delete -n rg-ado-lab --yes --no-wait
7EntraApp registration (if the automatic method was used)az ad app list --display-name … → az ad app delete
8AzureBudget (keep or delete)Cost Management → Budgets

When: when to clean up

If you go straight toLesson 4 (AWS), the Azure resources can be deleted first (Lesson 4 does not depend on them), but keep the Azure DevOps project myapp-lab, repositories and CI pipelines. Lesson 5 uses multi-environment deployment again; recreate the resources following Module 0 of this lesson then (about 5 minutes).

Common misconceptions① “Deleting the resource group means everything is clean” — the service connections and environments on the Azure DevOps side, and role assignments outside the resource group, still exist. ② “Deactivated revisions still cost money” — inactive revisions are not billed. ③ “ACA scaled to 0 is completely free” — ACR and Log Analytics are still billed per day / per usage. ④ “Free parallel jobs need no attention” — they are obtained automatically only after billing is set up for the organization; beyond 1,800 minutes, runs are queued.

Resource diagram: what is on each side during cleanup

Azure DevOps (project myapp-lab) Service connections sc-azure-myapp / sc-acr-myapp Environments myapp-dev / myapp-prod / myapp-infra (including checks) Pipelines gates-demo / myapp-infra Azure variables in the variable group myapp-common Keep: project, repositories, CI pipelines Azure (rg-ado-lab) ACR · ACA environment · 3 Container Apps Log Analytics workspace UAMI id-ado-myapp (+ federated credential) / id-myapp-pull Role assignments scoped to the resource group Also check: subscription-level role assignments, Entra app registrations
Figure 8-1: clean up both sides; Entra app registrations are not in the resource group

Cost share illustration (default configuration in this lesson, 3-hour lab)

ACR Basic (billed per day, even if unused) Log Analytics ACR Tasks ACA (≈ within the free allowance) Illustrative proportions, not exact billing; the total is usually under 1 US dollar if the optional labs are skipped
Figure 8-2: the ACA free allowance covers the lab; the fixed cost comes from ACR

Interactive: cost estimator

Unit prices are editable sample values (in US dollars, based on public price levels; for actual canadacentral prices, use the pricing calculator to check). The ACA free allowance per the official figures: 180,000 vCPU-seconds, 360,000 GiB-seconds, and 2 million requests per subscription per month.

Edit sample unit prices

Interactive: cleanup order check

Click the cleanup steps in the order you think is correct; the system will flag omissions or risks.

Start with the Azure DevOps side.

Cleanup commands (in order)

source ~/ado3.env
az devops configure --defaults organization=$ADO_ORG project=$ADO_PROJECT
# 1) Pipelines (delete only the lab ones, keep CI)
for P in gates-demo myapp-infra; do
  ID=$(az pipelines show --name $P --query id -o tsv 2>/dev/null) && az pipelines delete --id $ID --yes
done
# 2) Service connections
for S in sc-azure-myapp sc-acr-myapp; do
  ID=$(az devops service-endpoint list --query "[?name=='$S'].id" -o tsv)
  [ -n "$ID" ] && az devops service-endpoint delete --id $ID --yes
done
# 3) Azure variables in the variable group
VG=$(az pipelines variable-group list --group-name myapp-common --query "[0].id" -o tsv)
for V in ACR_NAME RG ACA_ENV APP_DEV APP_PROD PULL_ID; do
  az pipelines variable-group variable delete --group-id $VG --name $V --yes 2>/dev/null
done
# 4) Role assignments outside the resource group (should be empty)
az role assignment list --assignee $CLIENT_ID --all --query "[?!contains(scope,'$RG')].{role:roleDefinitionName,scope:scope}" -o table
# 5) Resource group (including the UAMI and federated credentials)
az group delete -n $RG --yes --no-wait
az group wait -n $RG --deleted --timeout 1800 && echo "rg deleted"
rg deleted

Environments must be deleted in the web UI (Pipelines → Environments → select the environment → ⋮ → Delete), or with REST: az devops invoke --area distributedtask --resource environments --route-parameters project=$ADO_PROJECT environmentId=<id> --http-method DELETE --api-version 7.1 (check the REST docs for route parameters).

Verify cleanup

CommandExpected
az group exists -n rg-ado-labfalse
az devops service-endpoint list --query "[].name" -o tsvsc-azure-myapp no longer exists
az role assignment list --assignee $CLIENT_ID --all[] (after the identity is deleted, a “principal not found” message may also appear)
az ad app list --display-name <auto-generated name> --query "[].appId"Empty (if the automatic method was used)

Budget alert

Recommended in the Azure portal: Cost Management → Budgets → Add → amount 10 US dollars / month → alert thresholds 50%, 90%, 100% → email. CLI az consumption budget create can also be used to create it (check the parameters in --help ). A budget only alerts and does not stop spending.

Lab 8: estimation, cleanup and verification (about 6 minutes)

Estimate: in the cost estimator on the Animations tab, enter your actual lab duration and configuration and record the estimate; afterward (after 24–48 hours), check the actual cost in Cost Management for the resource group rg-ado-lab and compare.
Export deployment evidence (optional, for review):
az containerapp revision list -g $RG -n $APP_PROD --all -o table > prod-revisions.txt
az monitor activity-log list -g $RG --offset 24h --query "[].{t:eventTimestamp,op:operationName.value,who:caller,st:status.value}" -o table > activity.txt
Run cleanup: run the steps in the order on the Commands tab; delete the three environments in the web UI.
Verify: run the commands in the “Verify cleanup” table; all should match the expected results.
Keep: the myapp-lab project, repositories, CI pipelines,~/ado3.env (variable names reusable in Lesson 5).

Self-check list (answer without notes)

Case 1: forgotten lab AKS

Problem: After the training ended, 3 AKS clusters kept running for a month.

Approach: Tag all lab resource groups consistently purpose=lab,expires=2026-11-16; a daily scheduled pipeline (WIF service connection, with permissions only on the lab subscription) deletes expired resource groups.

Case 2: a departed employee's service connection still had subscription Owner

Problem: A security audit found that the app registration behind a service connection created automatically years ago held a subscription-level role, although the related project had long been retired.

Approach: Run a script periodically: list all ARM service connections (scheme, creationMode, last-used time) and the role assignments of their identities; disable and then delete the unused ones, and also delete the Entra app registrations and role assignments.

Case 3: Log Analytics bill exceeded the app itself

Problem: The ACA app printed large volumes of debug logs, so Log Analytics ingestion cost far exceeded compute cost.

Approach: Lower the log level; set a daily cap and an appropriate table plan on the workspace; shorten the log retention period for the dev environment.

Common issues during cleanup

Cannot delete resource group … because it contains resources that are locked

The resource has a delete lock (CanNotDelete). az lock list -g $RG -o table → az lock delete Remove the lock, then delete.

Service endpoint … is in use by … and cannot be deleted / service connection deletion fails

In some cases the connection is shared with, or in use by, other projects. First remove the project sharing in Security or wait for runs to finish; shared connections must be deleted in the source project.

Recreating a Log Analytics workspace with the same name fails (name in use)

The workspace is in soft-deleted state. Wait for the soft-delete period to end, or recover or permanently delete it in the portal (follow the official docs); in a lab, simply use a different name.

az group delete takes a very long time

Deleting an ACA environment takes several minutes. az group wait --deleted Wait, or check deletion progress in the portal.

Command-line questions
1. Delete the service connection named sc-azure-myapp.
az devops service-endpoint delete --id $(az devops service-endpoint list --query "[?name=='sc-azure-myapp'].id" -o tsv) --yes
2. List all role assignments of an identity outside the resource group.
az role assignment list --assignee $CLIENT_ID --all --query "[?!contains(scope,'rg-ado-lab')]" -o table
Scenario analysis
Finance requires that lab cost stay under 2 US dollars per person per day, and that no resources are left behind. How would you design the lab environment?

One resource group per person (tags owner / expires); ACA min-replicas 0; share one ACR (the fixed daily cost is split) or use a single registry with multiple repositories; set a daily cap on Log Analytics; skip the optional AKS / App Service; set budget alerts per resource group; a daily scheduled pipeline deletes expired resource groups and cleans up the matching service connections and identities (service connections can also be bulk-deleted by a script that follows a naming convention).

Verified teaching videos

▶
How to configure Azure budgets and costs alerts — A Cloud Guru
English · budgets and cost alerts
▶
8. Azure Cost Analysis, Budgets and Cost Alerts |Azure Beginners Tutorials — Mr. K Talks Tech
English · introduction to cost analysis

The titles and channels above were verified through the YouTube oEmbed API (2026-11-15).

Official docs

Video storyboard script

Shot 1 · 0:00–0:25
Visual: a bill is split into colored bars: ACR, logs, builds, Container Apps.
Narration: the largest fixed cost in this lesson comes from the container registry; Container Apps usually stays within the free allowance.
Shot 2 · 0:25–1:00
Visual: two boxes on the left and right, Azure DevOps and Azure, each with a list of items to delete.
Narration: clean up both sides: the service connections and environments in Azure DevOps, and the resource groups, identities and role assignments in Azure.
Shot 3 · 1:00–1:30
Visual: after the resource group is deleted, one subscription-level role assignment still glows.
Narration: role assignments outside the resource group do not disappear automatically; always check after deletion.
or score ≥ 70% on the Quiz

Command cheat sheet

WIF service connections · Environments · ACR · Container Apps · AKS · App Service · IaC · Troubleshooting · Cleanup (each code block can be copied with one click)
After-class reference

WIF service connection (manual, managed identity)

az identity create -g $RG -n $ID_NAME
CLIENT_ID=$(az identity show -g $RG -n $ID_NAME --query clientId -o tsv)
PRINCIPAL_ID=$(az identity show -g $RG -n $ID_NAME --query principalId -o tsv)
az devops service-endpoint create --service-endpoint-configuration sc.json   # scheme WorkloadIdentityFederation, creationMode Manual
az devops service-endpoint show --id $SC_ID --query authorization.parameters
az identity federated-credential create -g $RG --identity-name $ID_NAME -n fic-ado \
  --issuer "$ISSUER" --subject "$SUBJECT" --audiences api://AzureADTokenExchange
az role assignment create --assignee-object-id $PRINCIPAL_ID \
  --assignee-principal-type ServicePrincipal --role Contributor --scope $RG_ID

Issuer and subject

Entra (new default)
  issuer : https://login.microsoftonline.com/<tenant-id>/v2.0
  subject: <Entra prefix>/sc/<org-id>/<service-connection-id>
Azure DevOps (deprecated, retires 2027-07-01)
  issuer : https://vstoken.dev.azure.com/<org-id>
  subject: sc://<org>/<project>/<service-connection>
audience : api://AzureADTokenExchange

Using the service connection in AzureCLI@2

- task: AzureCLI@2
  inputs:
    azureSubscription: sc-azure-myapp
    scriptType: bash
    scriptLocation: inlineScript
    addSpnToEnvironment: true     # servicePrincipalId tenantId idToken
    inlineScript: |
      az account show -o table

Deployment job + environment + hooks

- stage: DeployProd
  lockBehavior: sequential        # runLatest (default) | sequential
  jobs:
  - deployment: Prod
    environment: myapp-prod
    strategy:
      runOnce:
        deploy:           { steps: [ … ] }
        routeTraffic:     { steps: [ … ] }
        postRouteTraffic: { steps: [ … ] }
        on:
          failure:        { steps: [ … ] }

Check execution order

1 Static: branch control (refs/heads/main) · required template · evaluate artifact
2 Pre-check approval
3 Dynamic: approval · Azure Function · REST API · business hours · Azure Monitor alert
4 Post-check approval
5 Exclusive lock
Approval timeout → stage skipped; rejection → failure; Rerun stage is possible; administrators can Bypass

ACR

az acr build -r $ACR -t myapp:$TAG .                  # requires ACR Tasks permission
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 5 -o tsv
az acr check-health -n $ACR --yes
az role assignment create --role AcrPush --scope $ACR_ID --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal
az role assignment create --role AcrPull --scope $ACR_ID --assignee-object-id $PULL_PRINCIPAL --assignee-principal-type ServicePrincipal

Container Apps revisions and traffic

az containerapp revision set-mode -g $RG -n $APP --mode multiple
az containerapp update -g $RG -n $APP --image $IMG --revision-suffix b$TAG --set-env-vars APP_VERSION=$TAG
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 registry set -g $RG -n $APP --server $ACR.azurecr.io --identity $PULL_ID
az containerapp logs show -g $RG -n $APP --type system --tail 50

AzureContainerApps@1

- task: AzureContainerApps@1
  inputs:
    azureSubscription: sc-azure-myapp
    imageToDeploy: $(ACR_NAME).azurecr.io/myapp:$(Build.BuildId)
    containerAppName: ca-myapp-dev
    resourceGroup: rg-ado-lab
    containerAppEnvironment: cae-myapp
    environmentVariables: APP_VERSION=$(Build.BuildId)
    disableTelemetry: true

AKS

- task: KubernetesManifest@1
  inputs:
    action: deploy
    connectionType: azureResourceManager
    azureSubscriptionConnection: sc-azure-myapp
    azureResourceGroup: rg-ado-lab
    kubernetesCluster: aks-ado-lab
    namespace: myapp
    manifests: k8s/*.yaml
    containers: $(ACR_NAME).azurecr.io/myapp:$(Build.BuildId)
# script method: az aks get-credentials … && kubelogin convert-kubeconfig -l azurecli

App Service slots

az webapp deployment slot create -g $RG -n $WEBAPP --slot staging
az webapp config appsettings set -g $RG -n $WEBAPP --slot-settings ENVIRONMENT=prod
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --target-slot production
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --action preview|swap|reset
# task: AzureWebAppContainer@1 (deployToSlotOrASE/slotName) + AzureAppServiceManage@0 (Action: Swap Slots)

IaC

az deployment group what-if -g $RG -f infra/app.bicep -p image=$IMG
az deployment group create  -g $RG -f infra/app.bicep -p image=$IMG
export ARM_CLIENT_ID=$servicePrincipalId ARM_TENANT_ID=$tenantId ARM_OIDC_TOKEN=$idToken ARM_USE_OIDC=true
terraform plan -out=tfplan -detailed-exitcode   # 0 no changes / 2 changes
terraform apply tfplan                          # state change → Saved plan is stale

Troubleshooting

az devops service-endpoint show --id $SC_ID --query authorization.parameters
az identity federated-credential list -g $RG --identity-name $ID_NAME -o table
az role assignment list --assignee $CLIENT_ID --all -o table
az monitor activity-log list -g $RG --offset 2h --query "[?status.value=='Failed']" -o table
# AADSTS700213 subject | 700211 issuer | 700024 assertion expired | 70025 no federated credential
# 7000215 secret expired | 700223/700238 tenant restriction | AuthorizationFailed = RBAC
# "...has not been authorized for use" = pipeline not authorized / connection disabled

Cleanup

az devops service-endpoint delete --id $SC_ID --yes
az pipelines delete --id $PIPELINE_ID --yes
az role assignment list --assignee $CLIENT_ID --all -o table
az group delete -n rg-ado-lab --yes --no-wait
az group exists -n rg-ado-lab

Comprehensive lab + final quiz

myapp multi-stage CI/CD → ACR → ACA (dev automatic, prod environment approval) → smoke test → rollback on failure → cleanup
After class ≈ 45 minutesCovers all modulesCost usually < 1 US dollar
Scenario The myapp team requires: ① no Azure secrets stored in the pipeline; ② every merge to main automatically deploys to dev and runs a smoke test; ③ prod can only be deployed from main, requires manual approval, and only one deployment may run at a time; ④ a new prod version is first verified at 0% traffic, failed verification rolls back automatically, and rollback takes no more than 1 minute; ⑤ after the lab, all resources on both sides are cleaned up and no permissions are left behind.
Permissions: Owner of the subscription / resource group (or Contributor + User Access Administrator); Azure DevOps project administrator. Cost: ACR Basic per day + a small amount of Log Analytics; ACA within the free allowance.
Environment (Module 0): create using the Warm-up tab rg-ado-lab, ACR, ACA environment, two UAMIs,ca-myapp-dev (single revision) and ca-myapp-prod (multiple revisions).
source ~/ado3.env
az containerapp list -g $RG --query "[].{n:name,m:properties.configuration.activeRevisionsMode}" -o table
az acr show -n $ACR --query "{server:loginServer,admin:adminUserEnabled}" -o table
N              M
-------------  --------
ca-myapp-dev   Single
ca-myapp-prod  Multiple
Server                    Admin
------------------------  -------
acrmyapp21877.azurecr.io  False
Identity and service connection (Module 2): id-ado-myapp Grant Contributor @ rg-ado-lab; create the WIF service connection manually sc-azure-myapp, add a federated credential using the issuer / subject shown for the service connection; authorize only the myapp pipeline. Verify:
az devops service-endpoint show --id $SC_ID --query "{scheme:authorization.scheme,issuerType:authorization.parameters.workloadIdentityFederationIssuerType}" -o table
Scheme                      IssuerType
--------------------------  ------------
WorkloadIdentityFederation  EntraID
Environments and checks (Module 3): myapp-dev (no checks); myapp-prod: branch control refs/heads/main + approval (1-hour timeout) + exclusive lock.
Pipeline (Module 4): commit scripts/smoke.sh and the complete pipeline from the Module 4 lab azure-pipelines.yml (Build → Push → DeployDev → DeployProd, including routeTraffic / postRouteTraffic / on.failure and failSmoke parameters). Merge to main; on the first run, permit the resources.
Success path: DeployDev smoke test passes; approve DeployProd; confirm the new revision is at 100%:
az containerapp revision list -g $RG -n $APP_PROD --query "[?properties.active].{n:name,w:properties.trafficWeight}" -o table
curl -s https://$(az containerapp show -g $RG -n $APP_PROD --query properties.configuration.ingress.fqdn -o tsv)/
N                     W
--------------------  ---
ca-myapp-prod--b1240  0
ca-myapp-prod--b1251  100
[1251] Hello from ca-myapp-prod--b1251-6f7d9c8b4-q8w2e, hits=N/A (redis not connected)
Failure and rollback path: manually run main and select failSmoke; after approval, routeTraffic fails and on.failure runs. Timing: from the failure until traffic is confirmed back on the old revision should take under 1 minute.
rolling back to: ca-myapp-prod--b1251
Name                  Weight
--------------------  ------
ca-myapp-prod--b1251  100
##[warning]prod rolled back to ca-myapp-prod--b1251
Fault drill (Module 7): a partner randomly injects one fault from A–E (not authorized, subject mismatch, missing RBAC, approval timeout, AcrPull deleted), and you use the troubleshooting tree to locate and fix it within 10 minutes.
Cleanup (Module 8): delete the lab pipelines, the three environments, the service connections, and the Azure variables in the variable group; check role assignments outside the resource group; delete the resource group; verify az group exists -n rg-ado-lab is false.
Acceptance checklist

Open-ended self-check (answer first, then expand the reference answer)

1. In your own words: why is WIF safer than a client secret? What risks remain?

There is no long-term secret to leak or expire; ID tokens are short-lived, have a fixed audience, and their subject is bound to a specific service connection, so only Azure DevOps can issue them. Remaining risks: anyone who can run an authorized pipeline can act with that identity (so use least privilege, authorize pipelines one by one, and apply checks and required templates); printing or exfiltrating $idToken / access tokens can still be misused during their validity period; a misconfigured federated credential may trust the wrong subject.

2. What are the main differences between the Entra issuer and the Azure DevOps issuer? What must you do when migrating?

The issuer changes from https://vstoken.dev.azure.com/<org-id> to https://login.microsoftonline.com/<tenant-id>/v2.0; the subject changes from a name-based sc://org/project/sc to an ID-based <prefix>/sc/<org-id>/<sc-id>; tokens issued by the Entra issuer can only be exchanged for Entra access tokens. Migration: for flagged connections, choose Update; identities created by Azure DevOps are updated automatically, otherwise add the federated credential manually using the new issuer / subject shown in the UI; complete it before 2027-07-01. Multi-tenant apps and sovereign clouds are out of scope.

3. Why configure approvals on the environment rather than in the YAML?

Checks are configured by the resource owner on the resource, and anyone who edits the YAML (including the PR author) cannot remove or bypass them; the same check runs whenever any pipeline uses the resource; approval records and deployment history are centralized on the environment for auditing.

4. Describe what each of the four prod hooks does, and why ordinary variables cannot be passed directly between hooks.

deploy: pins traffic to the current revision and creates a new revision at 0%; routeTraffic: smoke tests the revision FQDN, then shifts 100%; postRouteTraffic: verifies the version on the public FQDN; on.failure: shifts back to the previous active revision and deactivates the new one. Each hook runs as a separate job, so the working directory and ordinary variables are not shared; therefore use a deterministic revision name (APP--b<BuildId>) and query the revision list during rollback.

5. The deployment log shows AuthorizationFailed. How would you resolve it within 5 minutes?

State that L3 has passed and the problem is at L4. Read the client id, action and scope from the error; az role assignment list --assignee <clientId> --all check whether there is a role that includes that action at that scope; if one is missing, assign the minimum role (or correct the service connection's subscription / resource group); if the role was just assigned, wait a few minutes for propagation and rerun.

6. Compare three rollback methods: ACA revision traffic, AKS rolling update, and App Service slot swap.

ACA: change the app-scope traffic rule, which takes effect in seconds, provided the old revision is still active (multiple-revision mode); scaled-to-zero revisions have cold starts. AKS: rollout undo or redeploy the previous image, which requires Pods to be rescheduled and become ready; App Service: swap again; the old version is already warmed up in staging, so it takes seconds, but watch slot settings and database compatibility. All three require the old and new versions to be backward compatible at the data layer.

Final quiz (12 questions, covering all modules)

Sources and version notes

Sources verifying this lesson's technical facts (verified 2026-11-15)
TopicVerification resultSource (page date / access date)
How to create ARM service connectionsRecommended: WIF + app registration or managed identity. Options: App registration (automatic), Managed identity (create a WIF credential for an existing UAMI), App registration or Managed identity (manual); other methods (secrets, managed identity assigned by an agent, publish profiles) are kept only for backward compatibility; the automatic method requires subscription Owner and does not apply to Azure Stack / US Gov; Grant access permission to all pipelines is not recommended; connections unused for 100 days may be disabled automaticallyconnect-to-azure(ms.date 2026-08-18, updated 2026-11-03)
Issuer deprecationAzure DevOps issuer https://vstoken.dev.azure.com deprecated,retires 2027-07-01; new WIF connections default to the Microsoft Entra issuer; scope: public cloud single-tenant apps or managed identities; sovereign clouds and multi-tenant apps are excluded; for flagged connections, choose Update to convertconnect-to-azure;configure-workload-identity(ms.date 2026-08-18)
issuer / subject formatAzure DevOps issuer: https://vstoken.dev.azure.com/<organization id>,sc://<organization name>/<project name>/<service connection name>; Entra issuer: https://login.microsoftonline.com/<tenant id>/v2.0,<microsoft entra prefix>/sc/<organization id>/<service connection id>; Entra issuer tokens can only be exchanged for Entra access tokenstroubleshoot-workload-identity(ms.date 2026-04-22, updated 2026-11-03)
Converting secret-based connectionsOnly connections created in Azure DevOps and used by a single project; can be reverted within 7 days; bulk conversion PowerShell script (PowerShell 7.3+, Azure CLI)connect-to-azure
Manual / script creationOrder: identity → service connection (outputs workloadIdentityFederationIssuer,workloadIdentityFederationIssuerType: EntraID,workloadIdentityFederationSubject) → federated credential → role assignment; automation must creationMode: Manual; federated credential type Other issuer / Explicit subject identifier; audience api://AzureADTokenExchangeautomate-service-connections(ms.date 2026-04-22), configure-workload-identity
WIF error codesAADSTS700213 (subject), 700211 (issuer), 70021, 700024 (assertion time range; after about 1 hour use a managed identity, and for 10 minutes to 1 hour move token-fetching commands earlier), 70025, 700016, 7000215, 700223, 700238, 70052, 900382; Azure CLI requires 2.30+; task support table (AzureFileCopy@6, Kubernetes@1, KubernetesManifest@1, Docker@2, AzureContainerApps@1 and others support it)troubleshoot-workload-identity
Docker Registry service connectionACR authentication options: Service Principal, Managed Identity, Workload Identity federationservice-endpoints(ms.date 2026-10-15)
Approvals and checksFive categories in order: static (branch control, required template, evaluate artifact) → pre-check approval → dynamic (approval, Azure Function, REST API, business hours, Azure Monitor alerts) → post-check approval → exclusive lock; checks can be configured on environments, service connections, repositories, variable groups, secure files, and agent pools; service connections cannot be specified by variables; on approval timeout the stage is marked skipped; branch names must be refs/heads/…; lockBehavior runLatest (default) / sequential; Bypass, Defer and Rerun are availableapprovals(ms.date 2024-08-29, updated 2026-05-07)
AzureContainerApps@1Inputs: workingDirectory, appSourcePath, azureSubscription (alias connectedServiceNameARM, required), acrName, acrUsername, acrPassword, dockerfilePath, imageToBuild, imageToDeploy, containerAppName, resourceGroup, containerAppEnvironment, runtimeStack, kind, targetPort, location, environmentVariables, ingress, yamlConfigPath, disableTelemetry; no output variables; default names ado-task-app-<build-id>-<build-number> / <app>-rg; requires Azure CLI, and Docker for buildsazure-container-apps-v1(ms.date 2026-09-23)
ACA revisionsSingle (default) / Multiple / Deployment labels (preview); by default up to 100 inactive revisions are kept, and inactive revisions are not billed; revision-scope (properties.template) and app-scope (properties.configuration) changes; suffix rules (starts with a lowercase letter, ≤ 64 characters, no consecutive --)revisions(ms.date 2025-10-27, updated 2026-02-26)
ACA free allowanceThe first 180,000 vCPU-seconds, 360,000 GiB-seconds, and 2 million requests per subscription per month are free (unit prices could not be retrieved from the pricing page; estimator prices are editable examples)Container Apps pricing(accessed 2026-11-15)
KubernetesManifest@1action (bake, createSecret, delete, deploy, patch, promote, scale, reject); connectionType azureResourceManager / kubernetesServiceConnection; useClusterAdmin; strategy canary + pod/smi; rolloutStatusTimeout; resourceType; the ARM connection type generates a short-lived token for each task and supports private clusters and disabled local accounts; no long-term token is generated by default from K8s 1.24; kubelogin support is “to be provided in a future update”kubernetes-manifest-v1(ms.date 2026-09-23)
Parallel jobsPrivate project Microsoft-hosted free tier: 1 job, 1 hour per run, 1,800 minutes per month, takes effect automatically once billing is set up for the organization; paid tier 31 hours per job; self-hosted: 1 free plus 1 per active Visual Studio Enterprise subscriber; new organizations capped at 25 hosted jobs; waiting for approval does not use a parallel job; public projects are retired and will convert to private in 2027concurrent-jobs(ms.date 2026-06-19, updated 2026-11-03)

Video verification notes

All videos were checked one by one via the YouTube oEmbed API (which returns the title and channel name) to confirm that the video ID, title and author match (2026-11-15): John Savill's Technical Training “Azure DevOps Workload Identity Federation with Azure Overview. NO MORE SECRETS!” (saTUeR_U3lA), “Workload Identity Protection with Azure AD Identity Protection” (TASsrY_ilWc), “DevOps Master Class - Introduction” (R74bm8IGu2M); CoderDave “Azure DevOps Environments: Checks and Gates DEEP DIVE” (FbXKpo6oEyg), “Deploy to Azure Kubernetes (AKS) from Azure DevOps with Azure Pipelines | Build LIVE with Me” (4Oa5HneTuKs); Azure Infrastructure, Security & DevOps Series “Environments and approvals in Azure DevOps” (tCZ3958W3WI); DevStoriesEU “Azure Pipelines · 10/10 · Enterprise Gates: Approvals and Checks” (LDuYtOlrsxY); An IT Professional “Manual Approvals and Checks before Deployment” (B2frx9R8VKU); Brayan Ortiz “AKS vs App Service vs Container Apps” (A0w_3DvOf6M); MadeForCloud “Azure Container Apps (ACA) vs Azure Container Instances (ACI) vs Azure Kubernetes Service (AKS)” (oKZg33L_pPA); Infra2AI “Azure Container Apps Revisions, Traffic Splitting, Scale to Zero and Managed Identity (AI-200)” (otDMOabQbi8); Ehsan Tatasadi “How to send 20% of traffic to a new version on Azure Container Apps” (rVJ6gwVLCxI); Microsoft Learn “Implement Azure Container Apps | AZ-204 | Episode 15” (cqmUAzLUS4I); Kamal Rathnayake - MVP “Azure Container Apps Tutorial #01 - Getting Started” (jfYJEcDOOkI); Andrei Barbu “Deploy to AKS and ACR using Azure DevOps Pipelines” (tRjhTcXMAbo); Microsoft Azure “How to use Deployment Slots in Azure App Service” (2_tnbmnPAUk), “… for Containers” (5rR5C4Z5dU4); Chris Fulstow “Deploy Bicep with Azure DevOps Pipelines... from scratch!” (uZOTeca82Cg); Travis Roberts “Azure DevOps Pipelines and Bicep” (Q2HZdwTAWG0), “Azure DevOps Pipelines with Terraform and Stages” (d85-KD9stqc); Luke Byrne “Manual Approval | Azure DevOps Environments for Terraform (YAML)” (X9ELMS0zVVo); A Cloud Guru “How to configure Azure budgets and costs alerts” (mQYR7icumaU); Mr. K Talks Tech “8. Azure Cost Analysis, Budgets and Cost Alerts” (sQsLI-OaSHk). oEmbed does not return durations or publication dates, so they are not listed. Most videos were recorded before the “Entra issuer is the default” change; for issuer / subject details, follow this lesson. No verifiable high-quality Chinese video was found.

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 pronounced with en-US, and the result depends on the voices installed on the system. This courseware cannot embed MP3 files; for offline audio, pass the narration script to a TTS service such as Azure AI Speech. The Video tab of each module provides a storyboard script that can be given to a video generation tool.

Known limitations and conservative handling

  • The subject prefix of the Entra issuer (in the form /eid1/c/pub/t/…/a/…) is written only as “<microsoft entra prefix>” in the official table; this lesson does not hard-code the full format and always asks you to copy it from the service connection UI or REST output.
  • IDs, FQDNs, revision names, BuildIds and times in “Expected output” are example values; some Azure CLI output column names change between versions.
  • AzureContainerApps@1 The official reference does not describe item by item how updates to existing apps behave (whether registry configuration is overwritten, and whether environment variables are replaced or merged); in this lesson, dev passes only the required inputs and does not pass acrName, and prod uses az containerapp for precise control.
  • az acr build The required permission is written as “can run ACR tasks (such as Contributor)”; some subscription types may not be able to use ACR Tasks, in which case use Docker@2. The ACR ABAC repository permission model requires different built-in roles; follow the ACR docs.
  • The azurerm parameter names for fetching tokens dynamically via the Azure DevOps service connection ID, and the Microsoft DevLabs Terraform task version, were not verified one by one; they are directional guidance only.
  • az devops invoke The area / resource / route parameters (environments, pipelinePermissions) follow REST API naming and were not verified one by one in a real organization; the web UI is a reliable alternative.
  • Default timeout values for approval checks, and UI details such as whether a “minimum number of approvers” is supported, could not be found with definite values on the official pages; this lesson only describes behavior and notes that the UI is authoritative.
  • For the complete list of slot settings that are swapped or not swapped, follow the official docs; confirm task input names (AzureWebAppContainer@1, AzureAppServiceManage@0) on the task reference pages.
  • The unit prices in the cost estimator are sample values and do not represent current canadacentral prices; the ACA free allowance comes from the official pricing page.
  • The flows in the animations are teaching simulations; JWT contents are redacted and are not real tokens.