Jenkins Hour 3: Moving to the Cloud (Azure)

Take the myapp pipeline you got running locally in Lessons 1–2 ~/jenkinslab and connect it to Azure: choose the right identity (avoid long-lived keys where possible) → push to ACR → deploy to Container Apps / AKS / App Service → run agents elastically on Azure → troubleshoot, cost, and clean up
Jenkins LTS 2.580.2Azure CLI 2.89OIDC Provider · managed identity · workload identityVerified against learn.microsoft.com / plugins.jenkins.io · 2026-11-16
Overall learning goals
  • Explain the four identity paths from Jenkins to Azure: service principal + client secret (Azure Credentials plugin),managed identity (controller / agent on an Azure VM),AKS workload identity (Kubernetes plugin pod agent),OpenID Connect Provider plugin (Jenkins issues its own OIDC tokens + Entra federated credentials). Know where each path still has a secret, and whether its scope is “the whole agent” or “a single job”.
  • In a pipeline, use az login to log in, and isolate the Azure CLI and Docker login state to $WORKSPACE_TMP, and use az acr login --expose-token to push myapp images to ACR, and understand the ACR RBAC mode and ABAC mode, and their impact on AcrPush .
  • Deploy myapp (Flask + gunicorn,port 5000,/healthz) to Azure Container Apps (main track), and migrate to AKS (Entra ID + Azure RBAC + kubelogin) and App Service (custom container + deployment slots).
  • Choose the right agent on Azure: Azure VM Agents,Azure Container Agents (ACI),Kubernetes plugin + AKS, and know which Azure plugins are deprecated and which are still maintained by the community.
  • Independently diagnose AADSTS700213,AADSTS90061,AADSTS700024,AADSTS7000222,AuthorizationFailed, ACR unauthorized / denied, revision image-pull failures, kubelogin interactive-login hangs, and similar issues; in Wrap-up, fully clean up rg-jenkins-lab.
Prerequisites and comparison This lesson builds on Lesson 2 (Pipeline core): reuse the local environment ~/jenkinslab (jenkins controller,agent1,gitea), Gitea repository lab/myapp and the root directory Jenkinsfile. The same “cloud CD” pattern is covered in two other courses,so this lesson does not repeat it and only compares the differences: Azure DevOps uses native workload identity federation for service connections (ADO Lesson 3), GitHub Actions uses native OIDC + azure/login (GitHub Lesson 3). Jenkins core does not have built-in OIDC token issuance, the biggest difference in this lesson's identity section. For container and ACA basics, see the Docker course, Lesson 3, and for Kubernetes manifests, see the Kubernetes course.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (rg-jenkins-lab · canadacentral)
0PrepWarm-up and Azure setupResource group, ACR, ACA environment, two user-assigned managed identities, Azure CLI on agent1, cost and permissions—One-click lab resource creation
100–05From CI to CD: deployment architecture on AzureWhere Jenkins runs determines the identity approach; choosing ACA / AKS / App Service; push-based CD vs GitOps“Where Jenkins runs” identity-approach selector + pipeline stage animationRecord topology and variables
205–13Identity from Jenkins to AzureService principal secrets, managed identity (IMDS), AKS workload identity, OIDC Provider plugin + federated credentials; where secrets remainCore animation: how credentials reach Azure (4 identity types × 5 fault injection types)OIDC token + federated credentials + az login --federated-token
313–21Build and push to ACRimage tag policy,--expose-token, login state isolation, AcrPush vs ABAC roles, ACR Tasks limitsdocker push layered upload and token exchange animationJenkinsfile Build + Push stage
421–29Deploy to Azure Container Appsaz containerapp update, revisions, zero-downtime single revision, smoke tests, and rollbackRevision replacement (success / image-pull failure) animationDeploy + Smoke stage, running end to end
529–37Deploy to AKS and App ServiceAKS: Entra + Azure RBAC namespace-level authorization + kubelogin; App Service: custom container,WEBSITES_PORT, deployment slot swapRolling update vs slot swap(Optional) AKS or App Service
637–45Jenkins agents on AzureAzure VM Agents, Azure Container Agents (ACI), Kubernetes plugin + workload identity; current plugin maintenance statusComparison of the three agent provisioning processesKubernetes pod template + workload identity (optional)
745–54Troubleshooting cloud deploymentsAADSTS error codes, RBAC propagation, ACR 401/403, ACA revision failures, kubelogin, IMDS unreachableError classifierFault injection and fixes
854–60Cost, cleanup, and self-checkCost breakdown, budget alerts, cleanup order (including federated credentials, Jenkins credentials, static website)Cost estimator + Interactive troubleshooting treeFull cleanup
—Wrap-upCheat sheet · Capstone labmyapp: test → build → ACR → ACA → smoke → automatic rollback on failure → cleanupFinal quiz: 12 questionsCapstone lab

Knowledge Coverage Matrix

Target skillModuleKey commands / objectsLabQuiz
Choose the identity approach by where Jenkins runsm1 m2Decision table: local / Azure VM / AKS / other clouds✓✓
Log in to Azure without long-lived keys (OIDC)m2OpenID Connect id token credentials,az identity federated-credential create,az login --federated-token✓✓
managed identity and workload identity loginm2 m6az login --identity --client-id,$AZURE_FEDERATED_TOKEN_FILEOptional✓
Correct use of service principal secrets and their risksm2withCredentials([azureServicePrincipal(...)]), masking, rotationComparative reading✓
Build and push image to ACRm3az acr login --expose-token,DOCKER_CONFIG,AZURE_CONFIG_DIR✓✓
Deploy to ACA and smoke test / rollbackm4az containerapp update,revision list,/healthz✓✓
Deploy to AKS (no local accounts)m5--enable-azure-rbac, namespace-level roles,kubelogin convert-kubeconfig -l azurecliOptional✓
Deploy to App Service (container + slots)m5az webapp config container set,WEBSITES_PORT=5000,slot swapOptional✓
Run agents elastically on Azurem6Azure VM Agents, Azure Container Agents, Kubernetes plugin pod templateOptional✓
Diagnose identity / permission / image / deployment errorsm7 m8AADSTS error codes,az role assignment list,az containerapp logs show✓✓
Estimate cost and fully clean upm8az group delete, delete Jenkins credentials and federated credentials, budget✓✓

Content not covered in this lesson

ContentReasonWhere to learn
AWS (ECR / ECS / EKS, IAM OIDC,ca-central-1)Belongs to the next lessonLesson 4
Manage credentials and cloud configuration with JCasC, and install Jenkins itself on Kubernetes with HelmThis lesson uses the UI for demos; codified in Lesson 5Lesson 5 (configuration as code and Jenkins on Kubernetes)
Entra ID single sign-on to Jenkins, permission matrix, folder-level credential governanceBelongs to security governanceLesson 6
Creating Azure resources with Terraform / BicepBelongs to the IaC courseTerraform 8-hour course
Helm charts, Argo CD / Flux GitOpsBelongs to the Helm courseHelm 8-hour course
AKS networking, node pools, upgrade detailsBelongs to the AKS courseAKS 8-hour course

How to use this courseware

10 pages per module
Principles · Diagrams · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Read “Principles / Diagrams / Animation” first to build a mental model, then do the “Lab”.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser's localStorage (key jenkins60-part3-progress-v1).
Chinese voice
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script aloud; without a Chinese voice pack, the narration script can still be read or passed to a TTS tool.
Version and status notes (verified 2026-11-16)① Jenkins LTS 2.580.2 (2026-10-28), weekly 2.590 (updates.jenkins.io). From 2.555.1 onward, Java 21+ is required. ② Microsoft, on 2024-02-29 stopped supporting all Azure-related Jenkins plugins; the official guidance for retired plugins is “use Azure CLI”; Azure Credentials, Azure VM Agents, Azure Container Agents, Microsoft Entra ID, Azure Key Vault and others are still maintained by the Jenkins community, while Azure App Service, Azure Container Service, Azure Container Registry Tasks and other plugins are marked on plugins.jenkins.io as deprecated (last released in 2021). ③ Azure Credentials plugin (426.v5627e6a_4c7a_7, 2026-07-17) supports only service principals (secret / certificate) and managed identities,does not support workload identity federation. ④ OpenID Connect Provider plugin (234.vca_b_26b_f4b_dda_, 2026-09-18) lets Jenkins issue OIDC tokens; its README includes an Azure federated credential example. The default token lifetime is 3600 seconds. ⑤ ACR: az acr create default --role-assignment-mode rbac; Microsoft says ABAC mode (rbac-abac) will become the default in the future, at which point AcrPush / AcrPull no longer takes effect. ⑥ ACR Tasks (including az acr build) are “paused” on Azure free-credit subscriptions, so this lesson uses the agent's local docker build.

Module 0 · Warm-up and Azure setup

Connect the local Jenkins from Lessons 1–2 to Azure: resource group, ACR, ACA environment, managed identities, Azure CLI on agent1
Prep ≈ 20 minutesrg-jenkins-lab · canadacentralWill incur a small amount of Azure cost
Prerequisites
  • Lessons 1–2 completed: ~/jenkinslab/compose.yaml in the jenkins (127.0.0.1:8080),agent1 (label linux docker, can run docker build),gitea (127.0.0.1:3000, repo lab/myapp) are all running; the Multibranch job myapp-multibranch 's main branch's latest build succeeded.
  • myapp: Flask + gunicorn, listening on 5000,/healthz returns ok; reads environment variables APP_VERSION; without Redis, the home page shows hits=N/A (consistent with the Docker course; this lesson does not deploy Redis).
  • One Azure subscription, where you are in the subscription or resource group rg-jenkins-lab holding Owner, or Contributor + Role Based Access Control Administrator (needed to create role assignments). No Entra app registration permission is required; this lesson uses a user-assigned managed identity as the deployment identity.
  • Local machine: Azure CLI ≥ 2.69 (az login --identity of the --client-id parameter needs a newer version; this lesson checked syntax against 2.84) jq,curl.

Connection to the previous lesson

Lessons 1–2 already haveHow this lesson reuses / modifies
agent1 (label linux docker)Layer Azure CLI onto the image and add a label in the node configuration azure; the deploy stage uses agent { label 'linux && docker && azure' }
root directory Jenkinsfile (Test → Build)Keep Test / Build, and add Push,Deploy,Smoke, but only main branch deploys
. The credential gitea-myapp,registry-credsgitea-myapp continues to be used for pulling code; pushing to ACR no longer requires registry-creds (use an Entra token instead). Add azure-oidc-token (OpenID Connect id token, not a long-lived key)
image myapp:1.0 / myapp:$BUILD_NUMBER (local), after pushing to ACR, switch to an immutable tag <BUILD_NUMBER>-<short commit>

Shared variables (all later commands use them)

cat > ~/jenkins3.env <<'EOF'
export RG=rg-jenkins-lab
export LOC=canadacentral
export ACR=acrjenkins$RANDOM          # globally unique, 5–50 lowercase letters and digits; example acrjenkins12345
export ACA_ENV=cae-jenkins-lab
export APP=ca-myapp
export DEPLOY_ID=id-jenkins-deploy    # pipeline deployment identity (push images + update the Container App)
export PULL_ID_NAME=id-myapp-pull     # runtime image-pull identity (read-only on ACR)
export ST=stjenkinsoidc$RANDOM        # storage account for the managed OIDC discovery document (Module 2)
export JENKINS_URL=http://localhost:8080/
EOF
source ~/jenkins3.env && echo "ACR=$ACR ST=$ST"

Note:$RANDOM Each time source the value changes. After the first run, immediately change ACR= and ST= to the actual values (for example sed -i "s/^export ACR=.*/export ACR=acrjenkins12345/" ~/jenkins3.env).

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

source ~/jenkins3.env
az login
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 --role-assignment-mode rbac -o table   # explicitly set RBAC mode (the default); admin user stays disabled
az containerapp env create -g $RG -n $ACA_ENV -l $LOC -o table                   # automatically creates a Log Analytics workspace

# Two user-assigned managed identities: separation of duties
az identity create -g $RG -n $DEPLOY_ID -o none
az identity create -g $RG -n $PULL_ID_NAME -o none
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
RG_ID=$(az group show -n $RG --query id -o tsv)
DEPLOY_CLIENT_ID=$(az identity show -g $RG -n $DEPLOY_ID --query clientId -o tsv)
DEPLOY_PRINCIPAL=$(az identity show -g $RG -n $DEPLOY_ID --query principalId -o tsv)
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)

# Runtime: can only pull images
az role assignment create --assignee-object-id $PULL_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role AcrPull --scope $ACR_ID -o none
# Deployment identity: push images (data plane) + Contributor on the resource group (control plane; simplified for the lab, narrowed in production, see Module 4)
az role assignment create --assignee-object-id $DEPLOY_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role AcrPush --scope $ACR_ID -o none
az role assignment create --assignee-object-id $DEPLOY_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role Contributor --scope $RG_ID -o none

TENANT_ID=$(az account show --query tenantId -o tsv); SUB_ID=$(az account show --query id -o tsv)
printf 'export ACR_ID=%s\nexport RG_ID=%s\nexport DEPLOY_CLIENT_ID=%s\nexport DEPLOY_PRINCIPAL=%s\nexport PULL_ID=%s\nexport TENANT_ID=%s\nexport SUB_ID=%s\n' \
  "$ACR_ID" "$RG_ID" "$DEPLOY_CLIENT_ID" "$DEPLOY_PRINCIPAL" "$PULL_ID" "$TENANT_ID" "$SUB_ID" >> ~/jenkins3.env
Location       Name
-------------  --------------
canadacentral  rg-jenkins-lab
NAME             RESOURCE GROUP    LOCATION       SKU    LOGIN SERVER
---------------  ----------------  -------------  -----  ---------------------------
acrjenkins12345  rg-jenkins-lab    canadacentral  Basic  acrjenkins12345.azurecr.io

Push the bootstrap image and create the Container App

source ~/jenkins3.env
cd ~/myapp                                  # working copy cloned from Gitea in Lessons 1–2
az acr login -n $ACR                        # Docker is installed locally; the token is valid for 3 hours
docker build -t $ACR.azurecr.io/myapp:bootstrap .
docker push $ACR.azurecr.io/myapp:bootstrap
sleep 60                                    # wait for the AcrPull role assignment to propagate
az containerapp create -g $RG -n $APP --environment $ACA_ENV \
  --image $ACR.azurecr.io/myapp:bootstrap \
  --user-assigned $PULL_ID --registry-server $ACR.azurecr.io --registry-identity $PULL_ID \
  --target-port 5000 --ingress external \
  --env-vars APP_VERSION=bootstrap \
  --cpu 0.25 --memory 0.5Gi --min-replicas 0 --max-replicas 2 -o none
FQDN=$(az containerapp show -g $RG -n $APP --query properties.configuration.ingress.fqdn -o tsv)
echo "export FQDN=$FQDN" >> ~/jenkins3.env
curl -s https://$FQDN/healthz; echo
ok

--min-replicas 0: scales to zero when idle; the first request has a few seconds of cold start. If the first creation fails with an image-pull error, wait 1–2 minutes (RBAC propagation), then retry az containerapp update -g $RG -n $APP --revision-suffix retry1.

Install Azure CLI on agent1

In the pipeline, all Azure operations use az (Microsoft's official recommendation for retired plugins). In Lesson 1's ~/jenkinslab/agent/Dockerfile (based on jenkins/inbound-agent:3395.v6e5377b_0fb_3c-5-jdk21, with python3 and docker CLI added, and in compose build: ./agent, in the last USER jenkins before, insert the following block:

# ~/jenkinslab/agent/Dockerfile — insert before USER jenkins (still root at this point)
RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates jq \
 && curl -sL https://aka.ms/InstallAzureCLIDeb | bash \
 && az extension add --name containerapp --system \
 && az aks install-cli --install-location /usr/local/bin/kubectl --kubelogin-install-location /usr/local/bin/kubelogin \
 && rm -rf /var/lib/apt/lists/*
cd ~/jenkinslab
docker compose build agent1 && docker compose up -d agent1   # image name is still jenkinslab/agent1:jdk21
docker compose exec agent1 az version --query '"azure-cli"'
docker compose exec agent1 kubelogin --version | head -2
"2.89.1"
kubelogin version
git hash: v0.2.x/…

Then in Jenkins: Manage Jenkins → Nodes → agent1 → Configure, change the label to linux docker azure. Security trade-off: agent1 can access Docker (Lesson 1 already explained this is equivalent to root-level access on the host), and it can now also log in to Azure — only let jobs that need to deploy use azure label (Lesson 6 will use folders and permissions to keep it under control).

Costs, permissions, and security (read before doing)

ResourceEstimated cost (lab, 2–3 hours)Notes
ACR BasicBilled daily, roughly USD 0.17 per dayBilling stops after the resource group is deleted
Container Apps (consumption plan)Free each month per subscription for the first 180,000 vCPU-seconds, 360,000 GiB-seconds, and 2 million requests; this lab usually stays within the free allowance--min-replicas 0 Almost no cost when idle
Log AnalyticsBilled by ingested volume; lab usage is typically < USD 1ACA environment is created automatically
Storage account (static website, Module 2)A few KB of data, almost zero costManaged OIDC discovery document
Managed identities, role assignments, federated credentialsFreebut must be cleaned up to avoid leftover permissions
(Optional) AKS, App Service, VM / ACI agentsBilled hourly, significantly more expensiveModules 5 and 6 are optional; delete immediately after completing them

Unit prices vary by region and over time; use the Azure pricing calculatoras the reference (amounts on this page are illustrative). Security risk:id-jenkins-deploy Its role on rg-jenkins-lab is Contributor — anyone who can make Jenkins run as that identity can change this resource group. Module 2 will bind it to “only the myapp-multibranch of main branch”.

Self-check list

Module 1 · From CI to CD: deployment architecture on Azure

00:00 – 05:00 · First answer “Where does Jenkins run, where does it deploy, and whose identity does it use?” then write the Jenkinsfile
5 minACA · AKS · App Service★★★★☆ Architecture decision
Learning goals
  • Describe the three elements of Jenkins push-based CD: identity (the identity the agent process uses to call Azure),target (ACA / AKS / App Service),gate (which branches, who approves).
  • Understand how “Where Jenkins runs” determines the available identity approaches: local / data center, Azure VM, AKS, or other clouds.
  • Draw the target architecture for this lesson's myapp: Gitea → Jenkins (agent1) → ACR → ACA, and mark the identity at each hop.
Prerequisites: Lesson 2's stage / agent / when / post; ACA basics from the Docker course. Importance: ★★★★☆

What: what Jenkins actually does in CD

CI produces a “deployable artifact” (here, the container image myapp), CD takes the artifact in a controlled way and turns it into the version running in an environment. In Jenkins, CD is just a few stages in the Jenkinsfile: they run on an agent sh steps, and those steps call az / docker / kubectl. The Jenkins controller itself does not call Azure — the process running on the agent is what actually sends the requests (this is what determines where the identity lives).

Why: why putting Jenkins in the cloud takes one more step of thought than Azure DevOps / GitHub Actions

  • Azure DevOps ARM service connections natively support workload identity federation; GitHub Actions natively issues OIDC tokens (permissions: id-token: write). Jenkins core has neither these two capabilities; you can either rely on the platform identity (Azure VM managed identity, AKS workload identity), or install OpenID Connect Provider a plugin to make Jenkins itself an OIDC issuer, or fall back to service principal secrets.
  • Jenkins agents are often long-running machines shared by multiple jobs: the identity placed on an agent is visible to every job that runs on it. This is the risk most easily overlooked when choosing an approach.
  • Microsoft has stopped maintaining the Azure-related Jenkins plugins (2024-02-29), and the deployment plugins (Azure App Service, Azure Container Service, ACR Tasks, etc.) are deprecated. The current standard approach is: Credentials / platform identity → az login → az command.

How: choose the identity by where Jenkins runs

Where the Jenkins agent runsPreferred identityWhat “secret” remainsGranularity
Local / data center / other clouds (lab in this lesson)OIDC Provider plugin + Entra federated credential (user-assigned managed identity or app registration)RSA signing private key on the controller (auto-generated by the plugin, rotatable); the discovery document must be reachable by Entra over the public internetBy Job URL (sub), can be scoped down to the branch
Agent on Azure VM / VMSSAttached to the VM: user-assigned managed identity,az login --identity --client-idNoneWhole VM: every job on that VM can obtain a token
Pod agent on AKS (Kubernetes plugin)Workload identity: ServiceAccount + federated credential,--federated-tokenNone (short-lived SA token projected by Kubernetes)By ServiceAccount / pod template
Cannot do any of the aboveService principal + client secret or certificate (Azure Credentials plugin)Long-lived secret stored in the Jenkins credential storeBy Jenkins credential scope (global / folder)

Deployment target comparison (myapp view)

DimensionAzure Container Apps (main track)AKSApp Service (Web App for Containers)
Pipeline callARM: az containerapp updateARM (to get kubeconfig) + kube-apiserver: kubectlARM: az webapp config container set
Release unitRevision (immutable snapshot), single / multiple revision modeDeployment rolling updateRestart the container; deployment slots + swap (Standard tier and above)
Permissions required by the deployment identityWrite permission on the Container AppCluster User + namespace-level Azure RBAC WriterWrite permission on the Web App
Runtime image pullUser-assigned managed identity + AcrPullkubelet identity (--attach-acr)Managed identity + acrUseManagedIdentityCreds
Scale to zeroYesRequires KEDA or similarNo
Suitable forStateless APIs, when you want containers without managing a clusterA platform team already exists and needs the Kubernetes APITraditional web apps that need warm-up before slot switching

When: push-based CD or GitOps

  • Push-based (this lesson's main track): the Jenkins agent holds a short-lived token and changes cloud resources directly; suitable for all Azure PaaS. Gating relies on when { branch 'main' },input, and folder permissions.
  • GitOps: Jenkins only builds images and updates the config repo, and Flux / Argo CD inside the cluster pull and deploy; suitable for the AKS platform, and Jenkins needs no cluster credentials (see Helm course).
Common misconceptions① “Installing the Azure Credentials plugin means no passwords” — it only stores the service principal secret in Jenkins, and that secret is still long-lived. ② “Managed identities are isolated per job” — the managed identity belongs to the VM, and every process on the VM can get tokens from IMDS. ③ “The Jenkins controller calls Azure for me” — the call happens in the agent's sh process; network egress, CLI version, and login cache are all on the agent. ④ “Azure plugins can no longer be used” — Azure VM Agents, Azure Container Agents, Azure Credentials, and others are still maintained by the community; only Microsoft support has ended.

Diagram: target deployment for this lesson's myapp

Gitealab/myapp · main Jenkins (~/jenkinslab, local) controller: credential azure-oidc-token (signing private key) agent1 (linux docker azure) Test → Build → Push → Deploy → Smoke when { branch 'main' } only deploys az / docker state isolated in $WORKSPACE_TMP Microsoft Entra IDfederated credential → access token Storage account: static websiteOIDC discovery document + JWKS Azure Resource ManagerRBAC: rg-jenkins-lab ACR acrjenkins12345myapp:<build>-<sha>id-jenkins-deploy: AcrPushid-myapp-pull: AcrPull ACA environment cae-jenkins-lab (canadacentral) ca-myapp (port 5000)single-revision mode: switch traffic once the new revision is ready/healthz smoke test pull (id-myapp-pull)
Figure 1-1: the two identities are kept separate: the deployment identity (pushes images, updates the app) and the runtime pull identity (read-only on ACR); Entra reads Jenkins' public key from the static website

Flowchart: Jenkinsfile stages and identity boundaries

Testpytest (no cloud identity) Builddocker build (no cloud identity) PushOIDC → az → ACR DeployOIDC → az → ARM Smokecurl /healthz Only these two stages enter withCredentials, and they run only on the main branch
Figure 1-2: PR / feature branches run only Test and Build; cloud identity appears only in the narrowest scope of the last two stages

Interaction: where Jenkins runs → recommended identity approach

Select the agent's location and constraints; the selector recommends an approach based on the decision table in the “Principles” page (teaching rules, not an official tool).

The agent runs on:
Constraints:

Step-by-step animation: one push-based deployment from commit to release

Click “Play”.

Commands to check the current state

CommandPurposeNotes
az containerapp list -g $RG -o tableList Container AppsConfirm the target exists
az identity list -g $RG -o tableList managed identitiesDeployment identity and pull identity are separate
az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o tableRoles held by the deployment identityReview least privilege
curl -s http://localhost:8080/api/json?tree=urlJenkins root URLDetermines the OIDC sub (Job URL) prefix; add when anonymous reads are not possible -u admin:<API token>
az vm identity show -g <rg> -n <vm>List managed identities attached to the Azure VMWhen the agent runs on an Azure VM
source ~/jenkins3.env
az containerapp list -g $RG \
  --query "[].{name:name, mode:properties.configuration.activeRevisionsMode, fqdn:properties.configuration.ingress.fqdn}" -o table
az role assignment list --assignee $DEPLOY_PRINCIPAL --all --query "[].{role:roleDefinitionName, scope:scope}" -o table
Name      Mode    Fqdn
--------  ------  -----------------------------------------------------------
ca-myapp  Single  ca-myapp.kindpond-1a2b3c4d.canadacentral.azurecontainerapps.io
Role         Scope
-----------  -----------------------------------------------------------------------------------------------
AcrPush      /subscriptions/…/resourceGroups/rg-jenkins-lab/providers/Microsoft.ContainerRegistry/registries/acrjenkins12345
Contributor  /subscriptions/…/resourceGroups/rg-jenkins-lab

How to verify: The deployment identity has only these two roles, and its scope does not exceed the lab resource group. Common errors:--assignee Passing clientId but the lookup fails with no Graph permission — use principalId (object ID) instead. Production use: Before going live, attach this table to the change review.

Lab 1: confirm topology and record pipeline variables (about 4 minutes)

Goal: confirm that the ACA target is reachable, and collect the non-secret identifiers the pipeline needs. Cost: almost zero.
Collect variables
source ~/jenkins3.env
cat <<EOF
AZURE_TENANT_ID=$TENANT_ID
AZURE_SUBSCRIPTION_ID=$SUB_ID
AZURE_CLIENT_ID=$DEPLOY_CLIENT_ID      # clientId of id-jenkins-deploy (not a secret)
ACR=$ACR
RG=$RG
APP=$APP
FQDN=$FQDN
EOF

These values are not secrets, and can be written directly into the Jenkinsfile's environment. Only the token itself is sensitive; it exists only within the withCredentials block.

Confirm the Jenkins URL: Manage Jenkins → System → Jenkins URL should be http://localhost:8080/ It appears in the OIDC token's sub claim (Module 2); changing it later will break the federated credential.
Draw Figure 1-1 on paper, marking three identity points: Jenkins → Entra (federated credential), agent → ARM / ACR (id-jenkins-deploy), Container App → ACR (id-myapp-pull).
Cleanup: this lab creates no new resources.

Case 1: the managed identity on a shared agent was used “in passing”

Background: The team put the Jenkins agent on an Azure VM and attached a managed identity with Contributor on the whole subscription, reasoning that “no password means secure.” An intern's test Job ran on the same agent az group list successfully.

Action: Split agents by team (label deploy-prod only for the production deployment folder); narrow the managed identity's permissions to the resource group; move non-deployment jobs to an AKS pod agent (no identity attached).

Lesson: A managed identity's granularity is “the machine,” not “the job.”

Case 2: removing service principal secrets from an on-premises Jenkins

Background: The on-premises Jenkins deploys 30 applications with a client secret valid for 2 years, and the security audit requires removing long-lived keys.

Action: Install the OpenID Connect Provider plugin, use a “backup issuer” (discovery document hosted on an Azure storage static website), and create one federated credential per application's deployment Job (sub = Job URL). Delete the service principal secrets.

Limits: Each managed identity supports at most 20 federated credentials; renaming a Job or moving its folder changes sub.

Case 3: after moving from AKS to ACA, the pipeline became simpler

Background: 12 stateless APIs were deployed on AKS, and Jenkins had to maintain kubeconfig, kubelogin, and namespace RBAC.

Action: After moving to ACA, deployment becomes a single az containerapp update, and permissions need only ARM write access.

Common problems at the architecture stage

ERROR: Please run 'az login' to setup account. (appears only on certain agents)

Cause: The Azure CLI login state is local to each agent (by default ~/.azure), the Job was scheduled onto a different agent, or different agents were used across stages.

echo "$NODE_NAME $AZURE_CONFIG_DIR"; az account show -o table

Fix: Have each stage that needs Azure log in on its own (the pattern from Module 2); do not rely on “a previous stage already logged in.”

/bin/sh: az: not found

Cause: The Job runs on an agent without the Azure CLI (the label expression is too broad, e.g. only linux).

Fix: Use agent { label 'linux && docker && azure' }, or use a Kubernetes pod template that includes mcr.microsoft.com/azure-cli container.

Deployment succeeded, but the next day production was found overwritten by a feature branch

Cause: All branches in the Multibranch job ran the Deploy stage.

Fix: Add when { branch 'main' }; more importantly, the federated credential's sub only matches main 's Job URL — even if the Jenkinsfile is changed, other branches still cannot get an Azure token.

Command-line questions
1. Write a command that lists all role assignments and their scopes for the deployment identity id-jenkins-deploy.
P=$(az identity show -g rg-jenkins-lab -n id-jenkins-deploy --query principalId -o tsv)
az role assignment list --assignee $P --all --query "[].{role:roleDefinitionName,scope:scope}" -o table
2. How do you check the revision mode and FQDN of ca-myapp?
az containerapp show -g rg-jenkins-lab -n ca-myapp --query "{mode:properties.configuration.activeRevisionsMode,fqdn:properties.configuration.ingress.fqdn}"
Scenario analysis questions
The company's Jenkins runs in an on-premises data center and cannot be exposed to the public internet; the security team prohibits long-lived client secrets. How can Jenkins deploy to Azure?

Option 1: install the OpenID Connect Provider plugin and use the backup issuer, publishing two static JSON files (/.well-known/openid-configuration and /jwks) to public HTTPS (for example an Azure storage static website). Entra only needs to read the public keys and does not need access to Jenkins itself; create federated credentials on a user-assigned managed identity for the deployment Jobs. Option 2: set up a dedicated group of deployment agents in Azure (VMs with managed identities, or AKS pods using workload identity), which the on-premises controller dispatches to over inbound connections. Neither option uses long-lived keys; option 1 is scoped to the Job, option 2 to the agent / ServiceAccount.

Verified teaching videos

▶
AKS vs App Service vs Container Apps: Which Service Should You Choose? — Brayan Ortiz
English · comparison of three deployment targets
▶
How to get started with Azure Container Apps — Microsoft Azure
English · ACA introduction

The titles and channels above were verified via the YouTube oEmbed endpoint (2026-11-16); oEmbed does not return durations or publish dates, so those are not listed. The videos were recorded before this lesson, so for product details follow this lesson and the official docs.

Official docs

Video storyboard

Shot 1 · 0:00–0:20
Visual: local Jenkins icon, with a dashed line pointing to the cloud.
Narration: moving Jenkins to the cloud, the first question is not which plugin to use but whose identity the agent uses to call Azure.
Shot 2 · 0:20–1:00
Visual: four-panel grid (local, Azure VM, AKS, other clouds); each panel lights up its identity approach.
Narration: locally, use the OIDC plugin with federated credentials; on Azure VMs, use managed identity; on AKS, use workload identity; only fall back to service principal secrets when none of these work.
Shot 3 · 1:00–1:40
Visual: the architecture diagram builds up layer by layer, and the deployment identity and pull identity lines flash in turn.
Narration: the deployment identity pushes images and updates the app; the runtime identity only pulls images.
Shot 4 · 1:40–2:00
Visual: five Jenkinsfile stages, with the last two circled in red.
Narration: cloud identity appears only in the push and deploy stages on the main branch.

This courseware cannot generate video or MP3 directly; storyboards and narration scripts are provided instead.

or score ≥ 70% on the quiz

Module 2 · Identity from Jenkins to Azure: service principals, managed identities, and workload identity

05:00 – 13:00 · How credentials travel from Jenkins all the way to Azure, and where secrets still hide
8 minOIDC Provider 234.v… · Azure Credentials 426.v…★★★★★ Core lesson
Learning goals
  • Explain the token flow of the four identity paths: client secret (client_credentials),managed identity (IMDS 169.254.169.254),AKS workload identity (projected ServiceAccount token → federated credential),OIDC Provider plugin (Jenkins issues a JWT → federated credential).
  • Understand the three-part federated credential: issuer / subject / audience its fields must match the JWT's iss / sub / aud fields character for character, and Entra will go to {issuer}/.well-known/openid-configuration fetch the public keys.
  • On the local Jenkins, complete the long-lived-key-free az login --federated-token, and isolate the Azure CLI state to $WORKSPACE_TMP.
  • Be candid about the remaining risks: the OIDC plugin's signing private key lives on the controller, the managed identity applies to the whole VM, and service principal secrets can only be mitigated through rotation and narrower scope.
Prerequisites: Lesson 1 credential basics (credential scope,withCredentials, log masking). Importance: ★★★★★

What: the four paths

PathJenkins sideAzure sideRuns on the agentLong-lived secret?
① Service principal + client secretThe “Azure Service Principal” credential from the Azure Credentials plugin; withCredentials([azureServicePrincipal('azure-sp-lab')]) Injected AZURE_CLIENT_ID / AZURE_CLIENT_SECRET / AZURE_TENANT_ID / AZURE_SUBSCRIPTION_IDApp registration + service principal + role assignmentaz login --service-principal -u … -p "$AZURE_CLIENT_SECRET" -t …Yes (secret valid for 1 year by default; certificate-based is also a long-lived private key)
② Managed identityNo Jenkins credential needed (the plugin feature can optionally use an “Azure Managed Identity” credential)User-assigned managed identity attached to VM / VMSS + role assignmentaz login --identity --client-id <clientId>None
③ AKS workload identityKubernetes plugin pod template: serviceAccountName + labels azure.workload.identity/use: "true"AKS with OIDC issuer and workload identity enabled; federated credential on the managed identity, subject = system:serviceaccount:<ns>:<sa>az login --service-principal -u $AZURE_CLIENT_ID -t $AZURE_TENANT_ID --federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)"None
④ OIDC Provider plugin“OpenID Connect id token” credential, audience api://AzureADTokenExchange; each time entering withCredentials issues a new JWTFederated credential on the managed identity (or app registration): issuer = Jenkins issuer URL, subject = Job URLaz login --service-principal -u <clientId> -t <tenant> --federated-token "$OIDC_TOKEN"No long-lived cloud secret; the controller holds an RSA signing private key generated by the plugin.

Why: why client secrets should be removed as much as possible

  • A secret is “usable by whoever holds it”: if it leaks from the Jenkins credential store ($JENKINS_HOME + secrets/), build logs, agent memory, or backups, an attacker can use it anywhere until it expires or is revoked.
  • A federated credential binds three things — who issued the token, to whom it was issued, and for which audience — and the token expires within minutes to an hour; a leaked JWT is usable only within its validity period and only for that one identity.
  • Jenkins' masking (withCredentials hides secret strings in logs) only guards against “accidental printing”; it cannot stop a malicious Jenkinsfile from base64-encoding a secret and printing or sending it — so the branch and Job scope that can obtain the credential is what matters.

How: how a federated credential is verified (③ and ④ work the same way)

  1. The workload gets a JWT signed by an external issuer (a Kubernetes SA token or a Jenkins OIDC token),aud for api://AzureADTokenExchange.
  2. az login --federated-token to https://login.microsoftonline.com/<tenant>/oauth2/v2.0/token send a client_credentials request in which the client_assertion client assertion is this JWT.
  3. Entra reads the JWT's iss, goes to {iss}/.well-known/openid-configuration to fetch the jwks_uri, and downloads the public key to verify the signature.
  4. In client_id the corresponding managed identity / app, look for a federated credential with an exact match on issuer + subject + audience. If none is found → AADSTS700213.
  5. issues an Entra access token (ARM audience), and the Azure CLI cache is stored in $AZURE_CONFIG_DIR.

Key facts about the OIDC Provider plugin (plugins.jenkins.io / GitHub README, 2026-11-16)

  • Two credential types: OpenID Connect id token (as secret text) and OpenID Connect id token as file (temporary file path). Only the global domain is supported, and it can be created at the root or in a folder.
  • Default issuer is Jenkins itself: <JENKINS_URL>/oidc (folder credentials sit under the folder URL). When Jenkins cannot be reached from the public internet, set the backup issuer URI, and host the two static files yourself: {issuer}/.well-known/openid-configuration and {issuer}/jwks.
  • Default claims: sub = Job URL (for example http://localhost:8080/job/myapp-multibranch/job/main/), and includes the build number; can be customized via Manage Jenkins → Security → OpenID Connect → Claim templates . The default token lifetime is 3600 seconds.
  • Rotating the signing key: on the credential page, click Update and save again (when using the backup issuer, re-upload jwks).
  • If the branch name contains / the Job URL will show %252F, so the federated credential's subject must match the encoded form character for character.

When: how to choose

  • If the agent is on an Azure VM, and that VM is dedicated to deployment → ② Managed identity (simplest).
  • If the agent is an AKS pod → ③ workload identity, and use the Kubernetes cloud's “Restrict pipeline support to authorized folders” setting to limit who can use pod templates with identity (Module 6).
  • If Jenkins runs on-premises / in another cloud, or needs per Job / branch authorization → ④ OIDC Provider plugin (this lesson's lab).
  • If the Azure VM Agents / Azure Container Agents plugins themselves need authorization and the controller is not on Azure → only ① service principal works (the plugin accepts only the Azure Credentials type). In that case, a certificate is better than a secret, scope it to a dedicated resource group, set an expiry, and rotate.

Comparison with the other two courses

JenkinsAzure DevOpsGitHub Actions
OIDC token sourcePlugin (OpenID Connect Provider) or platform identityNative to service connections (Entra issuer)Native (id-token: write)
Default meaning of subjectJob URLService connection IDrepo:<org>/<repo>:ref:… or environment:…
discovery documentJenkins itself or static files you hostMicrosoft-hostedGitHub-hosted
Seethis moduleADO Lesson 3GitHub Lesson 3
Common misconceptions① “The Azure Credentials plugin supports workload identity federation” — as of 426.v5627e6a_4c7a_7 it only supports service principals (secret / certificate) and managed identities. ② “The OIDC plugin means Jenkins has no secrets at all” — the signing private key lives on the controller, and anyone with controller admin rights can sign arbitrary tokens; it only replaces “long-lived cloud keys” with “a signing key you control and can rotate.” ③ “Managed identity tokens can only be fetched from inside the Jenkins process” — any process on the same VM can access IMDS. ④ “Federated credentials support wildcards” — ordinary federated credentials only do exact matching; claim-matching expressions (flexible FIC) are still a preview feature.

Diagram 1: OIDC Provider plugin → Entra → Azure

Jenkins controllercredential azure-oidc-tokenJWT signed with RSA private keysub = Job URL · exp 3600 s agent1$OIDC_TOKEN (masked)az login --federated-tokenAZURE_CONFIG_DIR=$WORKSPACE_TMP/az Microsoft Entra IDverify signature + iss/sub/audfederated credential @ id-jenkins-deploy→ access token static website (backup issuer)/.well-known/openid-configuration/jwks (public keys) ACR/oauth2/exchange → push ARMPATCH containerApps/ca-myapp ① incoming via remote channel ② client_assertion ③ fetch public keys ④ Bearer access token
Figure 2-1: Entra never connects to Jenkins itself; it only reads static public keys; the token exists only inside the withCredentials block

Diagram 2: where the secret lives in each of the four paths

① Service principal secretJenkins credential store: secret (long-lived)agent environment variable: secretAfter leaking: usable anywhereuntil expiry / revocationGranularity: credential scope ② Managed identityNo static secretIMDS is reachable only within this VMAny process on the VM can obtain a tokenGranularity: whole agent ③ AKS workload identityProjected SA token (default 1 hour)Auto-refreshed by kubeletWhoever can specify the SA has the identityGranularity: ServiceAccount ④ OIDC Providercontroller: RSA signing private keyJWT expires after 3600 s by defaultValid only for the exact subGranularity: Job (branch)
Figure 2-2: from left to right, fewer and fewer long-lived secrets, and finer and finer authorization granularity

Core animation: how credentials reach Azure

Choose an identity path and a fault, and step through: where the token is produced, who passes it along, and at which step Azure performs which check. The log below shows the real command / HTTP request / error for that step (example values).

Fault injection:
Jenkins controllerCredential store agent / Podsh step Token source— Entra ID/oauth2/v2.0/token Discovery document / JWKS{issuer}/.well-known ACRpush myapp ARMcontainerApps ca-myappNew revision
Choose a path, then click “Play”.

Identity-related command overview

Command / stepPurposeKey parameters
az login --service-principal -u <clientId> -t <tenant> --federated-token "$TOKEN"Log in with an external JWT (③④)The JWT's aud must be api://AzureADTokenExchange
az login --identity --client-id <clientId>Log in with the user-assigned managed identity on the VM (②)can also use --object-id / --resource-id; with only one system-assigned identity, that identity is picked directly --identity
az login --service-principal -u … -p "$AZURE_CLIENT_SECRET" -t …Log in with a client secret (①)When the secret starts with - , write --password=…
az identity federated-credential createCreate a federated credential on the managed identity--issuer --subject --audiences; each identity supports at most 20 credentials
az identity federated-credential list -g $RG --identity-name $DEPLOY_IDCheck issuer / subjectCompare character by character against the JWT when troubleshooting
withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')])Issue a new Jenkins OIDC token each time the block is enteredFor file-type credentials, use file(...)
withCredentials([azureServicePrincipal('azure-sp-lab')])to inject the four service principal variables(variable names can be customized) clientIdVariable , etc.

Standard login snippet in pipeline (OIDC, recommended)

// Jenkinsfile snippet: wrap every stage that needs Azure like this
environment {
  AZURE_TENANT_ID       = '<tenantId>'
  AZURE_SUBSCRIPTION_ID = '<subscriptionId>'
  AZURE_CLIENT_ID       = '<clientId of id-jenkins-deploy>'   // not a secret
}
// …
steps {
  withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
    withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
      sh '''
        set -eu
        az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" \
          --federated-token "$OIDC_TOKEN" -o none
        az account set -s "$AZURE_SUBSCRIPTION_ID"
        az account show --query "{user:user.name, type:user.type, sub:name}" -o tsv
      '''
    }
  }
}
[Pipeline] withCredentials
Masking supported pattern matches of $OIDC_TOKEN
[Pipeline] withEnv
[Pipeline] sh
+ az login --service-principal -u 3f1c…-clientid -t 72f9…-tenant --federated-token **** -o none
+ az account set -s 0a1b…-sub
+ az account show --query … -o tsv
3f1c…-clientid	servicePrincipal	Lab Subscription

Why single quotes sh '''…''': so the shell, not Groovy, expands the variables $OIDC_TOKEN, to keep the token out of Groovy string interpolation (Jenkins flags sh "…${OIDC_TOKEN}…" with an “insecure interpolation of sensitive variables” warning). Why set AZURE_CONFIG_DIR: Otherwise the login cache is written to the agent user's ~/.azure, so the next Job (perhaps on another branch) can use it without logging in. WORKSPACE_TMP is a temporary directory that Pipeline provides for each workspace (<workspace>@tmp). Common errors: Multi-line sh sh block where the first line fails yet execution continues — add set -eu.

Managed identity (agent on Azure VM)

withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
  sh 'az login --identity --client-id "$AZURE_CLIENT_ID" -o none && az account show -o table'
}

Underneath, it is GET http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=…&client_id=… (Header Metadata: true). Only compute resources on Azure can reach this link-local address.

Service principal secret (for comparison; delete after use)

withCredentials([azureServicePrincipal('azure-sp-lab')]) {
  withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
    sh 'az login --service-principal -u "$AZURE_CLIENT_ID" -p "$AZURE_CLIENT_SECRET" -t "$AZURE_TENANT_ID" -o none'
  }
}

In Declarative's environment { SP = credentials('azure-sp-lab') } block, the plugin generates SP_CLIENT_ID,SP_CLIENT_SECRET,SP_TENANT_ID,SP_SUBSCRIPTION_ID (from the Azure Credentials plugin README).

Lab 2: log in to Azure from the local Jenkins without long-lived keys (about 15 minutes)

Goal: use the OpenID Connect Provider plugin to issue tokens, with the discovery document hosted on an Azure storage static website (because localhost:8080 is not reachable from Entra), create a federated credential on id-jenkins-deploy for myapp-multibranch 's main branch. Cost: the storage account costs almost nothing. Permissions: resource group Owner (you need to assign yourself a storage data role). Risk: the static website is public, so only put the public keys and discovery document there, nothing else.
Two routes; pick one as the main track This lesson defaults to the OIDC route (the plugin README includes a tested Azure federated credential example; Entra only needs to read two static JSON files from the public internet). If your environment cannot publish public static files, or step 1's plugin installation is restricted, switch to the bootstrap-secret route: per the “service principal secret path” at the end of this page, create a service principal that has a role only on rg-jenkins-lab , with the shortest validity possible, saved as azure-sp-lab, and in later modules replace withCredentials([string(… 'azure-oidc-token' …)]) + --federated-token with withCredentials([azureServicePrincipal('azure-sp-lab')]) + -p "$AZURE_CLIENT_SECRET", leave the other steps unchanged; delete it in Module 8 during Wrap-up.Lesson 4 (AWS)takes the opposite approach: the main lab uses a tightly scoped bootstrap secret, and OIDC is an advanced optional path. The two lessons use the same mechanism (the same OpenID Connect Provider plugin), so you can compare them.
1. Install the plugin: Manage Jenkins → Plugins → Available → search for OpenID Connect Provider (ID oidc-provider) → Install. After installing, confirm the version is ≥ 234.vca_b_26b_f4b_dda_.
2. Create a static website to host the discovery document
source ~/jenkins3.env
az storage account create -g $RG -n $ST -l $LOC --sku Standard_LRS --kind StorageV2 \
  --min-tls-version TLS1_2 --allow-blob-public-access false -o none
ME=$(az ad signed-in-user show --query id -o tsv)
az role assignment create --assignee-object-id $ME --assignee-principal-type User \
  --role "Storage Blob Data Contributor" --scope $(az storage account show -g $RG -n $ST --query id -o tsv) -o none
sleep 60   # wait for data-plane role propagation
az storage blob service-properties update --account-name $ST --auth-mode login \
  --static-website --index-document index.html -o none
WEB=$(az storage account show -g $RG -n $ST --query primaryEndpoints.web -o tsv)
ISSUER="${WEB}jenkins"
echo "export ISSUER=$ISSUER" >> ~/jenkins3.env; echo $ISSUER
https://stjenkinsoidc12345.z9.web.core.windows.net/jenkins

The static website content is publicly readable, regardless of the “Allow Blob public access” setting. At the end of the issuer must not have a trailing slash.

3. Create the credential in Jenkins: Manage Jenkins → Credentials → System → Global → Add Credentials → Kind: OpenID Connect id token; ID: azure-oidc-token; Audience: api://AzureADTokenExchange; expand Advanced options and set the Issuer URI to the value from the previous step $ISSUER. After saving, click the credential's Update: the page says the content must be provided at $ISSUER/.well-known/openid-configuration and $ISSUER/jwks , and it gives two download links. Save them as ~/oidc/openid-configuration and ~/oidc/jwks.
4. Upload and verify the discovery document
source ~/jenkins3.env
for f in openid-configuration:.well-known/openid-configuration jwks:jwks; do
  az storage blob upload --account-name $ST --auth-mode login -c '$web' \
    -f ~/oidc/${f%%:*} -n jenkins/${f#*:} --content-type application/json --overwrite -o none
done
curl -s $ISSUER/.well-known/openid-configuration | jq .
curl -s $ISSUER/jwks | jq '.keys[0] | {kty, alg, kid}'
{
  "issuer": "https://stjenkinsoidc12345.z9.web.core.windows.net/jenkins",
  "jwks_uri": "https://stjenkinsoidc12345.z9.web.core.windows.net/jenkins/jwks",
  "response_types_supported": [ "code" ],
  "subject_types_supported": [ "public" ],
  "id_token_signing_alg_values_supported": [ "RS256" ],
  "authorization_endpoint": "https://unimplemented",
  "token_endpoint": "https://unimplemented"
}
{ "kty": "RSA", "alg": "RS256", "kid": "…" }

issuer field must match $ISSUER exactly (Entra compares them). The field matches the plugin source Keys.openidConfiguration() ; two unimplemented endpoints are placeholder values from the plugin, not used in token exchange. jwks in alg field: whether it appears is determined by the downloaded content.

5. Decode a token once to get the exact sub: in myapp-multibranch 's main branch Jenkinsfile, temporarily add a stage:
stage('Show OIDC claims') {
  steps {
    withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
      sh '''
        set +x
        p=$(echo "$OIDC_TOKEN" | cut -d. -f2 | tr '_-' '/+')
        case $(( ${#p} % 4 )) in 2) p="$p==";; 3) p="$p=";; esac
        echo "$p" | base64 -d | jq '{iss, sub, aud, build_number, exp}'
      '''
    }
  }
}
{
  "iss": "https://stjenkinsoidc12345.z9.web.core.windows.net/jenkins",
  "sub": "http://localhost:8080/job/myapp-multibranch/job/main/",
  "aud": "api://AzureADTokenExchange",
  "build_number": 12,
  "exp": 1794816000
}

Print only the claims (payload), not the whole token. Delete this stage after confirming.

6. Create the federated credential (trust only the Job for the main branch)
source ~/jenkins3.env
az identity federated-credential create -g $RG --identity-name $DEPLOY_ID -n fic-jenkins-myapp-main \
  --issuer "$ISSUER" \
  --subject "http://localhost:8080/job/myapp-multibranch/job/main/" \
  --audiences api://AzureADTokenExchange -o table
Issuer                                                       Name                    Subject
-----------------------------------------------------------  ----------------------  ----------------------------------------
https://stjenkinsoidc12345.z9.web.core.windows.net/jenkins  fic-jenkins-myapp-main  http://localhost:8080/job/myapp-multibranch/job/main/
7. Verify login: put the login snippet from the “Commands” page into a Azure smoke stage (when { branch 'main' }), and push to Gitea to trigger a build.
+ az login --service-principal -u **** -t 72f9… --federated-token **** -o none
+ az account show --query … -o tsv
3f1c…-clientid	servicePrincipal	Lab Subscription
Finished: SUCCESS

The first run may report AADSTS700213 (federated credential propagation takes a few seconds to about a minute) — just re-run once. On a feature branch, run the same stage again: it should fail with AADSTS700213, which is exactly what we want.

(For comparison, optional) service principal secret path
az ad sp create-for-rbac -n sp-jenkins-lab --role Reader --scopes $RG_ID --years 1 -o json   # output contains the password: shown only once

In Jenkins, create a new Azure Service Principal credential azure-sp-lab, log in once using the snippet from the “Commands” page to see the difference; then immediately delete: az ad app delete --id <appId> and delete the Jenkins credential. If you make it the main bootstrap-secret track (see the top of this page), change the role to --role Contributor --scopes $RG_ID and additionally assign it on ACR AcrPush, with the credential stored in myapp the folder rather than globally. Wrap-up in Module 8 deletes the app registration.

Cleanup: keep the static website, the credential and the federated credential, which later modules need; Module 8 deletes them all.

Case 1: one deployment identity per app

Problem: One managed identity is shared by 40 Jobs, so its permissions can only be the union of all of them.

Approach: One user-assigned managed identity per app (created in bulk with IaC within the same subscription), with the federated credential subject set to that app's main branch Job URL; permissions are limited to that app's resource group. A managed identity supports up to 20 federated credentials, so splitting by “app × environment” is enough.

Case 2: Jenkins URL changed, so every deployment failed at once

Problem: After migrating to a new domain, the Job URL prefix changed,sub no longer matched the federated credential, so all deployments AADSTS700213.

Approach: Use Claim templates to change the sub to a stable value unrelated to the URL, for example jenkins:${JOB_NAME} (the plugin supports build variable substitution). Before migrating, create a federated credential for each of the old and new subjects, then delete the old one after cutover.

Limitation: When customizing sub, make sure ordinary users cannot forge it, for example JOB_NAME which is decided by who can create Jobs; pair this with the permission design from Lesson 6.

Case 3: the controller is on an Azure VM, but the agent is on-premises

Problem: The managed identity is attached to the controller VM,az login --identity so when running on the agent, IMDS is not reachable.

Approach: The managed identity is only for plugins running inside the controller (for example, Azure VM Agents uses an “Azure Managed Identity” credential to create VMs); in pipelines, the az should switch to OIDC plugin tokens.

Identity-related errors

AADSTS700213: No matching federated identity record found for presented assertion subject '…/job/myapp-multibranch/job/feature%252Flogin/'

Cause: The JWT sub does not match the federated credential: different branch, renamed Job, changed Jenkins URL, or a / in the branch name is encoded as %252F, or the federated credential was just created and has not propagated yet.

az identity federated-credential list -g rg-jenkins-lab --identity-name id-jenkins-deploy --query "[].{iss:issuer,sub:subject,aud:audiences[0]}" -o yaml

Fix: Decode the token using the method in Lab step 5, and copy the exact sub; only create federated credentials for branches that need to deploy.

AADSTS90061: Request to External OIDC endpoint failed.

Cause: Entra cannot reach {issuer}/.well-known/openid-configuration or jwks: the issuer is localhost / an internal address; the static website is not enabled; the file path or letter case is wrong; there is an extra trailing slash.

curl -sS -o /dev/null -w "%{http_code}\n" "$ISSUER/.well-known/openid-configuration"
curl -s "$ISSUER/.well-known/openid-configuration" | jq -r .issuer   # must equal $ISSUER

Fix: Use the fallback issuer and verify from the public internet that both URLs return 200.

AADSTS700024: Client assertion is not within its valid time range.

Cause: The Jenkins token (default 3600 seconds) expired before use: waiting for a long time input before logging in; or the controller's clock is skewed.

Fix: Only log in when it is actually needed withCredentials, re-login in each stage; check the controller's NTP.

AADSTS7000222: The provided client secret keys for app '…' are expired.

Cause: The service principal secret expired (default 1 year).

az ad app credential list --id <appId> --query "[].{end:endDateTime, hint:hint}" -o table

Fix:az ad app credential reset --id <appId> --append --years 1 Generate a new secret, update the Jenkins credential, then delete the old secret; the long-term solution is to migrate to OIDC / managed identity.

ERROR: Failed to connect to MSI. Please make sure MSI is configured correctly. (or IMDS timeout)

Cause:az login --identity Running on a non-Azure machine, or the container network cannot reach 169.254.169.254, or the VM does not have this user-assigned identity attached.

curl -s -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2021-02-01" | jq .compute.name
az vm identity show -g <rg> -n <vm> -o jsonc

Fix: Confirm which machine the agent actually runs on; an agent running in Docker on a custom network must be able to route to IMDS; or switch to OIDC.

Command-line exercise
1. Write out, for the Job URL on id-jenkins-deploy, http://localhost:8080/job/myapp-multibranch/job/main/ the command that creates a federated credential (the issuer is in $ISSUER).
az identity federated-credential create -g rg-jenkins-lab --identity-name id-jenkins-deploy -n fic-jenkins-myapp-main \
  --issuer "$ISSUER" --subject "http://localhost:8080/job/myapp-multibranch/job/main/" --audiences api://AzureADTokenExchange
2. On an Azure VM agent, sign in with the user-assigned managed identity and put the CLI state in the workspace temporary directory.
export AZURE_CONFIG_DIR="$WORKSPACE_TMP/az"
az login --identity --client-id "$AZURE_CLIENT_ID" -o none
Scenario analysis
A security team audit found that all Jenkins Jobs can read a global Azure Service Principal credential. How would you remediate this within two weeks?

Short term: move the credential from global scope to a folder scope visible only to the deployment folder; narrow the service principal's role scope; rotate the secret and set a 6-month expiry. Medium term: install the OpenID Connect Provider plugin, create federated credentials for each app's main-branch Job (with the discovery document hosted on a public static website), and delete the service principal secret once verification passes; if there is a dedicated deployment agent on Azure, use a managed identity. Also, in the permission matrix from Lesson 6, restrict who can modify the repository containing the Jenkinsfile and the Job configuration.

Verified teaching videos

▶
Microsoft Azure Managed Identity Deep Dive — John Savill's Technical Training
English · Managed identity principles and IMDS
▶
Why use workload identity federation? — Microsoft Developer
English · Why federated credentials
▶
AKS Workload Identity - Quick Tutorial — Azure Kubernetes Service (AKS)
English · AKS workload identity

The videos above were verified via YouTube oEmbed (2026-11-16). No verified video specifically covering the Jenkins OpenID Connect Provider plugin's Azure integration was found; refer to the plugin README and the storyboard below.

Official docs

Video storyboard

Shot 1 · 0:00–0:25
Visual: a key flies from the Jenkins credential store to the agent, then on to Azure, and gets copied along the way.
Narration: the problem with client secrets is that whoever holds one can use it; a copied key works anywhere.
Shot 2 · 0:25–1:10
Visual: Jenkins stamps and issues a ticket marked “valid for one hour” and “main branch only”; Entra holds a magnifying glass and checks the issuer, subject, and audience.
Narration: the OIDC plugin lets Jenkins issue short-lived tokens; Entra verifies the signature with the public key, then matches the federated credential word for word.
Shot 3 · 1:10–1:40
Visual: multiple processes in an Azure VM queue up to access 169.254.169.254.
Narration: a managed identity has no secret, but every process on the machine shares the same identity.
Shot 4 · 1:40–2:10
Visual: an AKS pod wears a ServiceAccount name tag, and a webhook injects a token file into it.
Narration: workload identity is granted per ServiceAccount, so restrict who can use pod templates that carry an identity.

This lesson cannot directly generate a video or MP3, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Module 3 · Build and push to ACR

13:00 – 21:00 · Immutable tags, exchanging an Entra token for an ACR token, and keeping login state inside the workspace
8 minACR Basic · RBAC mode★★★★☆
Learning goals
  • Design immutable image tags for myapp <BUILD_NUMBER>-<short commit>, and explain why deployments must not use latest.
  • Understand az acr login the two-step token exchange (Entra access token → ACR refresh token → repository-scoped access token), as well as --expose-token + 00000000-0000-0000-0000-000000000000 how the username is used.
  • Use AZURE_CONFIG_DIR and DOCKER_CONFIG to keep login state isolated in $WORKSPACE_TMP, destroyed when the build ends.
  • Distinguish between ACR's RBAC mode (AcrPush / AcrPull) and ABAC mode (Container Registry Repository Writer etc.), and know the limitations of ACR Tasks on free-tier subscriptions.
Prerequisites: the login snippet from Module 2; image layers from the Docker lesson. Importance: ★★★★☆

What: what happens when you push to ACR

ACR is an OCI image registry; data-plane authentication does not use the Entra token directly. Instead: ① The client first obtains an Entra access token (Module 2) → ② Call ACR's /oauth2/exchange endpoint to exchange it for an ACR refresh token (az acr login do this step and pass it to docker login, with the username fixed to the all-zero GUID) → ③ During push, docker uses the refresh token to request /oauth2/token a repository-scoped (repository:myapp:pull,push) access token. In step ③, ACR checks roles: in RBAC mode the identity needs AcrPush.

Why: a few choices that look like details but are actually critical

  • Immutable tags: myapp:12-a1b2c3d can be traced back to the build and commit; latest a reused tag gets overwritten, so rollback cannot tell what the ‘previous’ one was, and ACA / AKS may also skip creating a new revision or rolling out because the tag has not changed.
  • Isolate login state: by default, docker login writes it to the agent user's ~/.docker/config.json, so other Jobs on the same agent can push to your ACR for up to 3 hours without logging in. Setting DOCKER_CONFIG=$WORKSPACE_TMP/docker is set, the credential exists only in this build's temporary directory.
  • Do not enable the ACR admin user: the admin account is a single shared username with two passwords, has full pull and push permissions, and does not support RBAC; the official guidance is to use it only for personal testing. The registry-creds (username + password) approach in older tutorials should be replaced by Entra tokens on ACR.

How: two ACR role modes

Registry’s “role-assignment permission mode”PushPullNotes
RBAC Registry Permissions (rbac, current CLI default)AcrPushAcrPullOwner / Contributor also imply data-plane permissions
RBAC Registry + ABAC Repository Permissions (rbac-abac)Container Registry Repository Writer (can add conditions to allow only myapp repository)Container Registry Repository Reader (+ Catalog Lister is needed to list repositories)AcrPush / AcrPull / AcrDelete no longer takes effect; Owner / Contributor retains only control-plane permissions

Microsoft docs (updated 2026-06) state that rbac-abac it will become the default mode in the future, and recommend migrating existing registries. Migration order: first add equivalent ABAC roles → switch the mode → refresh cached credentials on each client → verify → delete the old roles. This lesson explicitly uses --role-assignment-mode rbac to create the registry, for easy reuse AcrPush.

Control plane vs data plane

az acr login -n acrjenkins12345 First you need to read the registry from ARM (control plane) to get the login server address, and only then do the token exchange (data plane). This lesson's deployment identity has Contributor on the resource group, so it works; if production only grants AcrPush, you also need a control-plane role that can read the registry (the official docs list in az acr login the scenario “Container Registry Contributor and Data Access Configuration Administrator”; a read-only alternative is “Container Registry Configuration Reader and Data Access Configuration Reader”, so verify this in your environment).

When: build on the agent, or use ACR Tasks

Local on agent docker build + push (this lesson)az acr build (ACR Tasks, quick build)
the agent needsa Docker daemon (or BuildKit / Kaniko, etc.)only the Azure CLI; the build context is uploaded to ACR
PermissionsAcrPush (or Repository Writer)Container Registry Tasks Contributor (in ABAC mode, also need --source-acr-auth-id [caller])
LimitationSecurity risk of the Docker socket (Lesson 1)Official docs: ACR Tasks runs on Azure free-credit subscriptions get “suspended”; command-line arguments may be written to diagnostic logs.
Suitable forexisting Docker agents that need cachingKubernetes pod agents that do not want to mount the Docker socket
Common misconceptions① “az acr login stays valid indefinitely”: the ACR token expires after about 3 hours, so long builds must log in again before pushing. ② “Contributor can always push images”: this fails on an ABAC-mode registry. ③ “Using registry-creds to store the admin password is simpler”: that is a long-lived shared secret, and it cannot be audited to a specific identity. ④ “docker logout is enough”: if DOCKER_CONFIG is not set, the credential may already have been read by a credential helper or another Job; isolating the directory and deleting it at the end is more reliable.

Diagram 1: ACR two-step token exchange

agent1 $AZURE_CONFIG_DIREntra access token (ARM) $DOCKER_CONFIG/config.jsonACR refresh token docker push (in memory)repository:myapp:push token ARMGET registries/acrjenkins12345 ACR /oauth2/exchangeEntra token → refresh token ACR /oauth2/tokencheck AcrPush → access token ACR /v2/myappHEAD blobs: already exists → skipPOST/PUT: upload new layersPUT manifests/12-a1b2c3d→ digest sha256:… ① Read login server ② az acr login ③ docker gets scoped token ④ Bearer
Figure 3-1: where each of the three tokens is stored; all are under $WORKSPACE_TMP and are deleted when the build ends

Diagram 2: tags and traceability

Gitea commita1b2c3d… Jenkins build #12BUILD_NUMBER=12 myapp:12-a1b2c3dlabel revision=a1b2c3d… ACA revisionAPP_VERSION=12-a1b2c3d
Figure 3-2: tracing from the running version (the APP_VERSION shown at /) back to the build and commit

Animation: token exchange and layer upload for one docker push

Click “Play”.

Common ACR commands

CommandPurposeNotes
az acr login -n $ACR --expose-token --query accessToken -o tsvGet only the ACR refresh token, without calling DockerUse with docker login -u 00000000-0000-0000-0000-000000000000 --password-stdin
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 5 -o tablethe 5 most recent tagsConfirm the push succeeded
az acr manifest list-metadata -r $ACR -n myapp --query "[].{d:digest,t:tags}"Manifest and digestDeployments can pin to a digest
az acr show -n $ACR --query roleAssignmentModeCheck RBAC / ABAC modeDecide which set of roles to use
az acr check-health -n $ACR --yesCheck Docker, CLI, DNS, and authFirst step in troubleshooting
az acr repository delete -n $ACR --image myapp:12-a1b2c3d --yesDelete an imageRequires delete permission (AcrDelete / Repository Contributor)

Jenkinsfile: Build + Push

pipeline {
  agent { label 'linux && docker && azure' }
  options { disableConcurrentBuilds(); buildDiscarder(logRotator(numToKeepStr: '20')) }
  environment {
    AZURE_TENANT_ID       = '<tenantId>'
    AZURE_SUBSCRIPTION_ID = '<subscriptionId>'
    AZURE_CLIENT_ID       = '<id-jenkins-deploy clientId>'
    ACR   = 'acrjenkins12345'
    IMAGE = 'acrjenkins12345.azurecr.io/myapp'
  }
  stages {
    // stage('Test') { … keep the Test stage from Lesson 2 unchanged … }
    stage('Build') {
      steps {
        script {
          def sha = sh(returnStdout: true, script: 'git rev-parse --short=7 HEAD').trim()
          env.TAG = "${env.BUILD_NUMBER}-${sha}"
        }
        sh 'docker build --pull -t "$IMAGE:$TAG" --label org.opencontainers.image.revision="$GIT_COMMIT" .'
      }
    }
    stage('Push') {
      when { branch 'main' }
      steps {
        withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
          withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az", "DOCKER_CONFIG=${env.WORKSPACE_TMP}/docker"]) {
            sh '''
              set -eu
              az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$OIDC_TOKEN" -o none
              az account set -s "$AZURE_SUBSCRIPTION_ID"
              az acr login -n "$ACR" --expose-token --query accessToken -o tsv \
                | docker login "$ACR.azurecr.io" -u 00000000-0000-0000-0000-000000000000 --password-stdin
              docker push "$IMAGE:$TAG"
              docker logout "$ACR.azurecr.io"
            '''
          }
        }
      }
    }
  }
  post {
    always { sh 'rm -rf "$WORKSPACE_TMP/az" "$WORKSPACE_TMP/docker"; docker image rm "$IMAGE:$TAG" || true' }
  }
}
+ docker push acrjenkins12345.azurecr.io/myapp:12-a1b2c3d
The push refers to repository [acrjenkins12345.azurecr.io/myapp]
3c1e4b2a9f10: Pushed
8d7f5e6a2b31: Pushed
5f70bf18a086: Layer already exists
1a2b3c4d5e6f: Layer already exists
12-a1b2c3d: digest: sha256:4e1f…9c2a size: 1786
+ docker logout acrjenkins12345.azurecr.io
Removing login credentials for acrjenkins12345.azurecr.io

Parameter notes:--password-stdin keeps the token out of process arguments; --pull pulls the latest base image on every build (security patches); GIT_COMMIT set by the Git plugin after checkout. How to verify:az acr repository show-tags -n $ACR --repository myapp -o table. Common mistakes: Inside sh "…" (double quotes), writing $OIDC_TOKEN will be interpolated by Groovy; post referenced in TAG is empty when it fails before Build —|| true use a fallback.

Equivalent authorization for ABAC-mode registries (for reference)

# Only allow pushing to the myapp repository (see the official docs for the condition expression; you can generate it in the portal's visual editor and copy it)
az role assignment create --assignee-object-id $DEPLOY_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role "Container Registry Repository Writer" --scope $ACR_ID \
  --condition "$CONDITION" --condition-version 2.0

Lab 3: first push of myapp from Jenkins to ACR (about 6 minutes)

Goal: after a main-branch build, the following appears in ACR: myapp:<build number>-<sha>; no Azure / Docker login state is left on the agent. Cost: ACR storage of a few dozen MB, negligible.
1. Update the Jenkinsfile: in ~/myapp the “Commands” section; fill in your tenant / subscription / clientId / ACR name, then commit and push to Gitea:
cd ~/myapp && git add Jenkinsfile && git commit -m "ci: push image to ACR" && git push origin main
2. Watch the build: Jenkins → myapp-multibranch → main → latest build → Console Output, confirm Masking supported pattern matches of $OIDC_TOKEN and digest: sha256:….
3. Verify the image and traceability tag
source ~/jenkins3.env
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 3 -o table
az acr manifest show-metadata -r $ACR -n myapp:$(az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 1 -o tsv) --query "{digest:digest, created:createdTime}" -o table
Result
----------
12-a1b2c3d
bootstrap
4. Verify no login is left on the agent
cd ~/jenkinslab
docker compose exec agent1 sh -c 'ls ~/.azure 2>/dev/null; cat ~/.docker/config.json 2>/dev/null | grep -c azurecr || true'
0
5. Feature branch check: create a branch feature/x and push it. It only runs Test / Build, with no Push stage shown (when { branch 'main' } skipped).
Cleanup: keep the image for the deployment in the next module.

Case 1: “ghost pushes” on a shared agent

Problem: A team found image tags in ACR that their pipeline never pushed. The investigation showed that another team's Job ran on the same agent and directly reused the ~/.docker/config.json ACR token, which is valid for 3 hours.

Approach: All Jenkinsfiles wrap the acrPush() step in the shared library (Lesson 2) that forces the setting of DOCKER_CONFIG / AZURE_CONFIG_DIR and cleans up in post ; ACR diagnostic logs are enabled to audit pushes by identity.

Case 2: after switching to ABAC mode, all pipelines got 401

Problem: The platform team switched the registry to rbac-abac, so every deployment identity that had only AcrPush failed to push.

Approach: Follow the official migration order: first add Container Registry Repository Writer (optionally with a repository condition) to each identity, then switch the mode, then have clients refresh their tokens (Jenkins logs in again on every build, so it refreshes naturally; AKS nodes need to be handled per the docs), and finally delete the old roles.

Case 3: pin deployments to a digest

Problem: Someone manually re-pushed a tag with the same name, so rolling back to the “same tag” produced different content.

Approach: After pushing, use docker inspect --format '{{index .RepoDigests 0}}' to get the digest, and deploy using myapp@sha256:…; or enable a lock on important tags az acr repository update --image myapp:12-a1b2c3d --write-enabled false.

Push-related errors

unauthorized: authentication required, visit https://aka.ms/acr/authorization for more information.

Cause: The identity has no push permission: missing AcrPush; the registry is in ABAC mode but only AcrPush was assigned; the role was just assigned and has not propagated yet; or docker is using another, expired config directory.

az acr show -n $ACR --query roleAssignmentMode -o tsv
az role assignment list --assignee $DEPLOY_PRINCIPAL --scope $ACR_ID -o table
echo "$DOCKER_CONFIG"; cat "$DOCKER_CONFIG/config.json" | jq '.auths | keys'

Fix: Assign the correct roles for the mode, wait a few minutes, and rerun.

ERROR: The registry 'acrjenkins12345' was not found / (AuthorizationFailed) … does not have authorization to perform action 'Microsoft.ContainerRegistry/registries/read'

Cause:az acr login -n Reading the registry resource (control plane) is required first; the identity only has data-plane roles, or the subscription context is wrong (az account set is missing).

Fix:az account set -s $AZURE_SUBSCRIPTION_ID; give the deployment identity a control-plane role that can read the registry.

DOCKER_COMMAND / "docker" command not found … / Cannot connect to the Docker daemon

Cause: Without --expose-token the az acr login command will call the local docker; the agent has no docker CLI or cannot reach the daemon.

Fix: Use --expose-token + docker login --password-stdin; when there is no Docker in a pod agent, switch to az acr build (note the free-credit subscription limits) or BuildKit / Kaniko.

az acr build fails or never starts on a free-credit subscription (symptom description, not the verbatim error)

Cause: Official docs: ACR Tasks on Azure free credit is “temporarily suspended”; in ABAC mode, the quick build does not have source registry data-plane permissions by default.

Fix: Build on the agent instead; or upgrade to a paid subscription; in ABAC mode, add --source-acr-auth-id [caller] and grant it to the caller. The exact error text will vary; check the actual output.

Command-line exercise
1. In an environment without a Docker daemon, get an ACR token and use it to log in (write out two commands).
TOKEN=$(az acr login -n acrjenkins12345 --expose-token --query accessToken -o tsv)
echo "$TOKEN" | docker login acrjenkins12345.azurecr.io -u 00000000-0000-0000-0000-000000000000 --password-stdin

(Without Docker, you can also hand the token to helm registry login,oras login etc.)

2. List the 5 most recent tags of the myapp repository (newest first).
az acr repository show-tags -n acrjenkins12345 --repository myapp --orderby time_desc --top 5 -o table
Scenario analysis
Your Jenkins agent is a pod on AKS, the security team does not allow mounting the Docker socket, the subscription is an enterprise paid subscription, and the registry is in ABAC mode. How do you build and push images?

Option 1: az acr build -r $ACR -t myapp:$TAG --source-acr-auth-id [caller] ., the deployment identity needs Container Registry Tasks Contributor (plus Repository Writer as needed), the build runs on the ACR side, and the pod only needs the Azure CLI. Option 2: inside the pod, use a daemonless builder (BuildKit rootless / Kaniko), using --expose-token the token it obtains, written into the builder's Docker config; the identity needs Container Registry Repository Writer (optionally with a myapp repository condition). Either way, do not enable the admin user.

Verified teaching videos

▶
Manage container images in Azure Container Registry | AZ-204 | Episode 13 — Microsoft Learn
English · ACR basics and image management
▶
Create Jenkins Pipeline to upload Docker image into ACR — Cloudamy
English · Jenkins pushing to ACR demo (if the video uses the admin user or a service principal secret, switch to Entra tokens as this lesson describes)

The videos above were verified via YouTube oEmbed (2026-11-16). Community videos may not follow this lesson's security recommendations; this lesson and the official docs take precedence.

Official docs

Video storyboard

Shot 1 · 0:00–0:30
Visual: three keys of different colors (Entra token, ACR refresh token, and repository-scoped token) are handed over one after another.
Narration: pushing to ACR requires two token exchanges; the last key is only valid for pushes to the myapp repository.
Shot 2 · 0:30–1:00
Visual: docker push output; existing layers are grayed out and skipped, and new layers show an upload progress bar.
Narration: ACR first checks whether each layer already exists, uploads only the changed layers, and finally writes the manifest and returns the digest.
Shot 3 · 1:00–1:30
Visual: two Jobs share one agent; the second Job peeks at a config.json file; then the file is locked inside WORKSPACE_TMP and shredded when the build ends.
Narration: isolate the login state in this build's temporary directory, and destroy it when the build ends.

This lesson cannot directly generate a video or MP3, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Module 4 · Deploy to Azure Container Apps

21:00 – 29:00 · Revisions, readiness, traffic switching, and rollback behind a single az containerapp update
8 minContainer Apps · single-revision mode★★★★★ Core track
Learning goals
  • Use az containerapp update --image to deploy a new version from Jenkins, and understand why it creates a new revision (it changed the template).
  • Explain single-revision mode zero-downtime mechanism: the old revision keeps serving until the new revision is ready; if the new revision fails, traffic is not switched.
  • Implement in a pipeline: record the previous image → deploy → wait for readiness → smoke /healthz → automatic rollback on failure.
  • Know how to narrow the deployment identity in production from “Contributor on the resource group”.
Prerequisites: Docker course Lesson 3 (ACA environments, revisions, pulling images with a managed identity). Importance: ★★★★★

What: revisions

Each Container App's properties.template template (image, environment variables, resources, probes, scaling rules) creates a new immutable revision each time it changes; changes to the configuration (ingress, secrets, registries) do not create a new revision. az containerapp update --image … --set-env-vars APP_VERSION=… Because the template changed, a new revision is created, and its name defaults to ca-myapp--<random suffix>, or you can set it with --revision-suffix .

Why: why ACA is the core track of this lesson

  • A deployment is just one ARM call and requires no kubeconfig, kubelogin, or cluster network reachability, which makes it the most Jenkins-agent-friendly option.
  • Single-revision mode comes with “switch only after ready”; combined with smoke tests, that is a sufficient release strategy. When you need canary releases, switch to multiple-revision mode and split traffic by weight.
  • Pulling images uses a separate managed identity (id-myapp-pull), so the pipeline identity does not appear at runtime.

How: the timeline of one deployment

  1. Agent calls ARM: PATCH Microsoft.App/containerApps/ca-myapp (new image + new APP_VERSION). ARM uses the deployment identity's RBAC to decide whether it has write permission.
  2. ACA creates a new revision, using id-myapp-pull to pull from ACR myapp:12-a1b2c3d (requires AcrPull).
  3. Replicas start and probes pass → revision Running / Healthy.
  4. Single-revision mode: traffic switches 100% to the new revision, and the old revision is deactivated. If the new revision fails to pull its image or its probes fail, the old revision keeps serving.
  5. The pipeline polls latestReadyRevisionName == latestRevisionName, then runs curl https://$FQDN/healthz the smoke test.

Single-revision vs multiple-revision

Single-revision (this lesson)Multiple-revision
Traffic switchingAutomatic 100% once the new revision is readyManual az containerapp ingress traffic set By weight
RollbackRedeploy the previous image (creates a new revision)Shift the weight back to the old revision (seconds, no rebuild)
Suitable fordev / small teamsprod canary and blue-green

When: when stronger gating is needed

  • Production: add input stage (specifying submitter), or put production deployment in a protected folder so only specific people can trigger it (Lesson 6). Note input do not tie up an agent while waiting (by waiting in the agent none stage).
  • For canary: multiple-revision mode + new revision at 0% → smoke test → gradually increase the weight (same as ADO Lesson 3Module 4 ACA commands, just invoked from Jenkins).
Common misconceptions① “az containerapp update returns success means the new version is live”: an ARM operation completing does not mean the revision is ready; poll or smoke test. ② “re-pushing the same tag and running update will pull the new image”: if the template has not changed, no new revision is created; you must use a new tag (or add --revision-suffix force). ③ “The deployment identity needs AcrPull to deploy”: it is the Container App's identity that pulls the image, not Jenkins. ④ “Single-revision mode has no rollback”: rollback just means redeploying the previous immutable tag.

Diagram 1: revision replacement in single-revision mode

IngressFQDN :443 → 5000 ca-myapp--bootstrap (old)Running · 100% → 0% · deactivated afterward ca-myapp--b12 (new)Provisioning → Running → 100% ACRid-myapp-pull pulls Jenkins Deploy stagePATCH template → poll latestReadyRevisionName
Figure 4-1: until the new revision is ready, traffic stays on the old revision (dashed line = switch only after ready)

Diagram 2: deploy + smoke test + rollback in the pipeline

Record PREV imageaz containerapp show update --imageNew revision Wait for readyUp to 5 minutes Smoke passes/healthz = ok Smoke failsupdate --image $PREV Build marked as failederror() + notify
Figure 4-2: rollback is also a deployment (using the previous immutable tag), so it also requires the deployment identity

Animation: revision replacement (success / image pull failure / app crashes on startup)

Click “Play”.

Container Apps deployment commands

CommandPurposeKey parameters
az containerapp update -g $RG -n $APP --image … --set-env-vars APP_VERSION=…Deploy a new version (new revision)--revision-suffix Custom revision name
az containerapp show … --query "{latest:properties.latestRevisionName, ready:properties.latestReadyRevisionName}"Check whether the latest revision is readyReady when the two values are equal
az containerapp revision list -g $RG -n $APP -o tableList revisionsCheck active / trafficWeight / healthState
az containerapp logs show -g $RG -n $APP --type system --tail 50System logs (image pulls, probes)--type console View app output
az containerapp revision restart -g $RG -n $APP --revision <name>Restart a revisiondoes not change the image
az containerapp ingress traffic set -g $RG -n $APP --revision-weight <rev>=100Switch traffic in multiple-revision moderequires first revision set-mode --mode multiple

Deploy + Smoke stage (appended to the Module 3 Jenkinsfile)

    stage('Deploy') {
      when { branch 'main' }
      steps {
        withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
          withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az", 'RG=rg-jenkins-lab', 'APP=ca-myapp']) {
            sh '''
              set -eu
              az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$OIDC_TOKEN" -o none
              az account set -s "$AZURE_SUBSCRIPTION_ID"
              az containerapp show -g "$RG" -n "$APP" --query "properties.template.containers[0].image" -o tsv > "$WORKSPACE_TMP/prev_image"
              echo "previous: $(cat "$WORKSPACE_TMP/prev_image")"
              az containerapp update -g "$RG" -n "$APP" --image "$IMAGE:$TAG" \
                --set-env-vars APP_VERSION="$TAG" -o none
              for i in $(seq 1 30); do
                read LATEST READY <<EOF
$(az containerapp show -g "$RG" -n "$APP" --query "[properties.latestRevisionName, properties.latestReadyRevisionName]" -o tsv | tr '\\n' ' ')
EOF
                [ "$LATEST" = "$READY" ] && { echo "ready: $READY"; exit 0; }
                sleep 10
              done
              echo "revision $LATEST not ready after 5 minutes"; exit 1
            '''
          }
        }
      }
    }
    stage('Smoke') {
      when { branch 'main' }
      steps {
        script {
          def fqdn = 'ca-myapp.<env-suffix>.canadacentral.azurecontainerapps.io'   // FQDN from ~/jenkins3.env
          def rc = sh(returnStatus: true, script: """
            for i in 1 2 3 4 5 6; do
              body=\$(curl -fsS --max-time 5 https://${fqdn}/healthz) && [ "\$body" = ok ] && exit 0
              sleep 5
            done
            exit 1
          """)
          if (rc != 0) {
            withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
              withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
                sh '''
                  az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$OIDC_TOKEN" -o none
                  PREV=$(cat "$WORKSPACE_TMP/prev_image")
                  az containerapp update -g rg-jenkins-lab -n ca-myapp --image "$PREV" --set-env-vars APP_VERSION="rollback-${PREV##*:}" -o none
                '''
              }
            }
            error("Smoke test failed; rolled back to previous image")
          }
        }
      }
    }
previous: acrjenkins12345.azurecr.io/myapp:bootstrap
ready: ca-myapp--0000003
[Pipeline] stage (Smoke)
+ curl -fsS --max-time 5 https://ca-myapp.kindpond-1a2b3c4d.canadacentral.azurecontainerapps.io/healthz
Finished: SUCCESS

Watch escaping: Smoke uses a Groovy double-quoted GString (in order to insert fqdn), so shell variables must be written as \$body; no sensitive variables are interpolated here. In Deploy, tr '\\n' ' ' is written in a Groovy triple-single-quoted string as \\n, and the value passed to the shell is \n. How to verify: Open the FQDN in a browser. The home page shows [12-a1b2c3d] a version string in the same style (depends on the app.py from the Docker course). Production use: Wrap Deploy / Smoke / rollback as shared library steps acaDeploy(app:, image:).

Lab 4: end to end: commit → ACR → ACA → smoke test (about 8 minutes)

Goal: one commit to the main branch automatically deploys a new revision and passes the smoke test; then deliberately cause a failure and observe the automatic rollback. Cost: within the ACA free allowance.
1. Merge into the Jenkinsfile: add the Deploy / Smoke stages from the “Commands” section after Push,fqdn fill in ~/jenkins3.env in the $FQDN. Commit and push.
2. Watch the revision
source ~/jenkins3.env
az containerapp revision list -g $RG -n $APP \
  --query "[].{name:name, active:properties.active, traffic:properties.trafficWeight, health:properties.healthState, image:properties.template.containers[0].image}" -o table
curl -s https://$FQDN/
Name                Active    Traffic    Health    Image
------------------  --------  ---------  --------  ---------------------------------------------
ca-myapp--0000003   True      100        Healthy   acrjenkins12345.azurecr.io/myapp:13-9f8e7d6
ca-myapp--retry1    False     0          None      acrjenkins12345.azurecr.io/myapp:bootstrap
[13-9f8e7d6] Hello from ca-myapp--0000003-5d8c7b9f4-abcde, hits=N/A (redis not connected)
3. Cause a smoke test failure: in app.py change /healthz 's return value to "broken", commit and push. Expected: Deploy succeeds (the container starts), Smoke fails, and the pipeline automatically switches the image back to the previous version and ends Smoke test failed; rolled back… as a failure.
az containerapp show -g $RG -n $APP --query "properties.template.containers[0].{image:image, env:env}" -o jsonc

The image should return to the previous tag,APP_VERSION which is rollback-…. Then change app.py back and push again.

4. Cause a “revision not ready” failure: in Jenkins, Replay this build and change --image "$IMAGE:$TAG" to a nonexistent "$IMAGE:nope". Expected: Deploy fails after 5 minutes of polling; the old revision still serves production (curl https://$FQDN/healthz returns ok). Use az containerapp logs show -g $RG -n $APP --type system --tail 20 to view the reason for the pull failure.
Cleanup: keep the resources; Module 8 deletes them all.

Case 1: narrowing the deployment identity

Problem: The audit requires that the deployment identity must not hold Contributor on the resource group.

Approach (verify in your environment): Assign Contributor on the Container App resource (or a custom role that includes Microsoft.App/containerApps/* read/write for); if ARM reports LinkedAuthorizationFailed involves Microsoft.App/managedEnvironments/join/action, add a custom role with that operation on the ACA environment; if it involves Microsoft.ManagedIdentity/userAssignedIdentities/assign/action, assign on id-myapp-pull the identity resource Managed Identity Operator; keep AcrPush on ACR. Fill in permissions one operation at a time using the operation names in the error messages, rather than granting broad roles all at once.

Case 2: dev is automatic, prod requires approval

Approach: In the same Jenkinsfile, add before the prod deployment stage input message: 'Deploy to prod?', submitter: 'release-managers', and put it in agent none a stage that waits without holding an agent; prod uses another managed identity id-jenkins-deploy-prod, whose federated credential only trusts the URL of the prod deployment Job.

Case 3: cold starts cause intermittent smoke test failures

Problem:--min-replicas 0 when scaled to zero, the first request has to start a replica, so the smoke test with a 5-second timeout fails intermittently and triggers a rollback.

Approach: retry the smoke test 6 times × 5 seconds; in production, set --min-replicas 1; in the template, configure a readiness probe pointing to /healthz, so that “ready” is more accurate.

Common errors when deploying to ACA

(AuthorizationFailed) The client '…' with object id '…' does not have authorization to perform action 'Microsoft.App/containerApps/write' over scope '…/ca-myapp'

Cause: The deployment identity has no write permission on the Container App, or the role was just assigned and has not taken effect yet (usually within a few minutes); it may also az account set point to the wrong subscription.

az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o table
az account show --query id -o tsv

Fix: Add the missing roles; wait for propagation and rerun; the Azure CLI may have cached an old token, and a new az login will obtain a token with the new permissions.

The revision stays in Provisioning / Failed; system log: Failed to pull image "acrjenkins12345.azurecr.io/myapp:nope" … manifest unknown / unauthorized

Cause: The tag does not exist (manifest unknown), or the Container App's pull identity has no AcrPull / the registry is not configured --registry-identity (unauthorized).

az containerapp logs show -g $RG -n $APP --type system --tail 30
az containerapp registry list -g $RG -n $APP -o table
az acr repository show-tags -n $ACR --repository myapp -o table

Fix: Correct the tag; az containerapp registry set -g $RG -n $APP --server $ACR.azurecr.io --identity $PULL_ID; confirm that id-myapp-pull has AcrPull.

Revision is Running but Unhealthy / access returns upstream connect error or disconnect/reset before headers

Cause: ingress targetPort The container's listening port does not match (myapp must listen on 5000); gunicorn is bound to 127.0.0.1 instead of 0.0.0.0; the app crashes on startup.

az containerapp show -g $RG -n $APP --query properties.configuration.ingress.targetPort
az containerapp logs show -g $RG -n $APP --type console --tail 50

Fix:az containerapp ingress update -g $RG -n $APP --target-port 5000; make gunicorn use --bind 0.0.0.0:5000.

The deployment “succeeded”, but the site is still the old version

Cause: A mutable tag was used (such as latest), and since the template did not change, no new revision is created; or in multiple-revision mode, the new revision has 0% traffic.

Fix: Use unique tags; in multiple-revision mode, check az containerapp ingress traffic show.

Command-line exercise
1. Write the command that checks whether the latest revision of ca-myapp is ready.
az containerapp show -g rg-jenkins-lab -n ca-myapp --query "{latest:properties.latestRevisionName, ready:properties.latestReadyRevisionName}" -o table

Ready when the two values match.

2. In single-revision mode, roll back to myapp:12-a1b2c3d.
az containerapp update -g rg-jenkins-lab -n ca-myapp --image acrjenkins12345.azurecr.io/myapp:12-a1b2c3d --set-env-vars APP_VERSION=12-a1b2c3d
Scenario analysis
Production requires “send 10% of traffic to the new version and observe for 10 minutes before going to 100%,” and Jenkins must be able to recover automatically whenever it fails at any point. How would you design this?

Switch the prod app to multiple-revision mode. Deploy: update --image … --revision-suffix b$BUILD_NUMBER, then ingress traffic set --revision-weight <old>=100 <new>=0; smoke test using a revision-specific FQDN or label; after it passes, set 90/10, and while waiting, poll metrics (failure rate, latency); then set 0/100 and deactivate the old revision. If any step fails,post { failure { … traffic set <old>=100 } }. Do not hold an executor during the waiting phase (use agent none a stage with sleep or input).

Verified teaching videos

▶
How to get started with Azure Container Apps — Microsoft Azure
English · ACA environments, apps, and revisions
▶
The ONLY Azure Container Apps video you need in 2024 — Microsoft DevRadio
English · ACA overview
▶
Azure Container Apps Tutorial #01 - Getting Started — Kamal Rathnayake - MVP
English · hands-on getting started

The videos above were verified via YouTube oEmbed (2026-11-16). No verified video on “Jenkins deploying to Container Apps” was found.

Official docs

Video storyboard

Shot 1 · 0:00–0:30
Visual: the Jenkins Deploy stage sends a PATCH, and a new revision appears below the Container App card.
Narration: changing the image or environment variables creates a new immutable revision.
Shot 2 · 0:30–1:10
Visual: the old revision keeps receiving traffic; the new revision goes from pulling the image to ready, and the traffic arrow switches over at the last moment.
Narration: in single-revision mode, the old revision keeps serving until the new revision is ready.
Shot 3 · 1:10–1:50
Visual: the smoke test turns red, the pipeline redeploys the previous tag, and it turns green.
Narration: when the smoke test fails, redeploying the previous immutable tag is the rollback.

This lesson cannot directly generate a video or MP3, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Module 5 · Deploy to AKS and App Service

29:00 – 37:00 · Same image, same deployment identity, two targets: kube-apiserver and App Service
8 minAKS (Entra + Azure RBAC) · App Service Linux★★★★☆ Optional lab, higher cost
Learning goals
  • AKS: use --enable-aad --enable-azure-rbac --disable-local-accounts a cluster where the Jenkins deployment identity has write permission only in namespace myapp ; understand kubelogin convert-kubeconfig -l azurecli why it lets kubectl reuse az login the identity.
  • Use kubectl set image + rollout status + rollout undo to implement deployment and rollback.
  • App Service: custom containers,WEBSITES_PORT=5000, managed identity pulling from ACR, health check paths, and deployment slots and swaps.
Prerequisites: Deployment / Service from the Kubernetes course; Modules 2–4. Importance: ★★★★☆

What: AKS deployment adds one more hop

Deploying to ACA / App Service only talks to ARM; deploying to AKS requires two hops: ① ARM (az aks get-credentials calls listClusterUserCredential to get kubeconfig; this requires “Azure Kubernetes Service Cluster User Role”) → ② kube-apiserver (kubectl carries an Entra token, and the API server checks authorization through the Azure RBAC webhook). For clusters with Entra integration enabled, the kubeconfig specifies exec the exec plugin calling kubelogin, not a static certificate.

Why: why to disable local accounts --disable-local-accounts and use Azure RBAC

  • Local accounts (--admin kubeconfig) are cluster-level certificates, effectively a long-lived cluster-admin key; once disabled, all access goes through Entra, which is auditable and revocable.
  • Azure RBAC lets you control Kubernetes permissions through role assignments on the Azure side, with scope down to the namespace: <AKS resource ID>/namespaces/myapp. Resource group Contributor does not include Kubernetes data-plane permissions (dataActions), so you must also explicitly assign “Azure Kubernetes Service RBAC Writer”.

How: kubelogin login modes

ModeWhen to useToken source
-l azurecli (this lesson)the agent is already az login (OIDC or managed identity both work)Azure CLI's token cache (affected by AZURE_CONFIG_DIR )
-l workloadidentityJenkins pod agent on AKS using workload identity$AZURE_FEDERATED_TOKEN_FILE
-l msiagent on an Azure VMIMDS
-l devicecode (default, interactive)Only suitable for humansbrowser device code — in Jenkins it hangs waiting

App Service: three key points for custom containers

  • Port: App Service probes port 80 by default; myapp listens on 5000, so you must set the app setting WEBSITES_PORT=5000.
  • Image pull identity: --acr-use-identity --acr-identity <user-assigned identity resource ID>, which needs AcrPull; do not use the ACR admin password.
  • Deployment slots: available only on Standard (S1) and above; deploy to the staging slot → warm up / smoke test → slot swap. Before the swap, the platform warms up the target instances; “sticky” settings (slot settings) do not move with the swap.

When: which to choose

  • An existing AKS platform and need for Kubernetes objects (HPA, NetworkPolicy, CRDs) → AKS; if the platform team uses GitOps, Jenkins only pushes images and updates the config repository.
  • Traditional web apps, need for slot swaps, and a team that does not want to touch Kubernetes → App Service.
  • Neither applies → back to ACA (Module 4).
Common misconceptions① “Resource group Contributor is enough for kubectl apply”: Kubernetes permissions under Azure RBAC are dataActions and require a dedicated AKS RBAC role. ② “az aks get-credentials --admin is the easiest option in a pipeline”: it uses a cluster-level certificate; once local accounts are disabled it fails outright, which is exactly the point. ③ “App Service automatically discovers the container port”: for custom containers, set it explicitly WEBSITES_PORT. ④ “Deployment slots are free”: slots share the instances of the same plan, and require the Standard tier or above.

Diagram 1: two-hop authorization from Jenkins to AKS

agent1az login (OIDC)kubectl + kubelogin(azurecli) ARMlistClusterUserCredentialrequires Cluster User Role kube-apiserverEntra token authenticationAzure RBAC webhook authorization namespace myappAKS RBAC Writer (this namespace only)deployment/myapp rolling update kubeconfig ($WORKSPACE_TMP)users[].exec: kubelogin get-token--login azurecli (no static certificate) ① get-credentials ② kubectl set image
Figure 5-1: ARM permissions decide whether you can get the kubeconfig; Azure RBAC decides what you can do in which namespace

Diagram 2: App Service deployment slot swap

Jenkinscontainer set --slot staging staging slotmyapp:13-… · warm up · smoke test production slotmyapp:12-… · user traffic az webapp deployment slot swapFirst apply the target slot settings to the source slot and warm it up, then swap routingRollback = swap again
Figure 5-2: a slot swap makes “rollback” a re-swap that takes seconds

Animation: AKS rolling update vs App Service slot swap

Click “Play”.

AKS commands

CommandPurposeNotes
az aks get-credentials -g $RG -n $AKS -f "$KUBECONFIG" --overwrite-existingGet user-level kubeconfigDo not use --admin
kubelogin convert-kubeconfig -l azurecli; instead switch the exec plugin to reuse the az loginApplies to $KUBECONFIG
kubectl auth can-i patch deployments -n myappVerify authorizationExpected yes; in the default namespace, expect no
kubectl -n myapp set image deployment/myapp myapp=$IMAGE:$TAGUpdate imagethe container name must match
kubectl -n myapp rollout status deployment/myapp --timeout=180sWait for rollout to completereturns non-zero on timeout
kubectl -n myapp rollout undo deployment/myappRoll back to the previous ReplicaSetor --to-revision
az aks command invoke -g $RG -n $AKS --command "kubectl get pods -n myapp"Runs through ARM when the private cluster is not network-reachableGood for troubleshooting, not for routine deployment
    stage('Deploy to AKS') {
      when { branch 'main' }
      steps {
        withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
          withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az", "KUBECONFIG=${env.WORKSPACE_TMP}/kubeconfig"]) {
            sh '''
              set -eu
              az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$OIDC_TOKEN" -o none
              az account set -s "$AZURE_SUBSCRIPTION_ID"
              az aks get-credentials -g rg-jenkins-lab -n aks-jenkins-lab -f "$KUBECONFIG" --overwrite-existing
              kubelogin convert-kubeconfig -l azurecli
              kubectl -n myapp set image deployment/myapp myapp="$IMAGE:$TAG"
              kubectl -n myapp annotate deployment/myapp kubernetes.io/change-cause="jenkins $BUILD_TAG" --overwrite
              if ! kubectl -n myapp rollout status deployment/myapp --timeout=180s; then
                kubectl -n myapp rollout undo deployment/myapp
                kubectl -n myapp rollout status deployment/myapp --timeout=180s
                exit 1
              fi
            '''
          }
        }
      }
    }
+ kubectl -n myapp set image deployment/myapp myapp=acrjenkins12345.azurecr.io/myapp:14-3c4d5e6
deployment.apps/myapp image updated
+ kubectl -n myapp rollout status deployment/myapp --timeout=180s
Waiting for deployment "myapp" rollout to finish: 1 old replicas are pending termination...
deployment "myapp" successfully rolled out

App Service commands

# Deploy to staging slot → smoke test → swap (slots require S1 or above)
az webapp config container set -g $RG -n $WEBAPP --slot staging \
  --container-image-name $ACR.azurecr.io/myapp:$TAG --container-registry-url https://$ACR.azurecr.io
az webapp config appsettings set -g $RG -n $WEBAPP --slot staging --settings APP_VERSION=$TAG -o none
curl -fsS https://$WEBAPP-staging.azurewebsites.net/healthz
az webapp deployment slot swap -g $RG -n $WEBAPP --slot staging --target-slot production

How to verify:az webapp config container show -g $RG -n $WEBAPP check the current image; az webapp log tail view the container startup logs. Common errors: Not setting WEBSITES_PORT causes “Container didn't respond to HTTP pings on port: 80”. The default hostname for a slot looks like <app>-<slot>.azurewebsites.net (if the new app has unique default hostnames enabled, the format in az webapp show --slot staging --query defaultHostName takes precedence).

Lab 5A (optional): AKS namespace-level deployment (about 15 minutes, billed hourly)

Cost / permissions / risks: one Standard_D2s_v5 node costs roughly US$0.1 / hour, plus a public load balancer IP; the Free-tier control plane is not charged. Requires Owner (--attach-acr to create role assignments). Delete the cluster when done.
1. Create the cluster and grant access
source ~/jenkins3.env
export AKS=aks-jenkins-lab
az aks create -g $RG -n $AKS -l $LOC --tier free --node-count 1 --node-vm-size Standard_D2s_v5 \
  --enable-aad --enable-azure-rbac --disable-local-accounts \
  --enable-oidc-issuer --enable-workload-identity --attach-acr $ACR -o none
AKS_ID=$(az aks show -g $RG -n $AKS --query id -o tsv)
ME=$(az ad signed-in-user show --query id -o tsv)
az role assignment create --assignee-object-id $ME --assignee-principal-type User --role "Azure Kubernetes Service RBAC Cluster Admin" --scope $AKS_ID -o none
az role assignment create --assignee-object-id $DEPLOY_PRINCIPAL --assignee-principal-type ServicePrincipal --role "Azure Kubernetes Service Cluster User Role" --scope $AKS_ID -o none
az role assignment create --assignee-object-id $DEPLOY_PRINCIPAL --assignee-principal-type ServicePrincipal --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp -o none
echo "export AKS=$AKS AKS_ID=$AKS_ID" >> ~/jenkins3.env
2. Admin creates the initial objects
az aks get-credentials -g $RG -n $AKS --overwrite-existing
kubelogin convert-kubeconfig -l azurecli
kubectl create namespace myapp
kubectl -n myapp create deployment myapp --image=$ACR.azurecr.io/myapp:bootstrap --port=5000 --replicas=2
kubectl -n myapp set env deployment/myapp APP_VERSION=bootstrap
kubectl -n myapp expose deployment myapp --type=LoadBalancer --port=80 --target-port=5000
kubectl -n myapp get svc myapp -w   # wait for EXTERNAL-IP
3. Verify the authorization boundary as the deployment identity (Simulating locally is impractical without OIDC, so run the “Commands” stage in Jenkins directly once and temporarily add a line)
kubectl auth can-i patch deployments -n myapp     # yes
kubectl auth can-i patch deployments -n default   # no
kubectl auth can-i create clusterrolebindings     # no
4. Run the deployment: add the Deploy to AKS stage to the Jenkinsfile (it can coexist with the ACA deployment), then after pushing curl http://<EXTERNAL-IP>/healthz.
Cleanup: az aks delete -g $RG -n $AKS --yes --no-wait; delete the AKS stage from the Jenkinsfile.

Lab 5B (optional): App Service custom container (about 10 minutes, B1 billed hourly)

1. Create the plan and app
source ~/jenkins3.env
export WEBAPP=app-myapp-$RANDOM; echo "export WEBAPP=$WEBAPP" >> ~/jenkins3.env
az appservice plan create -g $RG -n asp-jenkins-lab --is-linux --sku B1 -o none
az webapp create -g $RG -p asp-jenkins-lab -n $WEBAPP \
  --container-image-name $ACR.azurecr.io/myapp:bootstrap \
  --assign-identity $PULL_ID --acr-use-identity --acr-identity $PULL_ID -o none
az webapp config appsettings set -g $RG -n $WEBAPP --settings WEBSITES_PORT=5000 APP_VERSION=bootstrap -o none
az webapp config set -g $RG -n $WEBAPP --generic-configurations '{"healthCheckPath":"/healthz"}' -o none
curl -fsS https://$(az webapp show -g $RG -n $WEBAPP --query defaultHostName -o tsv)/healthz
ok
2. (Optional) deployment slot: az appservice plan update -g $RG -n asp-jenkins-lab --sku S1,az webapp deployment slot create -g $RG -n $WEBAPP --slot staging --configuration-source $WEBAPP, then deploy to staging and swap following the “Commands” section.
Cleanup: az webapp delete -g $RG -n $WEBAPP; az appservice plan delete -g $RG -n asp-jenkins-lab --yes.

Case 1: private AKS cluster

Problem: The API server has only a private endpoint, so the on-premises Jenkins agent cannot reach it.

Approach: Place the deployment agent in the cluster's VNet (or a peered VNet) (a VM or a pod agent inside AKS, Module 6); for emergency troubleshooting, use az aks command invoke (runs inside the cluster through ARM, with the command output returned).

Case 2: GitOps cluster run by the platform team

Problem: The cluster is managed by Flux, and if Jenkins directly kubectl set image the change is reconciled back.

Approach: Jenkins only pushes the image and commits the new tag to the config repository (Gitea / GitHub PR), and Flux deploys it; the Jenkins deployment identity no longer needs any AKS role.

Case 3: App Service cold start causes 503 after swap

Approach: Configure the health check path /healthz, send warm-up requests to staging before the swap; if needed, set WEBSITE_SWAP_WARMUP_PING_PATH=/healthz so the platform warms up that path during the swap.

Common AKS and App Service errors

Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "…" cannot patch resource "deployments" in API group "apps" in the namespace "myapp": User does not have access to the resource in Azure. Update role assignment to allow access.

Cause: The deployment identity has no Azure RBAC data-plane role for that namespace, or the role scope was set to the cluster with a misspelled namespace path, or the role was just assigned and has not taken effect yet (it may take a few minutes).

az role assignment list --assignee $DEPLOY_PRINCIPAL --scope "$AKS_ID/namespaces/myapp" -o table

Fix: Assign “Azure Kubernetes Service RBAC Writer”, with scope $AKS_ID/namespaces/myapp.

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code … (the build stays stuck)

Cause: The kubeconfig's exec plugin is still the default device-code mode; you forgot to kubelogin convert-kubeconfig -l azurecli, or the conversion did not target $KUBECONFIG the file it points to.

Fix: Run the conversion immediately after get-credentials ; add timeout(time: 10, unit: 'MINUTES') to the stage to prevent waiting forever.

Getting static credential is not allowed because this cluster is set to disable local accounts.

Cause: The script used az aks get-credentials --admin.

Fix: Remove --admin, and use Entra identity + Azure RBAC.

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

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

az webapp config appsettings list -g $RG -n $WEBAPP --query "[?name=='WEBSITES_PORT']"

Fix:az webapp config appsettings set … --settings WEBSITES_PORT=5000.

App Service log: pull access denied / unauthorized (failed to pull the ACR image)

Cause: Not enabled acrUseManagedIdentityCreds, or the user-assigned identity is not set as the pull identity / has no AcrPull.

az webapp config show -g $RG -n $WEBAPP --query "{mi:acrUseManagedIdentityCreds, id:acrUserManagedIdentityId}"

Fix:az webapp config set -g $RG -n $WEBAPP --generic-configurations '{"acrUseManagedIdentityCreds": true, "acrUserManagedIdentityID": "<clientId>"}'.

Command-line exercise
1. Assign Kubernetes write permission to the deployment identity that is valid only within the myapp namespace.
az role assignment create --assignee-object-id $DEPLOY_PRINCIPAL --assignee-principal-type ServicePrincipal \
  --role "Azure Kubernetes Service RBAC Writer" --scope "$AKS_ID/namespaces/myapp"
2. On App Service, swap the staging slot to production.
az webapp deployment slot swap -g rg-jenkins-lab -n $WEBAPP --slot staging --target-slot production
Scenario analysis
Your Jenkins runs on-premises, AKS is a private cluster, and the security team requires local accounts to be disabled and the deployment identity to be unable to see other namespaces. Give a complete design.

Run a dedicated deployment Jenkins pod agent in AKS (Kubernetes plugin; the controller is on-premises and connects via WebSocket / an inbound port — the agent needs outbound access to the controller); the pod uses workload identity (ServiceAccount federated to id-jenkins-deploy), the Kubernetes cloud has “Restrict pipeline support to authorized folders” enabled; the deployment identity has only Cluster User Role and namespaces/myapp the RBAC Writer role; the kubeconfig uses kubelogin convert-kubeconfig -l workloadidentity. The cluster keeps --disable-local-accounts. If the controller cannot be reached from the cluster, fall back to az aks command invoke for troubleshooting only.

Verified teaching videos

▶
Kubelogin to connect to Kubernetes — Houssem Dellai
English · kubelogin login modes
▶
AKS Integration with Azure AD explained in plain English - Azure RBAC, Kubernetes RBAC, … — cloud-monk - cloud in plain english
English · AKS Entra integration and Azure RBAC
▶
How to use Deployment Slots in Azure App Service for Containers | Azure Tips and Tricks — Microsoft Azure
English · deployment slots for container apps

The videos above were verified via YouTube oEmbed (2026-11-16).

Official docs

Video storyboard

Shot 1 · 0:00–0:30
Visual: the agent first knocks on ARM's door to get the kubeconfig, then knocks on the API server's door.
Narration: deploying to AKS passes through two gates: ARM decides whether you can get the connection info, and Azure RBAC decides what you can do in which namespace.
Shot 2 · 0:30–1:00
Visual: the exec section in the kubeconfig is highlighted, and kubelogin takes a token from the Azure CLI cache.
Narration: convert kubelogin to azurecli mode, and kubectl reuses the identity the pipeline has already signed in with.
Shot 3 · 1:00–1:40
Visual: two App Service slots; after staging turns green, it swaps places with production.
Narration: App Service uses deployment slots to warm up before switching; rollback is just swapping again.

This lesson cannot directly generate a video or MP3, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Module 6 · Jenkins agents on Azure: VMs, ACI, and AKS

37:00 – 45:00 · On-demand cloud agents: which plugins are still maintained, how identities are granted, and how the network connects
8 minAzure VM Agents 1124.v… · Kubernetes 4560.v…★★★★☆
Learning goals
  • Compare three dynamic agent options on Azure: Azure VM Agents (VMs created from ARM templates),Azure Container Agents (ACI containers),Kubernetes plugin + AKS (pods), and the current maintenance status of each.
  • Understand the connection direction between agent and controller: SSH (controller → agent) and inbound / WebSocket (agent → controller), and what this means for a “controller on-premises + agents in the cloud” setup.
  • Configure workload identity for an AKS pod agent, and use “Restrict pipeline support to authorized folders” to limit who can use pod templates that carry an identity.
Prerequisites: Lesson 1 agents / executors / labels; Module 2 workload identity. Importance: ★★★★☆

What: three cloud agent plugins (plugins.jenkins.io, 2026-11-16)

PluginLatest version / releaseMaintenance statusHow agents are createdAuthentication to Azure
Azure VM Agents (azure-vm-agents)1124.v89b_2f7a_76f35 · 2026-11-03Community-maintained, active; Microsoft support ended on 2024-02-29Creates VMs from ARM templates; starts via SSH or inbound; retention strategies: Idle / Pool / OnceAzure Credentials: service principal, or a managed identity when the controller is on Azure
Azure Container Agents (azure-container-agents)372.v073266fff4a_7 · 2025-02-26Community-maintained, few updates; Microsoft support has endedACI container group, default image jenkins/inbound-agent, billed per secondSame as above (service principal or managed identity)
Kubernetes (kubernetes)4560.vc25b_83890c34 · 2026-10-08Very active; one of the core Jenkins community pluginsOne pod per build (jnlp container + tool containers)Cluster API uses kubeconfig / ServiceAccount; inside the pod, Azure access uses workload identity
Azure Container Service (azure-acs), Azure App Service, and ACR Tasks pluginsNo releases since 2021deprecatedDo not use for new work; the Azure Container Agents README also states that for AKS scenarios you should use the Kubernetes plugin instead

Why: why use dynamic agents

  • Created on demand and destroyed after use: low cost, clean environment (no leftover login state or workspace from a previous Job).
  • Deployment and ordinary builds can use different templates, identities, and networks.
  • Costs: startup latency (minutes for VMs; ACI and pods depend on image size), cloud quotas, and network connectivity design.

How: the connection direction determines the network design

Startup methodDirectionwhen the controller is on-premises and the agent is on Azure
SSH (recommended for VM Agents)controller → agent:22Requires VPN / ExpressRoute, or a public IP on the VM + NSG restricting source IPs
Inbound TCP (JNLP, port 50000)agent → controllerthe controller's agent port must be reachable from Azure
Inbound WebSocketagent → controller:443/8080 (HTTP)Only the controller's HTTP(S) needs to be reachable, which is easiest through proxies; the Kubernetes plugin supports this

The controller in this lesson's local environment is bound to 127.0.0.1:8080, so agents on Azure cannot connect back to it. This module's lab is therefore mainly reading plus optional exercises; in Lesson 5 you will move the controller itself into Kubernetes, and the pod agent will then be in the same cluster.

When: how to choose

  • Need a full VM (Windows builds, a Docker daemon, GPU, nested virtualization) → Azure VM Agents; use custom images (Azure Compute Gallery) to shorten startup time, and reclaim with the Idle retention strategy.
  • Short tasks, no Docker daemon requirement, and no desire to maintain a cluster → ACI (note the plugin is updated infrequently; first verify compatibility with the current LTS in a test environment).
  • Already have AKS → Kubernetes plugin (the mainstream choice), with workload identity attached to deployment pod templates.
Common misconceptions① “If Microsoft no longer supports it, it cannot be used”: the community still publishes releases; before production use, just check the latest release date, security advisories, and compatibility with the current LTS. ② “Pod agents isolate identity automatically”: the Kubernetes plugin allows inline Pod YAML in the Jenkinsfile, and anyone who can write a Jenkinsfile can specify serviceAccountName; you must use a separate namespace + “Restrict pipeline support to authorized folders”. ③ “An ACI agent can run docker build directly”: an ACI container has no Docker daemon and cannot mount the host socket.

Diagram 1: provisioning paths for the three dynamic agents

Jenkins controllerQueue has a label demand→ Cloud.provision() Azure VM AgentsARM deploys VM (minutes) → SSH starts agent Azure Container AgentsACI container group → inbound connects back to controller Kubernetes pluginPOST Pod → jnlp container connects back (WebSocket) VM: can attach a managed identityaz login --identity (whole VM) ACI: the container group can attach a managed identitywhether the plugin template exposes this option depends on the actual UI Pod: workload identitySA token → --federated-token
Figure 6-1: when the controller finds label demand in the queue that cannot be met, it calls the matching Cloud implementation to provision an agent

Diagram 2: pod agent with workload identity

Namespace jenkins-deploy (restricted Kubernetes cloud) jnlp containerconnects back to controllerRuns sh step (scheduled) az containermcr…/azure-cli:2.89.1AZURE_FEDERATED_TOKEN_FILESA: sa-jenkins-deploy AKS OIDC issuerpublic key (read by Entra) Entrafederated credential matches the SA ARM / ACRDeploy
Figure 6-2: subject = system:serviceaccount:jenkins-deploy:sa-jenkins-deploy

Animation: the three agents, from “queued” to “execution started”

Durations are illustrative only and depend on image size, region, quotas, and caching; this is not a benchmark.

Click “Play”.

Kubernetes plugin: pod template with workload identity

pipeline {
  agent {
    kubernetes {
      cloud 'aks-deploy'                      // restricted cloud configured by the admin (authorized for the deployment folder only)
      yaml '''
apiVersion: v1
kind: Pod
metadata:
  labels:
    azure.workload.identity/use: "true"
spec:
  serviceAccountName: sa-jenkins-deploy
  containers:
  - name: az
    image: mcr.microsoft.com/azure-cli:2.89.1
    command: ["sleep"]
    args: ["infinity"]
'''
    }
  }
  stages {
    stage('Azure') {
      steps {
        container('az') {
          sh '''
            set -eu
            az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" \
              --federated-token "$(cat "$AZURE_FEDERATED_TOKEN_FILE")" -o none
            az account show --query user -o jsonc
          '''
        }
      }
    }
  }
}

AZURE_CLIENT_ID,AZURE_TENANT_ID,AZURE_FEDERATED_TOKEN_FILE,AZURE_AUTHORITY_HOST injected by the AKS workload identity webhook into every container in a labeled pod (you can use the annotation azure.workload.identity/skip-containers to exclude jnlp). The official docs require reading the token file path from an environment variable, not hard-coding it.

Azure-side configuration

source ~/jenkins3.env
ISSUER_AKS=$(az aks show -g $RG -n $AKS --query oidcIssuerProfile.issuerUrl -o tsv)
az identity federated-credential create -g $RG --identity-name $DEPLOY_ID -n fic-aks-jenkins-deploy \
  --issuer "$ISSUER_AKS" --subject system:serviceaccount:jenkins-deploy:sa-jenkins-deploy \
  --audiences api://AzureADTokenExchange
kubectl create namespace jenkins-deploy
kubectl -n jenkins-deploy create serviceaccount sa-jenkins-deploy
kubectl -n jenkins-deploy annotate serviceaccount sa-jenkins-deploy azure.workload.identity/client-id=$DEPLOY_CLIENT_ID

Key points for Azure VM Agents / ACI (UI configuration; switch to JCasC in Lesson 5)

SettingVM AgentsContainer Agents (ACI)
LocationManage Jenkins → Clouds → New cloud → Azure VM Agents… → Azure Container Instance
CredentialsAzure Credentials (service principal or managed identity)Same as left
Required Azure permissions (README)Resource group Contributor is the simplest option; for finer scope: Virtual Machine Contributor, Network Contributor, Storage (Windows / inbound), Managed Identity Operator (when attaching an identity in the template)Permission to create container groups in the resource group
ImageBuilt-in Ubuntu / Windows or a custom image (Compute Gallery requires Reader)Default jenkins/inbound-agent, private registries need a credential
RetentionIdle (minutes) / Pool / OnceRetention policy (delete after use by default)
NetworkOptional VNet, private IP, NSG (SSH requires port 22 open)Optional private IP (VNet); it must be able to connect back to the controller
# Observe the resources the plugin creates in the resource group (VM Agents are named with the template name prefix by default)
az vm list -g rg-jenkins-agents -o table
az container list -g rg-jenkins-agents -o table
# Prevent “orphaned” resources: periodically check for and delete agent resources older than 1 day
az resource list -g rg-jenkins-agents --query "[?createdTime<'$(date -u -d '-1 day' +%FT%TZ)'].id" -o tsv

createdTime Needs --expand createdTime before it returns: az resource list -g … --expand createdTime. Common errors: If the controller restarts or the plugin fails, VMs are not deleted and keep billing. Set a separate budget alert on the agent resource group.

Lab 6 (optional, requires the AKS cluster from Module 5): the Pod agent signs in to Azure with workload identity (about 15 minutes)

Prerequisites and limitations: the local controller is bound to 127.0.0.1, so Pods in AKS cannot connect back. The full exercise requires the controller to be reachable from the cluster (most natural after Lesson 5 installs Jenkins into the cluster). This lab first verifies the Azure side and the Kubernetes side of the identity chain, using a plain Pod in place of the Jenkins Pod. Cost: AKS nodes are billed hourly.
1. Complete the Azure-side setup on the “Commands” tab (federated credential, namespace, ServiceAccount annotation).
2. Verify sign-in with the same Pod spec
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: wi-test
  namespace: jenkins-deploy
  labels:
    azure.workload.identity/use: "true"
spec:
  serviceAccountName: sa-jenkins-deploy
  restartPolicy: Never
  containers:
  - name: az
    image: mcr.microsoft.com/azure-cli:2.89.1
    command: ["sh","-c"]
    args: ["az login --service-principal -u $AZURE_CLIENT_ID -t $AZURE_TENANT_ID --federated-token \"$(cat $AZURE_FEDERATED_TOKEN_FILE)\" -o none && az resource show -g rg-jenkins-lab -n ca-myapp --resource-type Microsoft.App/containerApps --query name -o tsv"]
EOF
kubectl -n jenkins-deploy wait --for=jsonpath='{.status.phase}'=Succeeded pod/wi-test --timeout=180s
kubectl -n jenkins-deploy logs wi-test
ca-myapp

If the output AADSTS700213: check the namespace and SA name in the subject; if the environment variable is empty, the Pod is missing the label or the cluster does not have workload identity enabled.

3. Verify the security boundary: try again from another namespace with an SA of the same name; it should fail (the subject differs). This is why deployment Pods should run in a separate namespace and use a restricted Kubernetes cloud.
Cleanup: kubectl delete ns jenkins-deploy; az identity federated-credential delete -g $RG --identity-name $DEPLOY_ID -n fic-aks-jenkins-deploy --yes; delete the cluster when you no longer need AKS.

Case 1: Windows builds with VM Agents + Compute Gallery image

Problem:.NET Framework builds need Windows + Visual Studio Build Tools, and the built-in image's init script takes 25 minutes every time.

Approach: Build a custom image with Packer and publish it to Azure Compute Gallery; the template references that image, with Idle retention of 30 minutes. VMs get a managed identity that only has write access to the build artifact storage.

Case 2: Separate deployment Pods from build Pods

Approach: Two Kubernetes clouds: aks-build (available to all folders, no identity attached) and aks-deploy (granted only to deploy/ folder, namespace jenkins-deploy, with the SA bound to workload identity). Regular developers cannot use aks-deploy in their own Jenkinsfile.

Case 3: Orphaned VM bill

Problem: The controller restarted unexpectedly, and the 12 VMs created by VM Agents were not deleted, generating charges over the weekend.

Approach: A dedicated resource group for agents + a budget alert + a scheduled job that cleans up agent resources older than 24 hours; upgrade the plugin to the latest version (which fixes several cleanup issues).

Common cloud agent issues

Builds stuck showing “Waiting for next available executor on ‘aci’” / “All nodes of label ‘aci’ are offline”

Cause: The container group was created, but the agent cannot connect back to the controller (controller URL unreachable, inbound port not open, WebSocket not enabled), or the image pull failed.

az container show -g rg-jenkins-agents -n <container-group> --query "containers[0].instanceView.events[-3:]" -o table
az container logs -g rg-jenkins-agents -n <container-group>

Fix: Confirm that the Jenkins URL under Manage Jenkins → System is reachable from Azure; open the inbound port or switch to WebSocket. Lesson 7 covers “why builds get stuck in the queue” in depth.

Azure VM Agents: Deployment failed … AuthorizationFailed / SkuNotAvailable / QuotaExceeded

Cause: The credential identity lacks permissions (see the per-feature required roles in the README); the VM size is not available in this region; vCPU quota is insufficient.

az vm list-skus -l canadacentral --size Standard_D2s --query "[].{n:name,r:restrictions[0].reasonCode}" -o table
az vm list-usage -l canadacentral --query "[?contains(name.value,'standardDSv5Family')]" -o table

Fix: Add the missing roles; choose a different size; request a quota increase.

$AZURE_FEDERATED_TOKEN_FILE is empty in the Pod agent

Cause: The Pod has no label azure.workload.identity/use: "true"; the cluster has not enabled --enable-workload-identity; the SA annotation was changed but the Pod is still the old one.

kubectl -n jenkins-deploy get pod <pod> -o jsonpath='{.metadata.labels}{"\n"}{.spec.containers[*].env[*].name}'

Fix: Add the label in the Pod template YAML; enable the cluster feature; rerun the build (new Pod).

ERROR: Unable to provision agent … Pod is forbidden / serviceaccount "sa-jenkins-deploy" not found

Cause: The namespace of the Kubernetes cloud does not match the namespace where the SA lives, or the cluster credential Jenkins uses does not have permission to create Pods in that namespace.

Fix: Set the namespace in the cloud configuration to jenkins-deploy; give Jenkins' cluster credential minimal RBAC (pods, pods/exec, pods/log).

Command-line tasks
1. Create a federated credential for jenkins-deploy/sa-jenkins-deploy in AKS.
ISSUER_AKS=$(az aks show -g rg-jenkins-lab -n aks-jenkins-lab --query oidcIssuerProfile.issuerUrl -o tsv)
az identity federated-credential create -g rg-jenkins-lab --identity-name id-jenkins-deploy -n fic-aks-jenkins-deploy \
  --issuer "$ISSUER_AKS" --subject system:serviceaccount:jenkins-deploy:sa-jenkins-deploy --audiences api://AzureADTokenExchange
2. List all container groups in the agent resource group and their states.
az container list -g rg-jenkins-agents --query "[].{n:name,state:instanceView.state}" -o table
Scenario analysis
The team wants to run Jenkins agents on ACI to save money, but builds need docker build. Give a feasible approach and the trade-offs.

ACI has no Docker daemon and cannot mount the host socket. Options: ① use az acr build (ACR Tasks, a paid subscription; the identity needs Tasks Contributor), ② build inside the container with Kaniko / BuildKit rootless (verify ACI's permission model), ③ move builds to VM Agents (full Docker) and use ACI only for tests / deployment. Also consider that the Azure Container Agents plugin is updated infrequently (last released 2025-02), so validate it on the current LTS before going live; an AKS Pod agent is often the safer “containerized agent” choice.

Verified training videos

▶
How to Use Kubernetes Pods As Jenkins Agents — CloudBeesTV
English · Kubernetes plugin Pod agent
▶
Effectively Using Kubernetes Plugin with Jenkins — CloudBeesTV
English · Pod templates and multi-container
▶
Workload Identity (OIDC) for AKS — Houssem Dellai
English · AKS workload identity demo

The videos above were verified via YouTube oEmbed (2026-11-16). No verified recent demo videos were found for the Azure VM Agents / Azure Container Agents plugins.

Official docs

Video storyboard

Shot 1 · 0:00–0:30
Visual: a build in the queue holds a sign reading “label: azure-deploy”, and three clouds raise their hands at once.
Narration: when the queue contains a label requirement that can't be met, Jenkins calls a cloud plugin to create an agent on the fly.
Shot 2 · 0:30–1:10
Visual: VMs build up slowly, ACI containers appear quickly, and Pods start within seconds on existing nodes.
Narration: VMs are the most flexible but slowest, ACI bills per second but has limited features, and Pods suit teams that already run AKS best.
Shot 3 · 1:10–1:40
Visual: the Pod template with an identity is locked inside the “deploy folder”, out of reach of ordinary jobs.
Narration: a template with an identity must be restricted to specific folders; otherwise any Jenkinsfile could borrow that identity.

This lesson cannot generate a video or MP3 directly, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Module 7 · Troubleshooting cloud deployments in practice

45:00 – 54:00 · Locate issues by layer: “Jenkins → token → Entra → ARM → data plane → runtime”
9 minAADSTS · AuthorizationFailed · ACR · ACA★★★★★
Learning goals
  • Use the six-layer model to classify any cloud deployment failure: L1 Jenkins credential / binding → L2 token contents → L3 Entra exchange → L4 ARM authorization → L5 data plane (ACR / kube-apiserver) → L6 runtime (revisions, Pods, containers).
  • Get comfortable with diagnostic commands: decode JWT claims,az identity federated-credential list,az role assignment list,az monitor activity-log list,az containerapp logs show,az acr check-health.
  • In the lab, inject four types of fault and fix them.
Prerequisites: Modules 2–6. Importance: ★★★★★

What: the six-layer model

LayerTypical symptom / errorFirst diagnostic command
L1 Jenkins credentialCould not find credentials entry with ID 'azure-oidc-token'; credential type mismatch; az: not foundJenkins credentials page scope (global / folder); echo $NODE_NAME
L2 token contentsToken sub / iss / aud does not match expectationsDecode the payload (Module 2 lab, step 5)
L3 Entra exchangeAADSTS700213,AADSTS90061,AADSTS700024,AADSTS7000215 (invalid key),AADSTS7000222 (expired key)az identity federated-credential list; az ad app credential list
L4 ARM authorizationAuthorizationFailed,LinkedAuthorizationFailed,No subscriptions foundaz role assignment list --assignee <principalId> --all
L5 data planeACR unauthorized: authentication required; kubectl Forbidden … does not have access to the resource in Azureaz acr show --query roleAssignmentMode; kubectl auth can-i
L6 runtimeRevision Failed / Unhealthy, ImagePullBackOff, App Service port probe failureaz containerapp logs show --type system; kubectl describe pod

Why: layer first, then act

  • Many people see “deployment failed” and immediately change roles, but AADSTS700213 the failure is at L3, and a bigger role (L4) won't help.
  • Errors before L3 do not appear in the Azure activity log; L4 denials appear in the activity log (failed write operations); for L5 / L6, check the service's own logs.

How: read the clues in the error

  • AADSTS code → L3; the error usually includes Trace ID and Correlation ID, which you can search in the Entra sign-in logs (service principal sign-ins / managed identity sign-ins).
  • “The client '…' with object id '…'” → L4: the object id is the denied principal, so first confirm it is the identity you expect (OIDC uses id-jenkins-deploy, not your user).
  • “over scope '…'” → tells you the resource ID that lacks permission; assign the role to that resource or one of its parents.
  • RBAC propagation: new role assignments usually take effect within a few minutes; when the old access token cached by Azure CLI lacks new group membership info, run az login again.

When: when to use Jenkins' own logs

  • Credential not found, wrong type, plugin errors: Manage Jenkins → System Log; controller container docker compose logs jenkins.
  • OIDC plugin issuer configuration: validation hints on the credential page (“Unable to determine the issuer URI”, etc.).
Common misconceptions① “Adding Owner fixes everything” — problems at L3 / L5 / L6 have nothing to do with ARM roles, and Owner carries major risk. ② “Retrying three times is enough” — retries help with RBAC propagation issues, but if the subject does not match, retrying ten thousand times won't help. ③ “If I can't see the token in the logs, I can't troubleshoot” — decoding the claims (without printing the signature) is enough to pinpoint L2.

Diagram: six-layer locating map

L1 JenkinsCredential / bindingagent tooling L2 tokeniss / sub / audexp L3 EntraAADSTS…Sign-in logs L4 ARMAuthorizationFailedActivity log L5 data planeACR 401 / k8s 403Service logs L6 runtimeRevision / PodContainer logs Not visible in the Azure activity log (the request never reached ARM)Check the Jenkins console, decode the token, Entra sign-in logs Recorded on the Azure sideActivity log, ACR / AKS diagnostics, container logs
Figure 7-1: first determine which layer the request reached, then choose the diagnostic tool

Interactive: error classifier

Paste an error from the Jenkins console (or click an example), and the classifier uses keywords to report the layer, the most likely cause, and the first diagnostic command. The rules match this lesson's content. This is not an official tool.

Waiting for input.

Troubleshooting command box

LayerCommandWhat to look for
L2Decode the JWT payload (Module 2 lab, step 5)iss trailing slash,sub in %252F,exp
L3az identity federated-credential list -g $RG --identity-name $DEPLOY_ID -o yamland compare verbatim with the JWT
L3curl -s $ISSUER/.well-known/openid-configuration | jq -r .issuer,.jwks_uripublicly reachable, issuer matches
L4az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o tableRoles and scope
L4az monitor activity-log list -g $RG --offset 1h --status Failed --query "[].{op:operationName.value, who:caller, status:status.value}" -o tableDenied write operations and caller
L5az acr check-health -n $ACR --yes; az acr show -n $ACR --query roleAssignmentModeDNS / authentication / mode
L5kubectl auth can-i --list -n myappPermissions of the current identity in the namespace
L6az containerapp logs show -g $RG -n $APP --type system --tail 50Image pulls, probes, crashes
L6az containerapp revision list -g $RG -n $APP -o tableWhich revision receives traffic
source ~/jenkins3.env
az monitor activity-log list -g $RG --offset 1h --status Failed \
  --query "[].{time:eventTimestamp, op:operationName.value, caller:caller, msg:properties.statusMessage}" -o table
Time                          Op                                     Caller                                Msg
----------------------------  -------------------------------------  ------------------------------------  -----------------------------------------
2026-11-16T15:02:11.12+00:00  Microsoft.App/containerApps/write      3f1c…(id-jenkins-deploy principal)    {"error":{"code":"AuthorizationFailed",…

Note: Activity log entries can be delayed by a few minutes; for service principals / managed identities, the caller shows as an object ID or application ID. Production use: Export the activity log to Log Analytics and set up alerts by deployment identity.

Lab 7: four fault injections (about 9 minutes)

Fault 1 (L3): delete the federated credential
source ~/jenkins3.env
az identity federated-credential delete -g $RG --identity-name $DEPLOY_ID -n fic-jenkins-myapp-main --yes

Trigger a main build → expect the Push stage AADSTS700213. Fix: recreate it following step 6 of the Module 2 lab, wait about 1 minute, then rerun.

Fault 2 (L5): revoke AcrPush (also temporarily remove Contributor, otherwise pushes still succeed in RBAC mode)
az role assignment delete --assignee $DEPLOY_PRINCIPAL --role AcrPush --scope $ACR_ID
az role assignment delete --assignee $DEPLOY_PRINCIPAL --role Contributor --scope $RG_ID

Expected: az acr login fails when reading the registry (L4), or when pushing unauthorized: authentication required (L5). Check which layer the error belongs to. Fix: re-assign both roles as described on the warm-up page and wait a few minutes.

Fault 3 (L6): wrong target port
az containerapp ingress update -g $RG -n $APP --target-port 8080
curl -s -o /dev/null -w "%{http_code}\n" https://$FQDN/healthz
az containerapp logs show -g $RG -n $APP --type system --tail 20

Expected: non-200 / probe failure. Fix: --target-port 5000.

Fault 4 (L2): change the Jenkins URL: under Manage Jenkins → System, change the Jenkins URL to http://127.0.0.1:8080/, trigger a build → AADSTS700213, decoding the token shows sub the prefix has changed. Fix: change it back to http://localhost:8080/.
Record: for each fault, write down “symptom → layer → diagnostic command → fix”; this is the beginning of your team's runbook.

Case 1: all deployments fail on Monday morning

Symptom: All AADSTS7000222. Root cause: The service principal secret was created a year earlier and expired over the weekend. Fix and prevention: Temporarily az ad app credential reset --append, update the Jenkins credential; afterwards, migrate to OIDC and set an alert 30 days before the expiry of any remaining secrets.

Case 2: fails on only one branch

Symptom:release/2026.11 Branch AADSTS700213, main is fine. Root cause: The branch name contains /, and in the job URL it is release%252F2026.11, while the federated credential was written as release/2026.11. Fix: Copy the decoded sub; or, using claim templates, use ${BRANCH_NAME} or another stable claim (evaluate how easily it can be forged).

Case 3: deployment succeeds but users report 502

Symptom: The pipeline is green, and the smoke test only checked /healthz, but the downstream service address the home page depends on is misconfigured. Fix: Add critical-path checks to the smoke test; in ACA multi-revision mode, validate at 0% traffic first.

More real-world errors

ERROR: Could not find credentials entry with ID 'azure-oidc-token'

Cause: The credential was created in another folder, or the ID is spelled differently; OIDC credentials only support the global domain.

Fix: Create it in the job's folder or in the root “Global” domain; check the ID's letter case.

No subscriptions found for 3f1c….

Cause: The identity has no role assignment on any subscription (or on resource groups / resources under it); or the role was just assigned and has not yet taken effect.

Fix: Retry after assigning the role; when you only need tenant-level resources (such as Graph), use --allow-no-subscriptions.

ERROR: 'containerapp' is misspelled or not recognized by the system.

Cause: The Azure CLI on the agent does not have the containerapp extension, and dynamic installation is disabled or requires interactive confirmation.

az extension add --name containerapp --upgrade --yes

Fix: Bake the extension installation into the agent image (append one line to the Dockerfile on the setup page); don't install it on every build.

(LinkedAuthorizationFailed) The client has permission to perform action 'Microsoft.App/containerApps/write' on scope '…', however it does not have permission to perform action(s) '…/join/action' on the linked scope(s) '…/managedEnvironments/cae-jenkins-lab'

Cause: The deployment identity only has permissions on the Container App, but the operation also involves linked resources (environment, managed identity).

Fix: Add the minimum required permissions based on the operations and scope listed in the error (a custom role, or built-in roles assigned on the linked resources).

Warning: A secret was passed to "sh" using Groovy String interpolation, which is insecure.

Cause:sh "az login … ${OIDC_TOKEN}" (double quotes) make Groovy interpolate first, so the token may appear in process arguments and build records.

Fix: Use single quotes instead sh '… $OIDC_TOKEN …', so the shell expands it.

Command-line tasks
1. Query the failed ARM operations and their callers in rg-jenkins-lab in the last hour.
az monitor activity-log list -g rg-jenkins-lab --offset 1h --status Failed --query "[].{op:operationName.value,caller:caller}" -o table
2. Verify that the issuer in the discovery document on the static website matches the expected value.
test "$(curl -s $ISSUER/.well-known/openid-configuration | jq -r .issuer)" = "$ISSUER" && echo match
Scenario analysis
The same Jenkinsfile deploys successfully on main but fails with AADSTS700213 after a Replay. What does Replay change?

Replay creates a new build of the same job; the job URL does not change, so sub usually stays the same. To troubleshoot: check whether the Replay ran in another job (for example, a copied test job); whether the credential ID was changed during the Replay so that a different OIDC credential was used (different issuer; for example, the default issuer of a folder-level credential is the folder URL); or whether someone also changed the Jenkins URL or claim templates. Decoding the token and comparing iss and sub is enough to pinpoint the cause.

Verified training videos

▶
Azure DevOps Workload Identity Federation with Azure Overview. NO MORE SECRETS! — John Savill's Technical Training
English · Federated credential principles (ADO perspective; the issuer/subject/audience concepts are general)
▶
Authentication fundamentals: Federation | Microsoft Entra ID — Microsoft Azure
English · Federated authentication basics

The videos above were verified via YouTube oEmbed (2026-11-16). No verified video on “Jenkins cloud troubleshooting” was found; please use the storyboard below.

Official docs

Video storyboard

Shot 1 · 0:00–0:30
Visual: a six-story building, each floor with a sign: Jenkins, token, Entra, ARM, data plane, runtime.
Narration: when a cloud deployment fails, first ask which floor the request reached.
Shot 2 · 0:30–1:10
Visual: an AADSTS error card is pinned to the third floor; an AuthorizationFailed card is pinned to the fourth floor.
Narration: an AADSTS error is a failed identity exchange and has nothing to do with roles; only AuthorizationFailed calls for checking role assignments.
Shot 3 · 1:10–1:40
Visual: the decoded JWT and the federated credential are compared side by side, with the %252F in sub circled in red.
Narration: compare the token claims with the federated credential character by character; most identity problems are obvious at a glance.

This lesson cannot generate a video or MP3 directly, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Module 8 · Cost, cleanup, and self-check

54:00 – 60:00 · Know where the money goes, clean up in the right order, and leave no permission leftovers
6 minrg-jenkins-lab · canadacentral★★★★☆
Learning goals
  • List how each resource in this lesson is billed, and estimate the cost order of magnitude of one lab run.
  • Clean up in this order: Jenkins-side credentials and pipelines → objects outside the Azure resource group (Entra apps, subscription-level roles) → the resource group.
  • Review the Module 7 layered troubleshooting using the interactive troubleshooting tree.
Prerequisites: all modules in this course. Importance: ★★★★☆

What: cost breakdown (example magnitudes; the pricing calculator is authoritative)

ResourceBilling modelMagnitude in this lessonCost-saving tips
ACR BasicDaily fixed fee + excess storageAbout $0.17 / dayDelete immediately after the lab; in production, use a retention policy to clean up old tags
Container Apps (consumption)vCPU-seconds + GiB-seconds + requests; each subscription gets a monthly free allowanceUsually 0--min-replicas 0
Log AnalyticsPer GB ingested< $1Few system logs; turn off diagnostics you don't need
Storage account (static website)Storage + requests≈ 0—
AKS (optional)Node VMs billed per second; control plane on the Free tier is not charged; load balancers and public IPsAbout $0.1 / hour / node (D2s_v5 class)Run the delete right after finishing az aks delete; or az aks stop
App Service (optional)Per plan instance-hour, B1 / S1B1 is about $0.02 / hour, S1 is higherDeployment slots require S1; delete the plan after the lab
VM / ACI agent (optional)VMs billed per second + disk + IP; ACI billed per vCPU / GB-secondDepends on the retention policyIdle retention + agent resource group budget
Managed identities, role assignments, federated credentialsFree0but they are permissions, and must be cleaned up

Why: why the cleanup order matters

  • Deleting a resource group removes the managed identities in it (along with their federated credentials) and role assignments scoped within the resource group; but does not delete: Entra app registrations / service principals (the optional one from Module 2 sp-jenkins-lab), subscription-level role assignments, Jenkins credentials, or the deployment stages in the Jenkinsfile.
  • First stop Jenkins' automatic deployment, so that no build recreates resources or triggers a flood of alerts during cleanup.

How: budget alerts

In the portal, Cost Management → Budgets create a $10 monthly budget for the subscription or resource group, sending emails at 50% / 80% / 100% thresholds. Budget alerts are delayed (based on billing data refresh); they are a “safety net”, not real-time circuit breaking.

When: when to stop instead of delete

  • AKS: az aks stop Stopping ends control plane and node billing (disks and other resources are still billed); suitable if you will continue the next day.
  • ACA: --min-replicas 0 Scaling to zero replicas is already sufficient; no need to stop.
  • ACR / App Service plan: there is no “stop billing” option; delete them when not in use.
Common misconceptions① “Deleting the resource group means everything is gone” — the Entra app, subscription-level roles, and Jenkins credentials all still exist. ② “Managed identities are free, so leaving them doesn't matter” — what remains is exploitable permissions and federated trust relationships. ③ “Budgets automatically stop resources” — by default, budgets only send notifications; extra automation is needed to take action.

Diagram: cleanup order

① Jenkins sideRemove Push / Deploy stageDelete azure-oidc-tokenDelete azure-sp-lab, Kubernetes cloud ② Outside the resource groupaz ad app delete (sp-jenkins-lab)Subscription-level role assignmentsBudget (if no longer needed) ③ az group deleteACR, ACA, identities (including federated credentials)Storage static website, AKS, App ServiceRole assignments inside the RG ④ Verifyaz group exists → falseMC_ node resource group is goneNo Azure credentials in Jenkins
Figure 8-1: stop automation first, then delete objects outside the resource group, and finally delete the resource group and verify

Interactive: cost estimator (sample prices)

Unit prices are 2026 public prices, shown as order-of-magnitude examples (USD), only for judging where the money goes; the Azure pricing calculator is authoritative.

Cleanup commands

CommandPurpose
az ad app list --display-name sp-jenkins-lab --query "[].appId" -o tsvFind the app registration created in the optional step
az ad app delete --id <appId>Delete the app (the service principal and its secrets are deleted with it)
az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o tableConfirm no leftover roles outside the resource group
az group delete -n rg-jenkins-lab --yes --no-waitDelete all lab resources
az group exists -n rg-jenkins-labReturns false when done.
az group list --query "[?starts_with(name,'MC_rg-jenkins-lab')].name" -o tsvWhether the AKS node resource group was deleted along with the cluster
source ~/jenkins3.env
# ② Outside the resource group
APPID=$(az ad app list --display-name sp-jenkins-lab --query "[0].appId" -o tsv); [ -n "$APPID" ] && az ad app delete --id $APPID
az role assignment list --assignee $DEPLOY_PRINCIPAL --all --query "[?!starts_with(scope, '$RG_ID')]" -o table
# ③ Resource group
az group delete -n $RG --yes --no-wait
# ④ Verify (deletion usually takes a few minutes to a dozen or so minutes)
until [ "$(az group exists -n $RG)" = "false" ]; do sleep 30; echo waiting…; done; echo deleted
waiting…
waiting…
deleted

Jenkins side: delete in Manage Jenkins → Credentials azure-oidc-token,azure-sp-lab; if you installed Azure VM Agents / Container Agents / Kubernetes cloud configurations, delete them too; from Jenkinsfile remove the Push / Deploy / Smoke stages (or keep them, but the resources will need to be re-prepared next time); the agent1 label can be kept azure (the tool is harmless and contains no identity).

Lab 8: full cleanup (about 5 minutes of work + waiting)

1. Stop automatic deployment: in Gitea, commit a Jenkinsfile that removes the Push / Deploy / Smoke stages (or temporarily disable the main branch job of the Multibranch project).
2. Delete Jenkins credentials: azure-oidc-token (afterwards, even if someone restores the federated credential, the same issuer cannot issue tokens again),azure-sp-lab.
3. Delete objects outside the resource group and delete the resource group: run the scripts on the “Commands” tab.
4. Verify
az group exists -n rg-jenkins-lab
az identity list --query "[?name=='id-jenkins-deploy']" -o table
az ad app list --display-name sp-jenkins-lab -o table
false
(empty)
(empty)
5. Local files: ~/jenkins3.env contains only non-secret IDs, which you can keep for comparison in Lesson 4; ~/oidc/ holds the public key and discovery document, which can be deleted.

Self-check list (answer without looking at the materials)

Case 1: lab resource group ran for a month

Problem: A learner finished the optional AKS lab and forgot to delete it; the end-of-month bill was nearly $100.

Approach: Set budget alerts uniformly across lab subscriptions; add tags to resource groups expires=2026-11-17, and use a daily scheduled job to delete expired resource groups (Azure Automation / scheduled pipeline).

Case 2: resource group deleted, permissions remain

Problem: A security scan found a service principal named sp-jenkins-* still has subscription-level Reader and an unexpired secret.

Approach: Add “objects outside the resource group” to the cleanup checklist; use Entra's app credential expiry report; after migrating to managed identities, deleting the resource group is enough to remove them along with their federated credentials.

Case 3: storage growth in the production ACR

Approach: Every build pushes a unique tag, so storage keeps growing. Use az acr run --cmd "acr purge --filter 'myapp:.*' --ago 30d --keep 20 --untagged" /dev/null to clean up regularly (ACR Tasks; mind the subscription tier limits), or delete old tags according to a policy in the pipeline.

Interactive troubleshooting tree: Jenkins deployment to Azure fails

Follow the prompts to make selections step by step; it ends with a diagnosis and commands. Covers common issues from Modules 2–7.

Common issues in the cleanup phase

(ScopeLocked) The scope '…/resourceGroups/rg-jenkins-lab' cannot perform delete operation because following scope(s) are locked

Cause: The resource group or a resource in it has a delete lock.

az lock list -g rg-jenkins-lab -o table
az lock delete --name <lock> -g rg-jenkins-lab
The resource group stays in Deleting for a long time

Cause: Deleting AKS and its node resource group, Log Analytics, and load balancers takes time; or a resource depends on external objects (VNet peering, private endpoints).

az group show -n rg-jenkins-lab --query properties.provisioningState
az resource list -g rg-jenkins-lab -o table

Fix: Wait; check the activity log for failed delete operations, delete the stuck resources individually, and retry.

Insufficient privileges to complete the operation. (az ad app delete)

Cause: You are not the owner of the application, and you do not have an application-administrator-type role in Entra.

Fix: Ask the application owner or a tenant administrator to delete it; in the future, use managed identities to avoid creating app registrations.

Command-line tasks
1. Write the command to delete the lab resource group and wait for it to finish.
az group delete -n rg-jenkins-lab --yes --no-wait
until [ "$(az group exists -n rg-jenkins-lab)" = "false" ]; do sleep 30; done
2. Find the deployment identity's role assignments outside the resource group.
az role assignment list --assignee $DEPLOY_PRINCIPAL --all --query "[?!starts_with(scope, '$RG_ID')]" -o table
Scenario analysis
You need to set up a lab environment for this lesson for each of 30 learners. How do you control cost and permission risk?

One resource group per person (rg-jenkins-lab-<user>), tagged owner and expires; each learner is Owner only of their own resource group; subscription budget + per-group budget alerts; prohibit SKUs above a specified size for optional resources such as AKS / App Service (SKUs allowed by Azure Policy); a daily scheduled job deletes expired resource groups; the deployment identity uses a managed identity (deleted with the resource group), and creating app registrations and client secrets is prohibited.

Verified training videos

▶
How to configure Azure budgets and costs alerts — A Cloud Guru
English · Budgets and cost alerts
▶
AZ-900 Episode 37 | Azure Cost Management — Adam Marczak - Azure for Everyone
English · Introduction to cost management

The videos above were verified via YouTube oEmbed (2026-11-16).

Official docs

Video storyboard

Shot 1 · 0:00–0:30
Visual: the bill is broken into a bar chart, with ACR, AKS, and App Service rising in turn.
Narration: the main path of this lesson is almost free; the expensive parts are the optional AKS nodes and App Service plan.
Shot 2 · 0:30–1:10
Visual: the four cleanup steps are checked off one by one, and the app registration outside the resource group is highlighted in red.
Narration: stop automation first, then delete objects outside the resource group, and finally delete the resource group and verify.

This lesson cannot generate a video or MP3 directly, so the storyboard and narration script are provided instead.

or score ≥ 70% on the quiz

Command cheat sheet

Jenkins → Azure: identity, ACR, ACA, AKS, App Service, agents, troubleshooting, cleanup
Wrap-up

1. OIDC sign-in (no long-lived secrets)

withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
  withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
    sh '''
      az login --service-principal -u "$AZURE_CLIENT_ID" \
        -t "$AZURE_TENANT_ID" --federated-token "$OIDC_TOKEN" -o none
      az account set -s "$AZURE_SUBSCRIPTION_ID"
    '''
  }
}

2. Managed identity / workload identity / secret

# Azure VM agent
az login --identity --client-id "$AZURE_CLIENT_ID"
# AKS Pod (workload identity)
az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" \
  --federated-token "$(cat "$AZURE_FEDERATED_TOKEN_FILE")"
# Service principal secret (last resort)
az login --service-principal -u "$AZURE_CLIENT_ID" -p "$AZURE_CLIENT_SECRET" -t "$AZURE_TENANT_ID"

3. Federated credential

az identity federated-credential create -g rg-jenkins-lab \
  --identity-name id-jenkins-deploy -n fic-jenkins-myapp-main \
  --issuer "$ISSUER" \
  --subject "http://localhost:8080/job/myapp-multibranch/job/main/" \
  --audiences api://AzureADTokenExchange
az identity federated-credential list -g rg-jenkins-lab --identity-name id-jenkins-deploy -o yaml

4. ACR push

export DOCKER_CONFIG="$WORKSPACE_TMP/docker"
az acr login -n "$ACR" --expose-token --query accessToken -o tsv \
  | docker login "$ACR.azurecr.io" -u 00000000-0000-0000-0000-000000000000 --password-stdin
docker push "$ACR.azurecr.io/myapp:$TAG"
az acr repository show-tags -n "$ACR" --repository myapp --orderby time_desc --top 5 -o table
az acr show -n "$ACR" --query roleAssignmentMode

5. Container Apps

az containerapp update -g rg-jenkins-lab -n ca-myapp \
  --image "$ACR.azurecr.io/myapp:$TAG" --set-env-vars APP_VERSION="$TAG"
az containerapp show -g rg-jenkins-lab -n ca-myapp \
  --query "[properties.latestRevisionName, properties.latestReadyRevisionName]" -o tsv
az containerapp revision list -g rg-jenkins-lab -n ca-myapp -o table
az containerapp logs show -g rg-jenkins-lab -n ca-myapp --type system --tail 50

6. AKS (Entra + Azure RBAC)

export KUBECONFIG="$WORKSPACE_TMP/kubeconfig"
az aks get-credentials -g rg-jenkins-lab -n aks-jenkins-lab -f "$KUBECONFIG" --overwrite-existing
kubelogin convert-kubeconfig -l azurecli
kubectl -n myapp set image deployment/myapp myapp="$IMAGE:$TAG"
kubectl -n myapp rollout status deployment/myapp --timeout=180s || kubectl -n myapp rollout undo deployment/myapp

7. App Service

az webapp config appsettings set -g rg-jenkins-lab -n $WEBAPP --settings WEBSITES_PORT=5000
az webapp config container set -g rg-jenkins-lab -n $WEBAPP --slot staging \
  --container-image-name "$ACR.azurecr.io/myapp:$TAG" --container-registry-url "https://$ACR.azurecr.io"
az webapp deployment slot swap -g rg-jenkins-lab -n $WEBAPP --slot staging --target-slot production

8. Troubleshooting and cleanup

az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o table
az monitor activity-log list -g rg-jenkins-lab --offset 1h --status Failed -o table
curl -s "$ISSUER/.well-known/openid-configuration" | jq -r .issuer
az group delete -n rg-jenkins-lab --yes --no-wait
az group exists -n rg-jenkins-lab

Quick troubleshooting table

Error / symptomLayerMost likely causeFirst step
AADSTS700213L3sub does not match the federated credential (branch / job / URL / %252F)Decode the token and compare federated-credential list
AADSTS90061L3Entra cannot read the discovery document / JWKScurl $ISSUER/.well-known/openid-configuration
AADSTS700024L3Token expired (waited too long before signing in)Only sign in when needed withCredentials
AADSTS7000222 / 7000215L3Secret expired / invalidaz ad app credential list
AuthorizationFailedL4Missing ARM role / wrong subscription / still propagatingaz role assignment list --all
LinkedAuthorizationFailedL4Missing permissions on linked resources (environment, identity)Add minimum permissions based on the error
ACR unauthorized: authentication requiredL5Missing AcrPush; registry is in ABAC modeaz acr show --query roleAssignmentMode
kubectl Forbidden … in AzureL5Missing namespace-level AKS RBAC rolekubectl auth can-i … -n myapp
Revision not ready / image pull failedL6Wrong tag, pull identity missing AcrPull, port is not 5000az containerapp logs show --type system
Build stuck at device code sign-inL5kubeconfig not converted to azurecli modekubelogin convert-kubeconfig -l azurecli

Recommended configuration snippets

Jenkins
  • OIDC credential placed in the deployment folder, audience api://AzureADTokenExchange
  • Deployment stage: when { branch 'main' } + dedicated agent label
  • AZURE_CONFIG_DIR / DOCKER_CONFIG / KUBECONFIG all point to $WORKSPACE_TMP
  • sh '''…''' single quotes, to avoid interpolating sensitive variables
Azure
  • Keep the deployment identity separate from the runtime pull identity
  • One user-assigned managed identity per app × environment; federated credentials trust only the corresponding job
  • Disable admin on ACR; assign AcrPush or Repository Writer depending on the mode
  • AKS: --disable-local-accounts + namespace-level Azure RBAC

Capstone lab + final quiz

myapp: test → build → ACR → ACA → smoke → automatic rollback on failure → cleanup, with no long-lived secrets throughout
About 45 minutesrg-jenkins-labCost: ACR daily fee + ACA within the free allowance

Scenario

Your team wants to upgrade myapp from “local Jenkins doing CI only” to “automatic deployment to Azure Container Apps from the main branch.” The security team requires: There are no long-lived Azure keys in Jenkins; only myapp-multibranch 's main branch can get an Azure token; the deployment identity and the runtime identity are separate; failures must roll back automatically; after completion, no resources or permissions are left behind.

1. Prepare: following the warm-up page, create a resource group, ACR (--role-assignment-mode rbac), ACA environment and ca-myapp, two managed identities and their roles; install Azure CLI on agent1 and add the label azure.
2. Identity: install the OpenID Connect Provider plugin; host the discovery document on the static website; create the credential azure-oidc-token (audience api://AzureADTokenExchange, fallback issuer); decode a token once to confirm sub; on id-jenkins-deploy , create the federated credential.
3. Complete Jenkinsfile
def azLogin() {
  sh '''
    set -eu
    az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$OIDC_TOKEN" -o none
    az account set -s "$AZURE_SUBSCRIPTION_ID"
  '''
}

pipeline {
  agent { label 'linux && docker && azure' }
  options { disableConcurrentBuilds(); buildDiscarder(logRotator(numToKeepStr: '20')); timeout(time: 30, unit: 'MINUTES') }
  environment {
    AZURE_TENANT_ID       = '<tenantId>'
    AZURE_SUBSCRIPTION_ID = '<subscriptionId>'
    AZURE_CLIENT_ID       = '<id-jenkins-deploy clientId>'
    ACR   = 'acrjenkins12345'
    IMAGE = 'acrjenkins12345.azurecr.io/myapp'
    RG    = 'rg-jenkins-lab'
    APP   = 'ca-myapp'
    FQDN  = 'ca-myapp.<env-suffix>.canadacentral.azurecontainerapps.io'
  }
  stages {
    // stage('Test') { … the test stage from Lesson 2 … }
    stage('Build') {
      steps {
        script { env.TAG = "${env.BUILD_NUMBER}-" + sh(returnStdout: true, script: 'git rev-parse --short=7 HEAD').trim() }
        sh 'docker build --pull -t "$IMAGE:$TAG" --label org.opencontainers.image.revision="$GIT_COMMIT" .'
      }
    }
    stage('Push') {
      when { branch 'main' }
      steps {
        withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
          withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az", "DOCKER_CONFIG=${env.WORKSPACE_TMP}/docker"]) {
            azLogin()
            sh '''
              az acr login -n "$ACR" --expose-token --query accessToken -o tsv \
                | docker login "$ACR.azurecr.io" -u 00000000-0000-0000-0000-000000000000 --password-stdin
              docker push "$IMAGE:$TAG"
            '''
          }
        }
      }
    }
    stage('Deploy') {
      when { branch 'main' }
      steps {
        withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
          withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
            azLogin()
            sh '''
              az containerapp show -g "$RG" -n "$APP" --query "properties.template.containers[0].image" -o tsv > "$WORKSPACE_TMP/prev_image"
              az containerapp update -g "$RG" -n "$APP" --image "$IMAGE:$TAG" --set-env-vars APP_VERSION="$TAG" -o none
              for i in $(seq 1 30); do
                L=$(az containerapp show -g "$RG" -n "$APP" --query properties.latestRevisionName -o tsv)
                R=$(az containerapp show -g "$RG" -n "$APP" --query properties.latestReadyRevisionName -o tsv)
                [ "$L" = "$R" ] && exit 0
                sleep 10
              done
              exit 1
            '''
          }
        }
      }
    }
    stage('Smoke') {
      when { branch 'main' }
      steps {
        sh '''
          for i in 1 2 3 4 5 6; do
            [ "$(curl -fsS --max-time 5 "https://$FQDN/healthz" || true)" = ok ] && exit 0
            sleep 5
          done
          exit 1
        '''
      }
    }
  }
  post {
    failure {
      script {
        if (env.BRANCH_NAME == 'main' && fileExists("${env.WORKSPACE_TMP}/prev_image")) {
          withCredentials([string(credentialsId: 'azure-oidc-token', variable: 'OIDC_TOKEN')]) {
            withEnv(["AZURE_CONFIG_DIR=${env.WORKSPACE_TMP}/az"]) {
              azLogin()
              sh 'P=$(cat "$WORKSPACE_TMP/prev_image"); az containerapp update -g "$RG" -n "$APP" --image "$P" --set-env-vars APP_VERSION="rollback-${P##*:}" -o none'
            }
          }
        }
      }
    }
    cleanup {
      sh 'rm -rf "$WORKSPACE_TMP/az" "$WORKSPACE_TMP/docker" "$WORKSPACE_TMP/prev_image"; docker image rm "$IMAGE:$TAG" 2>/dev/null || true'
    }
  }
}

fileExists accepts absolute paths. Why cleanup is written in cleanup instead of always: Declarative post conditions run in a fixed order: always, changed, fixed, regression, aborted, failure, success, unstable, unsuccessful, cleanup. If it is written in always, it runs before failure deletes prev_image and the Azure login directory, so rollback cannot proceed.

4. Commit and check: fill in your tenant / subscription / clientId / ACR / FQDN, and push to Gitea. Confirm that Push, Deploy, and Smoke run only on main; feature branches run only Build. One acceptance point: Be able to explain the order between failure and cleanup in post.
5. Normal release: change the home page text and push to main. Verify that the new revision is Healthy and curl https://$FQDN/ shows the new APP_VERSION.
6. Failure rollback: change /healthz to return broken, push. Verify that Smoke fails → post failure rollback → live APP_VERSION=rollback-… and /healthz restored ok. Revert the code.
7. Branch isolation: on feature/demo branch, temporarily remove when, push. Verify that the Push stage AADSTS700213— even if the Jenkinsfile is modified, non-main branches still cannot get an Azure token. Delete the branch.
8. Cleanup: complete the four-step cleanup from Module 8 and verify.

Acceptance checklist

Open-ended self-check (6 questions)

1. Why can you say the OIDC Provider plugin has “no long-lived cloud keys”, but not “no secrets at all”?

Jenkins signs tokens with an RSA private key generated by the plugin, and the private key lives on the controller. Anyone with controller admin rights or the ability to read $JENKINS_HOME can issue arbitrary sub tokens. Controller security (Lesson 6) therefore remains the root of trust; the benefit is that no long-lived Azure key can be used outside Jenkins, and the signing key can be rotated at any time (republish the JWKS after Update).

2. How does the risk differ between a managed identity and the OIDC plugin on a “shared agent”?

A managed identity is bound to the VM, so any job running on that VM (even non-Jenkins processes) can get a token from IMDS; an OIDC token is issued only in withCredentials to a specific job, and Entra matches sub exactly. However, an OIDC token can still be impersonated if other processes on the same agent read it during its validity period (for example, from environment variables or process arguments), so you still need to isolate deployment agents and use short lifetimes.

3. If ACR is switched to ABAC mode, where would this lesson's pipeline fail? How do you fix it?

Push stage: the deployment identity's AcrPush and resource group Contributor no longer grant data-plane push permission → unauthorized. ACA pull: id-myapp-pull 's AcrPull becomes invalid → new revision image pull fails (the old revision keeps serving). Fix: first assign Container Registry Repository Writer / Repository Reader (optionally with repository conditions), then switch the mode, then have clients refresh their tokens.

4. Why must rollback after a Smoke failure be in post rather than inside the Smoke stage?

The Deploy stage itself can also fail (for example, the revision is not ready), and in that case the Smoke stage never runs. post { failure } post covers failures in all stages; also watch how always and failure execute, with cleanup placed in cleanup.

5. With local Jenkins and a private AKS cluster, how would you deploy?

See the Module 5 scenario question: place a deployment agent inside the cluster VNet (Pod agent + workload identity, restricted cloud), where the agent must be able to reach the controller over outbound connections; or switch to GitOps, where Jenkins only pushes images and updates the configuration repository. az aks command invoke For troubleshooting only.

6. Microsoft no longer supports the Azure plugin; how do you evaluate whether to keep using Azure VM Agents?

Check plugins.jenkins.io for recent releases (2026-11-03, active), maintainers, unfixed security advisories, compatibility with the current LTS (requires core 2.555.3), and the issue tracker; validate on a test controller; prepare a fallback (Kubernetes plugin or static agents). Do not use deployment plugins marked as deprecated; standardize deployment on Azure CLI.

Sources and version notes

Sources for all versions, plugin statuses, and command syntax in this lesson (verified 2026-11-16)
If they conflict with the official docs, the official docs take precedence

Sources table

TopicVerified findingSource (access date)
Jenkins versionLTS 2.580.2; weekly 2.590updates.jenkins.io/stable/latestCore.txt,latestCore.txt(2026-11-16)
Azure plugin support statusMicrosoft support for the Azure Jenkins plugins ended on 2024-02-29; for retired-plugin scenarios, Azure CLI is recommended; some plugins are community-maintainedJenkins plug-ins for Azure(page updated 2026-01, accessed 2026-11-16)
Azure Credentials plugin426.v5627e6a_4c7a_7 (2026-07-17); types: service principal (secret / certificate), managed identity, basic Key Vault; variables such as AZURE_CLIENT_IDplugins.jenkins.io, GitHub README / releases (2026-11-16)
OpenID Connect Provider plugin234.vca_b_26b_f4b_dda_ (2026-09-18, requires core 2.568.1); two credential types; default sub=JOB_URL, build_number; validity 3600 s; the fallback issuer must host /.well-known/openid-configuration and /jwks; the README includes Azure examplesplugins.jenkins.io,GitHub source Keys.java / IdTokenConfiguration.java(2026-11-16)
Azure VM Agents1124.v89b_2f7a_76f35 (2026-11-03); supports managed identity; required roles by featureplugins.jenkins.io(2026-11-16)
Azure Container Agents372.v073266fff4a_7 (2025-02-26); ACI; for AKS scenarios, use the Kubernetes plugin insteadplugins.jenkins.io(2026-11-16)
Kubernetes plugin4560.vc25b_83890c34 (2026-10-08); “Restrict pipeline support to authorized folders”plugins.jenkins.io, GitHub README (2026-11-16)
Deprecated pluginsazure-acs, azure-app-service, azure-container-registry-tasks are labeled deprecated; last released 2021-02plugins.jenkins.io API (2026-11-16)
Credentials Binding / Docker Pipeline728.v902a_273b_8947 (2026-07-09) / 653.v2f2c08eff0ec (2026-08-13, marked adopt-this-plugin)plugins.jenkins.io (2026-11-16)
az login managed identity syntax--identity + --client-id / --object-id / --resource-idSign in with a managed identity; local Azure CLI 2.84.0 help (2026-11-16)
AKS workload identityPod label azure.workload.identity/use: "true"; SA annotation client-id; each managed identity allows up to 20 federated credentials; the path is read from AZURE_FEDERATED_TOKEN_FILEWorkload ID on AKS(updated 2026-10, accessed 2026-11-16)
ACR authentication--expose-token, all-zeros GUID username, token valid for 3 hours; the admin user is disabled by default and not recommendedACR authentication(updated 2026-06, accessed 2026-11-16)
ACR roles and ABACRBAC mode AcrPush / AcrPull; in ABAC mode, the legacy roles no longer take effect and Repository Writer / Reader apply; rbac-abac will become the default in the future; the CLI currently defaults to rbacRoles overview,ABAC; az acr create -h (2026-11-16)
ACR TasksPausing at the Azure free allowance limitACR Tasks overview(2026-11-16)
Azure CLI container imagemcr.microsoft.com/azure-cli:2.89.1 existsMCR tags list (2026-11-16)
Container Apps free allowanceper subscription per month: 180,000 vCPU-seconds, 360,000 GiB-seconds, 2 million requests (consistent with Lesson 3 of the ADO course in the same repository)Container Apps billing
myapp behaviorport 5000,/healthz returns ok, hits=N/A when there is no Redis, reads APP_VERSIONSame repository Docker courseLessons 1, 3

Video verification notes

All videos were checked via https://www.youtube.com/oembed?url=…&format=json to verify title and channel (2026-11-16): A0w_3DvOf6M, QIg3NIgkARI, rC1TV0_sIrM, WIs3IRCJhEo, i2GobU0Wg48, OL9T6ovxzAE, I9cmk6uiLFs, 0HwQfsa03K8, jfYJEcDOOkI, XFWphg4EYL0, ABbJWP6TToc, 5rR5C4Z5dU4, ZXaorni-icg, 0dbUQYDUXbw, paaFMgWpCjQ, saTUeR_U3lA, CjarTgjKcX8, mQYR7icumaU, 7w88KBVesPI. The oEmbed endpoint does not return durations or publish dates, so they are not listed. No verified videos were found on “Jenkins OIDC Provider plugin with Azure”, “Jenkins deployment to Container Apps”, or “Jenkins cloud troubleshooting”; the corresponding modules provide storyboards instead. Practices shown in community videos (such as the ACR admin user or service principal secrets) do not represent this lesson's recommendations.

Voice notes

The “Voice” tab uses the browser's built-in Web Speech API to read the narration script aloud (zh-CN voice preferred, en-US voice for English terms). This lesson is a single offline file and cannot embed an MP3; if you need audio, pass the narration script to any TTS tool to generate it.

Known limitations

  • All command outputs in this lesson are examples (IDs, FQDNs, digests, and times are fictitious values); they were not run one by one in a real subscription; command syntax has been checked against Azure CLI 2.84.0's -h and the official docs.
  • The UI text, download link location, and jwks fields depend on the version actually installed; using an Azure Storage static website as the fallback issuer is derived from the “fallback issuer” mechanism in the plugin README, so verify in your environment that Entra can read it.
  • The specific role combinations for narrowing the deployment identity “from resource group Contributor” (environment join, Managed Identity Operator, etc.) depend on service behavior; this lesson only gives the method of adding roles based on errors.
  • Costs are order-of-magnitude examples and were not fetched in real time from the pricing API.
  • Lessons 1–2 were written in parallel with this lesson; this lesson is aligned with the completed Lessons 1–2: controller image jenkins/jenkins:2.580.2-jdk21,agent1 (jenkins/inbound-agent + python3 + docker CLI, tagged linux docker), credential gitea-myapp, Jenkins URL http://localhost:8080/, the Multibranch job from Lesson 2 myapp-multibranch (so the OIDC sub is http://localhost:8080/job/myapp-multibranch/job/main/). If your job name is different, replace the federated credential's subject accordingly.
  • The descriptions of behaviors such as ACA single-revision mode “the old revision keeps serving until the new revision is ready” and App Service slot swap warm-up are based on the official docs and have not been stress-tested.