Azure DevOps Hour 3: Moving to the Cloud (Azure)
- 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.
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
| # | Time | Module | Core content | Animations / interactions | Lab (project myapp-lab · rg-ado-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and Azure setup | Resource group, ACR, ACA environment, user-assigned managed identity, free parallel jobs, costs and permissions | — | One-click lab resource creation |
| 1 | 00–05 | From CI to CD: choosing a deployment architecture | ACA / AKS / App Service / Functions comparison, push vs GitOps (pull), target architecture | Deployment target selector + push / pull flow comparison | Draw the target deployment diagram for myapp |
| 2 | 05–14 | Service connections: workload identity federation | ARM service connection creation methods, Entra issuer vs legacy issuer, subject format, conversion, how tasks obtain tokens, why not use client secrets | Core animation: OIDC token exchange (toggle failures such as subject mismatch) | Manually create a WIF service connection with a managed identity |
| 3 | 14–21 | Environments, approvals and checks | Environments, deployment jobs, execution order of the 5 check types, exclusive lock (lockBehavior), deployment history | Check gating flow simulator | myapp-dev / myapp-prod + approvals + branch control |
| 4 | 21–30 | Deploying to Azure Container Apps | Docker@2 / az acr build push, AzureContainerApps@1, revisions and traffic, smoke test and rollback | Revision traffic switching + rollback simulation | Multi-stage pipeline dev → prod |
| 5 | 30–38 | Deploying to AKS and App Service | KubernetesManifest@1, ARM connection vs Kubernetes connection, kubelogin, deployment slots and swap | Slot swap animation | (optional) App Service slot swap |
| 6 | 38–45 | IaC pipelines (Bicep / Terraform) | Bicep what-if, Terraform plan → approval → apply of saved plan, OIDC environment variables | Plan / apply gating and stale plan demo | Bicep what-if pipeline |
| 7 | 45–54 | Troubleshooting cloud deployments | AADSTS700213 / 700024 / 700211, AuthorizationFailed, unauthorized service connection, approval timeout, ACR 401 | Error classifier + interactive troubleshooting tree | Fault injection and fixes |
| 8 | 54–60 | Cost, cleanup and self-test | Cost breakdown, free allowances, budget alerts, cleanup order (including federated credentials and service connections) | Cost estimator | Full cleanup |
| — | After class | Cheat sheet · Capstone lab | myapp multi-stage CI/CD → ACR → ACA (dev automatic, prod with approval) → smoke test → rollback → cleanup | Final quiz, 12 questions | Capstone lab |
Knowledge Coverage Matrix
| Target skill | Module | Key commands / objects | Lab | Quiz |
|---|---|---|---|---|
| Choose the Azure deployment target for a workload | m1 | ACA / AKS / App Service / Functions decision table | ✓ | ✓ |
| Create and diagnose WIF service connections | m2 | az identity federated-credential create, issuer / subject,azureSubscription: | ✓ | ✓ |
| Using the service connection identity in scripts | m2 m6 | AzureCLI@2 + addSpnToEnvironment ($idToken) | ✓ | ✓ |
| Gate production deployments with environments and checks | m3 | deployment: + environment:, Approvals and checks,lockBehavior | ✓ | ✓ |
| Build, push the image and deploy to ACA | m4 | Docker@2,az acr build,AzureContainerApps@1,az containerapp ingress traffic set | ✓ | ✓ |
| Automatic rollback after smoke test failure | m4 final | runOnce.on.failure, revision weights | ✓ | ✓ |
| Deploy to AKS (no long-lived tokens) | m5 | KubernetesManifest@1 + connectionType: azureResourceManager,kubelogin | Read | ✓ |
| App Service slot deployment and swap | m5 | AzureWebApp@1 (slotName),AzureAppServiceManage@0 (Swap Slots) | Optional | ✓ |
| IaC plan → approval → apply | m6 | az deployment group what-if,terraform plan -out / apply tfplan | ✓ | ✓ |
| Locate identity / permission / authorization / registry errors | m7 | AADSTS error codes,az role assignment list, yamlauthz | ✓ | ✓ |
| Estimate costs and fully clean up | m8 | az group delete, delete service connections and federated credentials, budget | ✓ | ✓ |
What this lesson does not cover
| Topic | Reason | Where to learn |
|---|---|---|
| AWS deployment (ECR / ECS / EKS / Lambda, AWS OIDC) | Belongs to the next lesson | Lesson 4 |
| Deeper extends templates, canary / rolling deployment strategies, templating multi-environment promotion | This lesson only uses runOnce | Lesson 5 (multi-stage and deployment strategies) |
| Organization-level governance of protected resources, Key Vault variable groups, scaling required templates | This lesson only demonstrates a single check | Lesson 6 (governance and security) |
| Terraform itself (providers, state, modules) | Belongs to the Terraform course | Terraform 8-hour course(Lesson 3 Azure, Lesson 5 CI/CD) |
| Writing Helm charts, Argo CD / Flux GitOps details | Belongs to the Helm course | Helm 8-hour course |
| Networking, scaling and probe details for Container Apps / AKS | Already covered in the Docker / K8s courses | Docker course Lesson 3,K8s course |
How to use this courseware
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.
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).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.
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
- Lessons 1–2 completed: Azure DevOps organization (dev.azure.com), project
myapp-lab, Azure Repos repositorymyapp(including the Docker course'sapp.py,Dockerfile, Flask listening on 5000,/healthzreturnsok, readsAPP_VERSION), and the Lesson 2 CI pipelineazure-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),containerappextension,azure-devopsextension (installed in Lesson 1).
How this lesson connects to the previous one
| Lesson 2 already has | How this lesson reuses it |
|---|---|
CI stage: pytest + docker build | keep as Build stage, and append after it Push,DeployDev,DeployProd |
variable group myapp-common | Add ACR_NAME,RG,ACA_ENV and other non-secret variables (no longer needs any Azure secrets) |
Microsoft-hosted pool ubuntu-latest | continue 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
pool: name: Default). Note: runs waiting for approval do not occupy a parallel job.Costs, permissions and security (read before doing)
| Resource | Estimated cost (lab 2–3 hours) | Notes |
|---|---|---|
| ACR Basic | Billed per day, on the order of about 0.17 USD per day | Billing 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 allowance | With min-replicas 0, idle time is almost free |
| Log Analytics | Billed by ingestion volume; lab usage is usually < 1 USD | Environment created automatically |
| Managed identities, RBAC, federated credentials | Free | but must be cleaned up to avoid leftover permissions |
| (optional) App Service S1, AKS | Billed hourly, noticeably more expensive | Module 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
- 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.
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
azcommand); 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)
| Dimension | Azure Container Apps | AKS | App Service | Azure Functions |
|---|---|---|---|---|
| Runtime unit | Container (revision = immutable snapshot) | Pod / Deployment, any K8s workload | Code package or container (Web App for Containers) | Function (event-triggered), can also be containerized |
| Kubernetes API | Not exposed (underlying platform is managed) | Fully exposed | None | None |
| Scaling | KEDA rules, can scale to 0 | HPA / KEDA / cluster autoscaling, configured by you | Manual or automatic scaling by instance plan, cannot go to 0 | Automatic by event; consumption plan can go to 0 |
| Release mechanism | Revisions + traffic weights / labels | Rolling update, canary (self-built or via mesh) | Deployment slots + swap (Standard and above) | Deployment slots (on some plans) |
| Operational effort | Low | High (version upgrades, node pools, add-ons) | Low | Low |
| Pipeline task | AzureContainerApps@1 or AzureCLI@2 | KubernetesManifest@1,HelmDeploy@1 | AzureWebApp@1 / AzureWebAppContainer@1 | AzureFunctionApp@2 |
| Suitable for | Microservices, APIs, background workers; want containers without managing a cluster | Platform teams; need CRDs / Operators / service mesh / fine-grained networking | Traditional web apps; need slot swap and built-in authentication | Event-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 change | The pipeline agent calls ARM / kubectl | A controller in the cluster continuously pulls from Git and reconciles |
| Where the credentials are | Azure DevOps service connection (WIF, short-lived tokens) | Inside the cluster; the pipeline only needs to write to Git (and push images) |
| Drift | Only overwritten at deployment time; later manual changes are not corrected | Continuously corrects drift |
| Gating | Environments approvals and checks (Module 3) | Git PR approval + branch policy |
| Applies to | Any 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.
Architecture diagram: myapp target deployment for this lesson
Comparison diagram: push-style vs GitOps
Flow diagram: the four stages of this lesson's pipeline
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
Commands to check the current state before choosing
| Command | Purpose | Notes |
|---|---|---|
az containerapp env list -o table | List ACA environments | The environment is the network and logging boundary |
az containerapp show -g $RG -n $APP_PROD --query properties.configuration.activeRevisionsMode | Check revision mode | Single / Multiple (label mode is in preview) |
az aks list -o table | Is there an existing AKS platform? | Reuse it first when a platform team exists |
az appservice plan list --query "[].{n:name,sku:sku.name}" -o table | App Service plan and tier | Deployment 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)
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
$(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.
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.
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 table2. 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).
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
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
- Comparing Container Apps with other Azure container options
- Choose an Azure compute service
- Deploy to Azure (Azure Pipelines)
Video storyboard
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.
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.
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.
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.
Module 2 · Service connections: workload identity federation
- 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_assertionto 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@1and similar tasks; in a script, getaddSpnToEnvironmentvia$idTokenand pass it to tools such as Terraform.
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
| Issue | Client secret (service principal key) | Workload identity federation (WIF) |
|---|---|---|
| Exposure surface | A long-lived password is stored in Azure DevOps; scripts echo, logs and third-party tasks can all leak it | There is no long-lived secret to leak; the ID token exists only briefly within one job |
| Expiry | When the secret expires, all pipelines fail (AADSTS7000215: Invalid client secret provided) | No rotation needed |
| Traceability | Whoever obtains the key can log in from anywhere | The token's subject is bound to a specific service connection and can only be issued by Azure DevOps |
| Official recommendation | Kept only for backward compatibility | Recommended: create everything new with WIF; try converting the old ones first |
How: creation methods and required permissions
| Method | Who creates the identity | Required permissions | Applies to |
|---|---|---|---|
| App registration (automatic) + Workload identity federation | Azure DevOps creates the app registration, federated credential and role assignment for you | Subscription Owner; can create app registrations in Entra | Fastest 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 credential | Can modify that UAMI; can assign roles | Use 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 yourself | Azure DevOps: service connection administrator; Azure: Managed Identity Contributor (or Federated Credential Contributor) + role assignment permission | Cross-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)
| Field | Microsoft Entra issuer (default for new connections) | Azure DevOps issuer (deprecated, retires 2027-07-01) |
|---|---|---|
| Issuer | https://login.microsoftonline.com/<Entra tenant ID>/v2.0 | https://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> |
| Audience | api://AzureADTokenExchange | |
| Who the token can be exchanged with | Only Microsoft Entra access tokens can be exchanged | Can be exchanged with Entra or other identity providers (such as AWS) |
| Impact of renaming | subject uses IDs; organization / project / connection Renaming does not break trust | After 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.AzureFileCopyrequires v6,Kubernetesrequires v1,KubernetesManifestrequires 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,azcommands run directly under the service connection identity. - Third-party tools (Terraform, Pulumi, azd): in
AzureCLI@2setaddSpnToEnvironment: 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
azuredevopsprovider / 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).
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
Object relationship diagram: who points to whom
Flowchart: the 5 manual steps (order must not change)
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).
Core commands and YAML
| Command / syntax | Purpose | Key parameters / notes |
|---|---|---|
az identity create -g $RG -n $ID_NAME | Create a user-assigned managed identity | Note clientId (for the service connection) and principalId (for the role assignment) |
az devops service-endpoint create --service-endpoint-configuration sc.json | Create a service connection with a script | scheme: WorkloadIdentityFederation,creationMode: Manual; output workloadIdentityFederationIssuer / Subject |
az identity federated-credential create | Add a federated credential to the UAMI | --issuer,--subject,--audiences api://AzureADTokenExchange |
az ad app federated-credential create --id APPID --parameters cred.json | Add a federated credential to the app registration | App registration method |
az role assignment create --assignee-object-id … --assignee-principal-type ServicePrincipal | Grant RBAC | Use 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 secrets | ServicePrincipal = secret/certificate,WorkloadIdentityFederation = WIF |
AzureCLI@2 + addSpnToEnvironment: true | Get identity information in a script | Environment 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)
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.- 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.
N Iss Sub ------------- ------------------------------------------------------------------- --------------------------------- fic-ado-myapp https://login.microsoftonline.com/aaaabbbb-…/v2.0 /eid1/c/pub/t/…/sc/…/…
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.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
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.
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 tablecreationMode 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.jsonSecurity 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
The titles and channels above were verified via the YouTube oEmbed endpoint (2026-11-15).
Official docs
- Use an Azure Resource Manager service connection
- Set a Resource Manager workload identity service connection (manual)
- Troubleshoot workload identity service connections
- Automate service connections with scripts
- Workload identity federation (Entra)
Video storyboard
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.
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.
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.
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.
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.
Module 3 · Environments, approvals and checks
- Understand what an Environment is: a logical collection of deployment targets + a protected resource + deployment history; be able to write
deploymentin 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 | runLatestto prevent concurrent deployments, and read the deployment history and bypass records.
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 job | deployment job |
|---|---|
- job: X | - deployment: X + environment: myapp-prod + strategy (runOnce / rolling / canary) |
| checks out source code by default | does not check out by default, and downloads the pipeline artifacts of the current run by default |
| no deployment history | records 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)
| Order | Category | Checks included | Key points |
|---|---|---|---|
| 1 | Static checks | Branch control,Required template,Evaluate artifact | Can be decided at compile time; if it fails, the stage fails |
| 2 | Pre-check approval | Pre-check approvals | Manual approval is obtained before the dynamic checks |
| 3 | Dynamic checks | Approvals,Invoke Azure Function,Invoke REST API,Business hours,Query Azure Monitor alerts | Retried at the “evaluation interval” until timeout |
| 4 | Post-check approval | Post-check approvals | Approval after the dynamic checks pass |
| 5 | Exclusive lock | Exclusive lock | Acquired 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
| Check | Behavior | Timeout / failure result |
|---|---|---|
| Approvals | Users 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 control | Allowed 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 run | Mismatch → stage fails |
| Business hours | Only allows through within the time window; if the stage has not started when the window ends, it is withdrawn and re-evaluated the next day | Timeout → fails |
| Invoke Azure Function / REST API | Calls 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 variables | Timeout → stage is skipped |
| Query Azure Monitor alerts | Passes only if no alert rules are active at evaluation time | Timeout → fails |
| Required template | Pipeline must extends use templates specified by repository / ref / path | Not satisfied → run fails |
| Evaluate artifact | Runs custom policy against container image metadata | Failure → stage fails |
| Exclusive lock | Only one stage allowed on the same resource at a time; used with YAML lockBehavior | see table below |
lockBehavior
| Value | Meaning | Applies to |
|---|---|---|
runLatest (default) | Only the latest run acquires the lock; earlier queued runs are canceled | Environments with frequent commits where only the latest version matters (dev/test) |
sequential | All runs acquire the lock in order | Environments where every version must be deployed; database migrations |
When: what to configure for each environment
| Environment | Recommended checks |
|---|---|
| myapp-dev | None, or only exclusive lock (runLatest) |
| myapp-prod | Branch 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-prod | Required template + branch control (prevents other pipelines from using the prod connection directly) |
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
Structure diagram: resources used by a stage and their respective checks
Timeline: runLatest vs sequential
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.
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"
| Action | Location / command | Description |
|---|---|---|
| Create environment | Pipelines → Environments → New environment (Resource: None) | Or created automatically on first run; you can also call REST distributedtask/environments |
| Add check | Environment → ⋮ → Approvals and checks → + | Requires the Administrator role on that environment |
| View deployment history | Environment → Deployments Tab | Runs, commits and work items for each deployment |
| Approve / reject | Run page → Review → Approve / Reject / Defer | Can also be reached from the email notification |
| Bypass checks | Run page → Bypass check | Resource administrators only; the bypasser is recorded (approvals, business hours, Function and REST checks can be bypassed) |
| Retry a timed-out stage | Run page → Rerun stage | The 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)
myapp-dev, Resource None → Create; create the same way myapp-prod (or use the REST approach on the “Commands” tab).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.
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
Branch control ✗ Failed The branch refs/heads/feature/gates is not in the list of allowed branches: refs/heads/main
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.sequential, the second continues after the first completes. Change lockBehavior to runLatest and repeat, and observe the earlier run being canceled.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.
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
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
The titles and channels above were verified through the YouTube oEmbed API (2026-11-15).
Official docs
- Pipeline deployment approvals (approvals and checks)
- Create and target an environment
- Deployment jobs
- Invoke Azure Function / REST API checks
Video storyboard script
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.
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.
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.
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.
Module 4 · Deploy to Azure Container Apps
- Push images to ACR in two ways:
Docker@2+ Docker Registry service connection (ACR, WIF), orAzureCLI@2+az acr build; know the permissions each one requires. - Use
AzureContainerApps@1the two modes of (build and push from source / deploy an existing image), and know when to switch toaz containerapp updatefor 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).
What: two ways to push images
Docker@2 (buildAndPush) | az acr build (in AzureCLI@2 ) | |
|---|---|---|
| Where it is built | Agent's local Docker | ACR Tasks cloud build (agent does not need Docker) |
| Service connection | Docker Registry Type → Azure Container Registry; authentication can be Service Principal, Managed Identity or Workload Identity federation | ARM service connection (WIF) |
| Permissions required for the identity | On ACR AcrPush | can run ACR tasks (e.g., Contributor on the registry); AcrPush is not enough |
| Advantages | can take advantage of agent caching, multi-stage builds, BuildKit | Simpler agent setup; build logs are traceable in ACR |
| Note | macOS Microsoft-hosted agents do not have Docker | Some 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 usesdocker build; otherwise Oryx++ Builder (pack CLI) generates the image. IfacrUsername/acrPasswordis not provided, useaz acr loginto get a token. - Deploy an existing image: provide
imageToDeploy(including the ACR login server). - Other inputs:
azureSubscription(aliasconnectedServiceNameARM, required),containerAppName,resourceGroup,containerAppEnvironment,targetPort,ingress(external / internal / disabled),environmentVariables(space-separatedkey=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: trueto 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 mode | Behavior | Usage 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 deactivated | dev |
| Multiple | Multiple revisions are active at the same time; traffic weights are assigned manually; you decide when to deactivate them | prod: 0% staging → smoke test → 100% |
| Deployment labels (preview) | Gives revisions label names such as dev / staging / prod, used for traffic switching and simpler rollback | Awareness 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 hook | What it does | Command |
|---|---|---|
deploy | Pins 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 |
routeTraffic | Smoke-tests the new revision's own FQDN; switches to 100% after it passes | az containerapp revision show --query properties.fqdn,scripts/smoke.sh |
postRouteTraffic | Verifies the version number once more on the public FQDN | scripts/smoke.sh https://$FQDN $(tag) |
on: failure | If any hook fails: traffic switches back to the previous active revision and the new revision is deactivated | az 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) →
yamlConfigPathor Bicep (Module 6), with the image tag passed in as a parameter.
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
State diagram: changes in prod revisions and traffic
Permissions diagram: each identity covers its own part
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.
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
| Command | Purpose | Description |
|---|---|---|
az containerapp update -g RG -n APP --image IMG --revision-suffix b123 --set-env-vars APP_VERSION=123 | Create a new revision | Suffix starts with a lowercase letter and contains only lowercase letters, digits and -, ≤ 64 chars |
az containerapp revision list -g RG -n APP -o table | List revisions, weights, status | --all including inactive |
az containerapp ingress traffic set -g RG -n APP --revision-weight A=100 B=0 | Set traffic weights | multiple-revision mode; must sum to 100 |
az containerapp ingress traffic show -g RG -n APP | View traffic rules | May appear latestRevision: true entries |
az containerapp revision show -g RG -n APP --revision R --query properties.fqdn | Revision-specific FQDN | used for smoke tests at 0% traffic |
az containerapp revision activate / deactivate --revision R | Activate / deactivate revisions | Deactivated revisions are not billed |
az containerapp revision label add --label canary --revision R | Add labels to revisions (separate URL) | Labels can be moved between revisions |
az containerapp logs show -g RG -n APP --revision R --tail 50 | View 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)
scripts/smoke.sh from the “Commands” tab to the repository.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”.
smoke OK … is version <BuildId>.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
failSmoke. After approval, routeTraffic fails, the on.failure job runs, traffic stays on the previous revision, and the new revision is deactivated.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).
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
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
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
- AzureContainerApps@1 task reference
- Deploy to Azure Container Apps from Azure Pipelines
- Update and deploy changes in Azure Container Apps (revisions)
- Traffic splitting
- Docker@2 task reference
Video storyboard script
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.
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.
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.
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.
Module 5 · Deploy to AKS and App Service
- Use
KubernetesManifest@1+connectionType: azureResourceManagerto 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 azureclito 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(orAzureWebApp@1) to deploy to a slot, and useAzureAppServiceManage@0to run Swap Slots.
What: three ways to connect to AKS
| Method | How it works | Advantages | Limitations |
|---|---|---|---|
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 accounts | The agent must be able to reach the API server |
| Kubernetes service connection (KubeConfig / Service Account / Azure Subscription) | Stores a kubeconfig or ServiceAccount token | Works 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 + kubelogin | Converts the kubeconfig in the script to use the Azure CLI login session | Full 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, outputmanifestsBundle) /createSecret/patch/scale/promote/reject/delete.containers: replaces matching images in the manifest with full names including tags / digests (artifact substitution);imagePullSecretsinjected 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/jobNameetc.). strategy: canary+trafficSplitMethod: pod | smi+percentage: create-baselineand-canaryvariants, thenpromoteorreject(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@2the script, runkubelogin convert-kubeconfigyourself.
Permissions required by AKS (WIF identity)
| Cluster authorization mode | Required roles |
|---|---|
| Entra ID authentication + Azure RBAC for Kubernetes | Azure Kubernetes Service Cluster User Role (get user kubeconfig) + Azure Kubernetes Service RBAC Writer (scope can go down to the namespace) |
| Entra ID authentication + Kubernetes RBAC | Cluster 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 images | Cluster 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 code | Sticky to the slot (not swapped) |
|---|---|
| Regular app settings, connection strings (not marked as slot settings), handler mappings, public certificates, WebJobs content | Marked 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 inAzureCLI@2the 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.
Architecture diagram: authentication chain from pipeline to AKS
Flowchart: App Service slot swap
Comparison diagram: “rollback” on AKS vs App Service
Step-by-step animation: App Service deployment slot swap (including failure and rollback)
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; }
| Command | Purpose | Notes |
|---|---|---|
az aks create -g RG -n aks-ado-lab --enable-aad --enable-azure-rbac --disable-local-accounts --attach-acr $ACR | Create a cluster with Entra + Azure RBAC | Parameters follow az aks create --help as the source of truth. |
az role assignment create --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp | Namespace-level write permission | together with Cluster User Role |
kubelogin convert-kubeconfig -l azurecli | Non-interactive login | Microsoft-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 annotations | added 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)
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
doneaz 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.
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.DeployWebApp stage; use the environment myapp-web-prod and add approval.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-myappGets Cluster User Role + RBAC Writer on namespacemyapp. - Pipeline:
KubernetesManifest@1(connectionType: azureResourceManager,containersreplaces 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.
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=…)"
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
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
- KubernetesManifest@1 task reference
- Use kubelogin to authenticate in AKS
- Set up staging environments in Azure App Service
- AzureAppServiceManage@0 task reference
Video storyboard script
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.
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.
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.
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.
Module 6 · Infrastructure as Code pipelines (Bicep / Terraform)
- 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.
What: the standard shape of an IaC pipeline
| Stage | Bicep | Terraform |
|---|---|---|
| Validate | az bicep build,az deployment group validate, linter (bicepconfig.json) | terraform fmt -check,validate, tflint |
| Preview | az deployment group what-if | terraform plan -out=tfplan |
| Review | Environment approval (paste the what-if summary in the approval instructions) | Environment approval (plan output / summary) |
| Apply | az deployment group create or AzureResourceManagerTemplateDeployment@3 | terraform apply tfplan (no re-plan) |
| State | ARM 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
| Tool | Approach |
|---|---|
| Bicep / ARM | AzureCLI@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 Analytics | Image 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 = [...] }.
Flow: Terraform plan → approval → apply
Illustration: change types in what-if output
Responsibility diagram
Step-by-step animation: IaC gates and the “stale plan”
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)
ca-myapp-iac, see the what-if output before approval. Cost: close to zero (min-replicas 0).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
+ Create … ca-myapp-iac; approve in the Review of the Deploy stage (the approval notes say “what-if: 1 to create”).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)
maxReplicas to 3 and commit; what-if shows ~ Modify and the property difference; it takes effect after approval again.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.
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: trueThe 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
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
- ARM template deployment what-if operation
- Integrate Bicep with Azure Pipelines
- AzureResourceManagerTemplateDeployment@3
- Store Terraform state in Azure Storage
Video storyboard script
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.
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.
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.
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.
Module 7 · Troubleshooting cloud deployments in practice
- 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.
What: the six-layer model
| Layer | Where it happens | Typical signals | First diagnostic |
|---|---|---|---|
| L1 Pipeline compilation and authorization | Before 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 checks | Before the stage starts | Waiting for review, Branch control failed, stage skipped | Checks panel on the run page |
| L3 Token exchange (Entra) | Sign-in step of the Azure task | AADSTS7002xx,AADSTS70025,AADSTS7000215 | Compare the issuer / subject / clientId of the service connection and the federated credential |
| L4 ARM authorization | When calling ARM | AuthorizationFailed, 403,ResourceGroupNotFound,SubscriptionNotFound | az role assignment list --assignee <clientId> --all |
| L5 Data plane / runtime | ACR, ACA revisions, AKS API | ACR 401 unauthorized, revision Provisioning failed, ImagePull failure | az containerapp logs show --type system, ACR role |
| L6 Application | Smoke test | 000 / 5xx / version mismatch | Revision 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
| Error | Layer | Root cause | Fix |
|---|---|---|---|
AADSTS700213 … presented assertion subject | L3 | Federated credential subject does not match the token sub, or no credential exists | Rebuild the federated credential using the subject shown for the service connection |
AADSTS700211 … presented assertion issuer | L3 | Issuer mismatch (issuer has switched to Entra) | Add a federated credential for the current issuer |
AADSTS700024 Client assertion is not within its valid time range | L3 | ID 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 action | L4 | Identity lacks the role, wrong scope, or the new assignment has not propagated yet | Assign the minimum role at the correct scope, then wait a few minutes |
…has not been authorized for use … aka.ms/yamlauthz | L1 | Service connection not authorized for this pipeline / disabled / name misspelled | Permit, or add it under Pipeline permissions; re-enable it |
| stage skipped (approval timed out) | L2 | Approval not completed within the timeout | Rerun stage; change the approver to a group; adjust the timeout |
ACR push unauthorized: authentication required | L5 | Pipeline identity has no AcrPush / ACR Tasks permission; the connection points to a different registry | Grant AcrPush (or Contributor for az acr build) |
| ACA revision pull fails (unauthorized) | L5 | Runtime identity has no AcrPull / the registry is not configured to use a managed identity | az 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
| Log | What to look for | Command / location |
|---|---|---|
Pipeline logs (system.debug=true) | Internal task requests and detailed az command output | Set a variable at run time system.debug to true |
| Entra sign-in logs (service principal sign-ins) | AADSTS errors, issuer, client | Entra admin center → Sign-in logs → Service principal / Managed identity sign-ins |
| Azure activity log | Who did what to a resource and when, AuthorizationFailed | az monitor activity-log list -g rg-ado-lab --offset 1h |
| Azure DevOps audit log | Changes to and disabling of service connections / checks | Organization settings → Auditing |
| ACA system / console logs | Image pulls, probes, crashes | az containerapp logs show --type system|console |
Layer diagram: from “run starts” to “smoke test passes”
Reference diagram: where to find evidence when an error occurs
Sequence diagram: where AuthorizationFailed occurs
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.
Troubleshooting command list
| Layer | Command | Purpose |
|---|---|---|
| L1 | az 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) |
| L1 | az devops invoke --area pipelinePermissions --resource pipelinePermissions --route-parameters project=$ADO_PROJECT resourceType=endpoint resourceId=$SC_ID --api-version 7.1-preview | See which pipelines are authorized to use this connection (REST; check the API docs for the route) |
| L3 | az devops service-endpoint show --id $SC_ID --query authorization.parameters | issuer / subject / clientId |
| L3 | az identity federated-credential list -g $RG --identity-name $ID_NAME -o table | Federated credentials |
| L4 | az role assignment list --assignee $CLIENT_ID --all -o table | All role assignments of the identity |
| L4 | az monitor activity-log list -g $RG --offset 2h --query "[?status.value=='Failed'].{op:operationName.value,who:caller,st:subStatus.value}" -o table | Failed ARM operations |
| L5 | az acr check-health -n $ACR --yes | ACR connectivity and authentication self-check |
| L5 | az containerapp logs show -g $RG -n $APP --type system --tail 50 | Image pulls, revision events |
| L5 | az containerapp show -g $RG -n $APP --query properties.configuration.registries | Whether the registry uses a managed identity |
| L6 | az containerapp revision list -g $RG -n $APP -o table | Revision 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)
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.
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.
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.
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.
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.
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 table2. 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
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
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
- Troubleshoot workload identity service connections
- Authorize resources for YAML pipelines
- Troubleshoot Azure RBAC
- Troubleshoot ACR access / login
- Microsoft Entra error codes (AADSTS)
Video storyboard script
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.
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.
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.
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.
Module 8 · Cost, cleanup and self-test
- 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.
What: the cost structure of this lesson
| Resource | Billing method | Scale in this lesson | Cost-saving tips |
|---|---|---|---|
| Azure Container Registry Basic | Fixed daily fee + storage overage; ACR Tasks billed by build duration | 1 registry, a few images | Delete 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 free | 3 apps, 0.25 vCPU / 0.5 GiB, min 0 | min-replicas 0; deactivate old revisions (inactive revisions are not billed) |
| Log Analytics | Billed per GB ingested (for plans with a free ingestion allowance, check the pricing page) | Very small | Set a daily cap; delete the resource group |
| App Service S1 (optional) | Billed per plan instance-hour; slots share instances | 1 instance | Delete 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 DevOps | The 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 job | Waiting for approval does not use a parallel job |
| Managed identities, RBAC, federated credentials, service connections | Free | — | 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
| # | Location | Object | Command |
|---|---|---|---|
| 1 | Azure DevOps | Disable / delete lab pipelines (gates-demo, myapp-infra) | az pipelines delete --id … --yes |
| 2 | Azure DevOps | Environments myapp-dev / myapp-prod / myapp-infra | Pipelines → Environments → ⋮ → Delete |
| 3 | Azure DevOps | Service connections sc-azure-myapp (and sc-acr-myapp) | az devops service-endpoint delete --id $SC_ID --yes |
| 4 | Azure DevOps | Variables such as ACR_NAME in the variable group | az pipelines variable-group variable delete |
| 5 | Azure | Role assignments at subscription or other scopes | az role assignment list --assignee $CLIENT_ID --all |
| 6 | Azure | Resource group rg-ado-lab (ACR, ACA, environment, Log Analytics, UAMI and its federated credentials) | az group delete -n rg-ado-lab --yes --no-wait |
| 7 | Entra | App registration (if the automatic method was used) | az ad app list --display-name … → az ad app delete |
| 8 | Azure | Budget (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).
Resource diagram: what is on each side during cleanup
Cost share illustration (default configuration in this lesson, 3-hour lab)
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.
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
| Command | Expected |
|---|---|
az group exists -n rg-ado-lab | false |
az devops service-endpoint list --query "[].name" -o tsv | sc-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)
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~/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.
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
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
The titles and channels above were verified through the YouTube oEmbed API (2026-11-15).
Official docs
- Azure Container Apps pricing
- Azure Container Registry pricing
- Configure and pay for parallel jobs
- Create and manage budgets
Video storyboard script
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.
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.
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.
Command cheat sheet
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 tableDeployment 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: trueAKS
- 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 azurecliApp 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
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.
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
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
myapp-dev (no checks); myapp-prod: branch control refs/heads/main + approval (1-hour timeout) + exclusive lock.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.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)
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
az group exists -n rg-ado-lab is false.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
| Topic | Verification result | Source (page date / access date) |
|---|---|---|
| How to create ARM service connections | Recommended: 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 automatically | connect-to-azure(ms.date 2026-08-18, updated 2026-11-03) |
| Issuer deprecation | Azure 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 convert | connect-to-azure;configure-workload-identity(ms.date 2026-08-18) |
| issuer / subject format | Azure 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 tokens | troubleshoot-workload-identity(ms.date 2026-04-22, updated 2026-11-03) |
| Converting secret-based connections | Only 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 creation | Order: 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://AzureADTokenExchange | automate-service-connections(ms.date 2026-04-22), configure-workload-identity |
| WIF error codes | AADSTS700213 (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 connection | ACR authentication options: Service Principal, Managed Identity, Workload Identity federation | service-endpoints(ms.date 2026-10-15) |
| Approvals and checks | Five 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 available | approvals(ms.date 2024-08-29, updated 2026-05-07) |
| AzureContainerApps@1 | Inputs: 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 builds | azure-container-apps-v1(ms.date 2026-09-23) |
| ACA revisions | Single (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 allowance | The 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@1 | action (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 jobs | Private 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 2027 | concurrent-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@1The 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 passacrName, and prod usesaz containerappfor precise control.az acr buildThe 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 useDocker@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 invokeThe 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.