Jenkins Hour 3: Moving to the Cloud (Azure)
~/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- 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 loginto log in, and isolate the Azure CLI and Docker login state to$WORKSPACE_TMP, and useaz acr login --expose-tokento pushmyappimages to ACR, and understand the ACR RBAC mode and ABAC mode, and their impact onAcrPush. - 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, ACRunauthorized/denied, revision image-pull failures, kubelogin interactive-login hangs, and similar issues; in Wrap-up, fully clean uprg-jenkins-lab.
~/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
| # | Time | Module | Core content | Animation / interaction | Lab (rg-jenkins-lab · canadacentral) |
|---|---|---|---|---|---|
| 0 | Prep | Warm-up and Azure setup | Resource group, ACR, ACA environment, two user-assigned managed identities, Azure CLI on agent1, cost and permissions | — | One-click lab resource creation |
| 1 | 00–05 | From CI to CD: deployment architecture on Azure | Where Jenkins runs determines the identity approach; choosing ACA / AKS / App Service; push-based CD vs GitOps | “Where Jenkins runs” identity-approach selector + pipeline stage animation | Record topology and variables |
| 2 | 05–13 | Identity from Jenkins to Azure | Service principal secrets, managed identity (IMDS), AKS workload identity, OIDC Provider plugin + federated credentials; where secrets remain | Core animation: how credentials reach Azure (4 identity types × 5 fault injection types) | OIDC token + federated credentials + az login --federated-token |
| 3 | 13–21 | Build and push to ACR | image tag policy,--expose-token, login state isolation, AcrPush vs ABAC roles, ACR Tasks limits | docker push layered upload and token exchange animation | Jenkinsfile Build + Push stage |
| 4 | 21–29 | Deploy to Azure Container Apps | az containerapp update, revisions, zero-downtime single revision, smoke tests, and rollback | Revision replacement (success / image-pull failure) animation | Deploy + Smoke stage, running end to end |
| 5 | 29–37 | Deploy to AKS and App Service | AKS: Entra + Azure RBAC namespace-level authorization + kubelogin; App Service: custom container,WEBSITES_PORT, deployment slot swap | Rolling update vs slot swap | (Optional) AKS or App Service |
| 6 | 37–45 | Jenkins agents on Azure | Azure VM Agents, Azure Container Agents (ACI), Kubernetes plugin + workload identity; current plugin maintenance status | Comparison of the three agent provisioning processes | Kubernetes pod template + workload identity (optional) |
| 7 | 45–54 | Troubleshooting cloud deployments | AADSTS error codes, RBAC propagation, ACR 401/403, ACA revision failures, kubelogin, IMDS unreachable | Error classifier | Fault injection and fixes |
| 8 | 54–60 | Cost, cleanup, and self-check | Cost breakdown, budget alerts, cleanup order (including federated credentials, Jenkins credentials, static website) | Cost estimator + Interactive troubleshooting tree | Full cleanup |
| — | Wrap-up | Cheat sheet · Capstone lab | myapp: test → build → ACR → ACA → smoke → automatic rollback on failure → cleanup | Final quiz: 12 questions | Capstone lab |
Knowledge Coverage Matrix
| Target skill | Module | Key commands / objects | Lab | Quiz |
|---|---|---|---|---|
| Choose the identity approach by where Jenkins runs | m1 m2 | Decision table: local / Azure VM / AKS / other clouds | ✓ | ✓ |
| Log in to Azure without long-lived keys (OIDC) | m2 | OpenID Connect id token credentials,az identity federated-credential create,az login --federated-token | ✓ | ✓ |
| managed identity and workload identity login | m2 m6 | az login --identity --client-id,$AZURE_FEDERATED_TOKEN_FILE | Optional | ✓ |
| Correct use of service principal secrets and their risks | m2 | withCredentials([azureServicePrincipal(...)]), masking, rotation | Comparative reading | ✓ |
| Build and push image to ACR | m3 | az acr login --expose-token,DOCKER_CONFIG,AZURE_CONFIG_DIR | ✓ | ✓ |
| Deploy to ACA and smoke test / rollback | m4 | az containerapp update,revision list,/healthz | ✓ | ✓ |
| Deploy to AKS (no local accounts) | m5 | --enable-azure-rbac, namespace-level roles,kubelogin convert-kubeconfig -l azurecli | Optional | ✓ |
| Deploy to App Service (container + slots) | m5 | az webapp config container set,WEBSITES_PORT=5000,slot swap | Optional | ✓ |
| Run agents elastically on Azure | m6 | Azure VM Agents, Azure Container Agents, Kubernetes plugin pod template | Optional | ✓ |
| Diagnose identity / permission / image / deployment errors | m7 m8 | AADSTS error codes,az role assignment list,az containerapp logs show | ✓ | ✓ |
| Estimate cost and fully clean up | m8 | az group delete, delete Jenkins credentials and federated credentials, budget | ✓ | ✓ |
Content not covered in this lesson
| Content | Reason | Where to learn |
|---|---|---|
AWS (ECR / ECS / EKS, IAM OIDC,ca-central-1) | Belongs to the next lesson | Lesson 4 |
| Manage credentials and cloud configuration with JCasC, and install Jenkins itself on Kubernetes with Helm | This lesson uses the UI for demos; codified in Lesson 5 | Lesson 5 (configuration as code and Jenkins on Kubernetes) |
| Entra ID single sign-on to Jenkins, permission matrix, folder-level credential governance | Belongs to security governance | Lesson 6 |
| Creating Azure resources with Terraform / Bicep | Belongs to the IaC course | Terraform 8-hour course |
| Helm charts, Argo CD / Flux GitOps | Belongs to the Helm course | Helm 8-hour course |
| AKS networking, node pools, upgrade details | Belongs to the AKS course | AKS 8-hour course |
How to use this courseware
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”.
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser's localStorage (key
jenkins60-part3-progress-v1).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.
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
- Lessons 1–2 completed:
~/jenkinslab/compose.yamlin thejenkins(127.0.0.1:8080),agent1(labellinux docker, can rundocker build),gitea(127.0.0.1:3000, repolab/myapp) are all running; the Multibranch jobmyapp-multibranch'smainbranch's latest build succeeded. - myapp: Flask + gunicorn, listening on 5000,
/healthzreturnsok; reads environment variablesAPP_VERSION; without Redis, the home page showshits=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-labholding 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 --identityof the--client-idparameter needs a newer version; this lesson checked syntax against 2.84)jq,curl.
Connection to the previous lesson
| Lessons 1–2 already have | How 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-creds | gitea-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)
| Resource | Estimated cost (lab, 2–3 hours) | Notes |
|---|---|---|
| ACR Basic | Billed daily, roughly USD 0.17 per day | Billing 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 Analytics | Billed by ingested volume; lab usage is typically < USD 1 | ACA environment is created automatically |
| Storage account (static website, Module 2) | A few KB of data, almost zero cost | Managed OIDC discovery document |
| Managed identities, role assignments, federated credentials | Free | but must be cleaned up to avoid leftover permissions |
| (Optional) AKS, App Service, VM / ACI agents | Billed hourly, significantly more expensive | Modules 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
- 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.
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→azcommand.
How: choose the identity by where Jenkins runs
| Where the Jenkins agent runs | Preferred identity | What “secret” remains | Granularity |
|---|---|---|---|
| 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 internet | By Job URL (sub), can be scoped down to the branch |
| Agent on Azure VM / VMSS | Attached to the VM: user-assigned managed identity,az login --identity --client-id | None | Whole VM: every job on that VM can obtain a token |
| Pod agent on AKS (Kubernetes plugin) | Workload identity: ServiceAccount + federated credential,--federated-token | None (short-lived SA token projected by Kubernetes) | By ServiceAccount / pod template |
| Cannot do any of the above | Service principal + client secret or certificate (Azure Credentials plugin) | Long-lived secret stored in the Jenkins credential store | By Jenkins credential scope (global / folder) |
Deployment target comparison (myapp view)
| Dimension | Azure Container Apps (main track) | AKS | App Service (Web App for Containers) |
|---|---|---|---|
| Pipeline call | ARM: az containerapp update | ARM (to get kubeconfig) + kube-apiserver: kubectl | ARM: az webapp config container set |
| Release unit | Revision (immutable snapshot), single / multiple revision mode | Deployment rolling update | Restart the container; deployment slots + swap (Standard tier and above) |
| Permissions required by the deployment identity | Write permission on the Container App | Cluster User + namespace-level Azure RBAC Writer | Write permission on the Web App |
| Runtime image pull | User-assigned managed identity + AcrPull | kubelet identity (--attach-acr) | Managed identity + acrUseManagedIdentityCreds |
| Scale to zero | Yes | Requires KEDA or similar | No |
| Suitable for | Stateless APIs, when you want containers without managing a cluster | A platform team already exists and needs the Kubernetes API | Traditional 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).
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
Flowchart: Jenkinsfile stages and identity boundaries
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).
Step-by-step animation: one push-based deployment from commit to release
Commands to check the current state
| Command | Purpose | Notes |
|---|---|---|
az containerapp list -g $RG -o table | List Container Apps | Confirm the target exists |
az identity list -g $RG -o table | List managed identities | Deployment identity and pull identity are separate |
az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o table | Roles held by the deployment identity | Review least privilege |
curl -s http://localhost:8080/api/json?tree=url | Jenkins root URL | Determines 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 VM | When 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)
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.
http://localhost:8080/ It appears in the OIDC token's sub claim (Module 2); changing it later will break the federated credential.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.
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 table2. 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}"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
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
- Jenkins plug-ins for Azure (support status table)
- Comparing Container Apps with other Azure container options
- Jenkins Pipeline Syntax
Video storyboard
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.
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.
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.
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.
Module 2 · Identity from Jenkins to Azure: service principals, managed identities, and workload identity
- 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/audfields character for character, and Entra will go to{issuer}/.well-known/openid-configurationfetch 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.
withCredentials, log masking). Importance: ★★★★★What: the four paths
| Path | Jenkins side | Azure side | Runs on the agent | Long-lived secret? |
|---|---|---|---|---|
| ① Service principal + client secret | The “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_ID | App registration + service principal + role assignment | az 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 identity | No Jenkins credential needed (the plugin feature can optionally use an “Azure Managed Identity” credential) | User-assigned managed identity attached to VM / VMSS + role assignment | az login --identity --client-id <clientId> | None |
| ③ AKS workload identity | Kubernetes 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 JWT | Federated credential on the managed identity (or app registration): issuer = Jenkins issuer URL, subject = Job URL | az 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 (
withCredentialshides 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)
- The workload gets a JWT signed by an external issuer (a Kubernetes SA token or a Jenkins OIDC token),
audforapi://AzureADTokenExchange. az login --federated-tokentohttps://login.microsoftonline.com/<tenant>/oauth2/v2.0/tokensend a client_credentials request in which theclient_assertionclient assertion is this JWT.- Entra reads the JWT's
iss, goes to{iss}/.well-known/openid-configurationto fetch thejwks_uri, and downloads the public key to verify the signature. - In
client_idthe corresponding managed identity / app, look for a federated credential with an exact match on issuer + subject + audience. If none is found →AADSTS700213. - 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-configurationand{issuer}/jwks. - Default claims:
sub= Job URL (for examplehttp://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
| Jenkins | Azure DevOps | GitHub Actions | |
|---|---|---|---|
| OIDC token source | Plugin (OpenID Connect Provider) or platform identity | Native to service connections (Entra issuer) | Native (id-token: write) |
| Default meaning of subject | Job URL | Service connection ID | repo:<org>/<repo>:ref:… or environment:… |
| discovery document | Jenkins itself or static files you host | Microsoft-hosted | GitHub-hosted |
| See | this module | ADO Lesson 3 | GitHub Lesson 3 |
Diagram 1: OIDC Provider plugin → Entra → Azure
Diagram 2: where the secret lives in each of the four paths
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).
Identity-related command overview
| Command / step | Purpose | Key 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 create | Create 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_ID | Check issuer / subject | Compare 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 entered | For 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)
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.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.oidc-provider) → Install. After installing, confirm the version is ≥ 234.vca_b_26b_f4b_dda_.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.
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.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.
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.
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/
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.
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.
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.
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
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
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
- OpenID Connect Provider (plugins.jenkins.io)
- Azure Credentials (plugins.jenkins.io)
- Workload identity federation (Microsoft Entra)
- Sign in with a managed identity (Azure CLI)
- Microsoft Entra Workload ID on AKS
Video storyboard
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.
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.
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.
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.
Module 3 · Build and push to ACR
- Design immutable image tags for myapp
<BUILD_NUMBER>-<short commit>, and explain why deployments must not uselatest. - Understand
az acr loginthe two-step token exchange (Entra access token → ACR refresh token → repository-scoped access token), as well as--expose-token+00000000-0000-0000-0000-000000000000how the username is used. - Use
AZURE_CONFIG_DIRandDOCKER_CONFIGto 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 Writeretc.), and know the limitations of ACR Tasks on free-tier subscriptions.
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-a1b2c3dcan be traced back to the build and commit;latesta 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 loginwrites 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. SettingDOCKER_CONFIG=$WORKSPACE_TMP/dockeris 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” | Push | Pull | Notes |
|---|---|---|---|
RBAC Registry Permissions (rbac, current CLI default) | AcrPush | AcrPull | Owner / 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 needs | a Docker daemon (or BuildKit / Kaniko, etc.) | only the Azure CLI; the build context is uploaded to ACR |
| Permissions | AcrPush (or Repository Writer) | Container Registry Tasks Contributor (in ABAC mode, also need --source-acr-auth-id [caller]) |
| Limitation | Security 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 for | existing Docker agents that need caching | Kubernetes pod agents that do not want to mount the Docker socket |
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
Diagram 2: tags and traceability
Animation: token exchange and layer upload for one docker push
Common ACR commands
| Command | Purpose | Notes |
|---|---|---|
az acr login -n $ACR --expose-token --query accessToken -o tsv | Get only the ACR refresh token, without calling Docker | Use 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 table | the 5 most recent tags | Confirm the push succeeded |
az acr manifest list-metadata -r $ACR -n myapp --query "[].{d:digest,t:tags}" | Manifest and digest | Deployments can pin to a digest |
az acr show -n $ACR --query roleAssignmentMode | Check RBAC / ABAC mode | Decide which set of roles to use |
az acr check-health -n $ACR --yes | Check Docker, CLI, DNS, and auth | First step in troubleshooting |
az acr repository delete -n $ACR --image myapp:12-a1b2c3d --yes | Delete an image | Requires 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)
myapp:<build number>-<sha>; no Azure / Docker login state is left on the agent. Cost: ACR storage of a few dozen MB, negligible.~/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
Masking supported pattern matches of $OIDC_TOKEN and digest: sha256:….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
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
feature/x and push it. It only runs Test / Build, with no Push stage shown (when { branch 'main' } skipped).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.
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
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
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
- ACR authentication options (including --expose-token)
- ACR Entra permissions and role assignments
- ABAC repository permissions
- ACR Tasks overview
Video storyboard
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.
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.
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.
Module 4 · Deploy to Azure Container Apps
- Use
az containerapp update --imageto deploy a new version from Jenkins, and understand why it creates a new revision (it changed thetemplate). - 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”.
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
- 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. - ACA creates a new revision, using
id-myapp-pullto pull from ACRmyapp:12-a1b2c3d(requires AcrPull). - Replicas start and probes pass → revision
Running/Healthy. - 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.
- The pipeline polls
latestReadyRevisionName == latestRevisionName, then runscurl https://$FQDN/healthzthe smoke test.
Single-revision vs multiple-revision
| Single-revision (this lesson) | Multiple-revision | |
|---|---|---|
| Traffic switching | Automatic 100% once the new revision is ready | Manual az containerapp ingress traffic set By weight |
| Rollback | Redeploy the previous image (creates a new revision) | Shift the weight back to the old revision (seconds, no rebuild) |
| Suitable for | dev / small teams | prod canary and blue-green |
When: when stronger gating is needed
- Production: add
inputstage (specifyingsubmitter), or put production deployment in a protected folder so only specific people can trigger it (Lesson 6). Noteinputdo not tie up an agent while waiting (by waiting in theagent nonestage). - 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).
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
Diagram 2: deploy + smoke test + rollback in the pipeline
Animation: revision replacement (success / image pull failure / app crashes on startup)
Container Apps deployment commands
| Command | Purpose | Key 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 ready | Ready when the two values are equal |
az containerapp revision list -g $RG -n $APP -o table | List revisions | Check active / trafficWeight / healthState |
az containerapp logs show -g $RG -n $APP --type system --tail 50 | System logs (image pulls, probes) | --type console View app output |
az containerapp revision restart -g $RG -n $APP --revision <name> | Restart a revision | does not change the image |
az containerapp ingress traffic set -g $RG -n $APP --revision-weight <rev>=100 | Switch traffic in multiple-revision mode | requires 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)
fqdn fill in ~/jenkins3.env in the $FQDN. Commit and push.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)
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.
--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.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.
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 tableReady 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
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
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
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.
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.
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.
Module 5 · Deploy to AKS and App Service
- AKS: use
--enable-aad --enable-azure-rbac --disable-local-accountsa cluster where the Jenkins deployment identity has write permission only in namespacemyapp; understandkubelogin convert-kubeconfig -l azurecliwhy it lets kubectl reuseaz loginthe identity. - Use
kubectl set image+rollout status+rollout undoto implement deployment and rollback. - App Service: custom containers,
WEBSITES_PORT=5000, managed identity pulling from ACR, health check paths, and deployment slots and swaps.
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 (
--adminkubeconfig) 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
| Mode | When to use | Token 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 workloadidentity | Jenkins pod agent on AKS using workload identity | $AZURE_FEDERATED_TOKEN_FILE |
-l msi | agent on an Azure VM | IMDS |
-l devicecode (default, interactive) | Only suitable for humans | browser 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
stagingslot → 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).
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
Diagram 2: App Service deployment slot swap
Animation: AKS rolling update vs App Service slot swap
AKS commands
| Command | Purpose | Notes |
|---|---|---|
az aks get-credentials -g $RG -n $AKS -f "$KUBECONFIG" --overwrite-existing | Get user-level kubeconfig | Do not use --admin |
kubelogin convert-kubeconfig -l azurecli | ; instead switch the exec plugin to reuse the az login | Applies to $KUBECONFIG |
kubectl auth can-i patch deployments -n myapp | Verify authorization | Expected yes; in the default namespace, expect no |
kubectl -n myapp set image deployment/myapp myapp=$IMAGE:$TAG | Update image | the container name must match |
kubectl -n myapp rollout status deployment/myapp --timeout=180s | Wait for rollout to complete | returns non-zero on timeout |
kubectl -n myapp rollout undo deployment/myapp | Roll back to the previous ReplicaSet | or --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-reachable | Good 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)
--attach-acr to create role assignments). Delete the cluster when done.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
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
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
curl http://<EXTERNAL-IP>/healthz.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)
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
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.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>"}'.
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
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
The videos above were verified via YouTube oEmbed (2026-11-16).
Official docs
- Use Azure RBAC for Kubernetes authorization
- kubelogin docs
- Configure a custom container for App Service
- Set up staging environments (deployment slots)
Video storyboard
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.
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.
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.
Module 6 · Jenkins agents on Azure: VMs, ACI, and AKS
- 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.
What: three cloud agent plugins (plugins.jenkins.io, 2026-11-16)
| Plugin | Latest version / release | Maintenance status | How agents are created | Authentication to Azure |
|---|---|---|---|---|
Azure VM Agents (azure-vm-agents) | 1124.v89b_2f7a_76f35 · 2026-11-03 | Community-maintained, active; Microsoft support ended on 2024-02-29 | Creates VMs from ARM templates; starts via SSH or inbound; retention strategies: Idle / Pool / Once | Azure Credentials: service principal, or a managed identity when the controller is on Azure |
Azure Container Agents (azure-container-agents) | 372.v073266fff4a_7 · 2025-02-26 | Community-maintained, few updates; Microsoft support has ended | ACI container group, default image jenkins/inbound-agent, billed per second | Same as above (service principal or managed identity) |
Kubernetes (kubernetes) | 4560.vc25b_83890c34 · 2026-10-08 | Very active; one of the core Jenkins community plugins | One 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 plugins | No releases since 2021 | deprecated | Do 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 method | Direction | when the controller is on-premises and the agent is on Azure |
|---|---|---|
| SSH (recommended for VM Agents) | controller → agent:22 | Requires VPN / ExpressRoute, or a public IP on the VM + NSG restricting source IPs |
| Inbound TCP (JNLP, port 50000) | agent → controller | the controller's agent port must be reachable from Azure |
| Inbound WebSocket | agent → 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.
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
Diagram 2: pod agent with workload identity
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.
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)
| Setting | VM Agents | Container Agents (ACI) |
|---|---|---|
| Location | Manage Jenkins → Clouds → New cloud → Azure VM Agents | … → Azure Container Instance |
| Credentials | Azure 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 |
| Image | Built-in Ubuntu / Windows or a custom image (Compute Gallery requires Reader) | Default jenkins/inbound-agent, private registries need a credential |
| Retention | Idle (minutes) / Pool / Once | Retention policy (delete after use by default) |
| Network | Optional 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)
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.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.
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).
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 tableThe 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
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
- Azure VM Agents
- Azure Container Agents
- Kubernetes plugin
- Scale with Azure VM agents (Microsoft Learn, older)
Video storyboard
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.
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.
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.
Module 7 · Troubleshooting cloud deployments in practice
- 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.
What: the six-layer model
| Layer | Typical symptom / error | First diagnostic command |
|---|---|---|
| L1 Jenkins credential | Could not find credentials entry with ID 'azure-oidc-token'; credential type mismatch; az: not found | Jenkins credentials page scope (global / folder); echo $NODE_NAME |
| L2 token contents | Token sub / iss / aud does not match expectations | Decode the payload (Module 2 lab, step 5) |
| L3 Entra exchange | AADSTS700213,AADSTS90061,AADSTS700024,AADSTS7000215 (invalid key),AADSTS7000222 (expired key) | az identity federated-credential list; az ad app credential list |
| L4 ARM authorization | AuthorizationFailed,LinkedAuthorizationFailed,No subscriptions found | az role assignment list --assignee <principalId> --all |
| L5 data plane | ACR unauthorized: authentication required; kubectl Forbidden … does not have access to the resource in Azure | az acr show --query roleAssignmentMode; kubectl auth can-i |
| L6 runtime | Revision Failed / Unhealthy, ImagePullBackOff, App Service port probe failure | az containerapp logs show --type system; kubectl describe pod |
Why: layer first, then act
- Many people see “deployment failed” and immediately change roles, but
AADSTS700213the 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 IDandCorrelation 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 loginagain.
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.).
Diagram: six-layer locating map
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.
Troubleshooting command box
| Layer | Command | What to look for |
|---|---|---|
| L2 | Decode the JWT payload (Module 2 lab, step 5) | iss trailing slash,sub in %252F,exp |
| L3 | az identity federated-credential list -g $RG --identity-name $DEPLOY_ID -o yaml | and compare verbatim with the JWT |
| L3 | curl -s $ISSUER/.well-known/openid-configuration | jq -r .issuer,.jwks_uri | publicly reachable, issuer matches |
| L4 | az role assignment list --assignee $DEPLOY_PRINCIPAL --all -o table | Roles and scope |
| L4 | az monitor activity-log list -g $RG --offset 1h --status Failed --query "[].{op:operationName.value, who:caller, status:status.value}" -o table | Denied write operations and caller |
| L5 | az acr check-health -n $ACR --yes; az acr show -n $ACR --query roleAssignmentMode | DNS / authentication / mode |
| L5 | kubectl auth can-i --list -n myapp | Permissions of the current identity in the namespace |
| L6 | az containerapp logs show -g $RG -n $APP --type system --tail 50 | Image pulls, probes, crashes |
| L6 | az containerapp revision list -g $RG -n $APP -o table | Which 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)
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.
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.
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.
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/.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.
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 table2. 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
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
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
- Microsoft Entra authentication and authorization error codes
- Troubleshoot Azure RBAC
- Troubleshoot registry login
- Troubleshoot Container Apps
Video storyboard
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.
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.
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.
Module 8 · Cost, cleanup, and self-check
- 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.
What: cost breakdown (example magnitudes; the pricing calculator is authoritative)
| Resource | Billing model | Magnitude in this lesson | Cost-saving tips |
|---|---|---|---|
| ACR Basic | Daily fixed fee + excess storage | About $0.17 / day | Delete 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 allowance | Usually 0 | --min-replicas 0 |
| Log Analytics | Per GB ingested | < $1 | Few 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 IPs | About $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 / S1 | B1 is about $0.02 / hour, S1 is higher | Deployment slots require S1; delete the plan after the lab |
| VM / ACI agent (optional) | VMs billed per second + disk + IP; ACI billed per vCPU / GB-second | Depends on the retention policy | Idle retention + agent resource group budget |
| Managed identities, role assignments, federated credentials | Free | 0 | but 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 stopStopping ends control plane and node billing (disks and other resources are still billed); suitable if you will continue the next day. - ACA:
--min-replicas 0Scaling 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.
Diagram: cleanup order
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
| Command | Purpose |
|---|---|
az ad app list --display-name sp-jenkins-lab --query "[].appId" -o tsv | Find 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 table | Confirm no leftover roles outside the resource group |
az group delete -n rg-jenkins-lab --yes --no-wait | Delete all lab resources |
az group exists -n rg-jenkins-lab | Returns false when done. |
az group list --query "[?starts_with(name,'MC_rg-jenkins-lab')].name" -o tsv | Whether 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)
azure-oidc-token (afterwards, even if someone restores the federated credential, the same issuer cannot issue tokens again),azure-sp-lab.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)
~/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.
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
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
The videos above were verified via YouTube oEmbed (2026-11-16).
Official docs
- Azure pricing calculator
- Create and manage budgets
- Container Apps billing
- Delete resource group and resources
Video storyboard
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.
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.
Command cheat sheet
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 / symptom | Layer | Most likely cause | First step |
|---|---|---|---|
AADSTS700213 | L3 | sub does not match the federated credential (branch / job / URL / %252F) | Decode the token and compare federated-credential list |
AADSTS90061 | L3 | Entra cannot read the discovery document / JWKS | curl $ISSUER/.well-known/openid-configuration |
AADSTS700024 | L3 | Token expired (waited too long before signing in) | Only sign in when needed withCredentials |
AADSTS7000222 / 7000215 | L3 | Secret expired / invalid | az ad app credential list |
AuthorizationFailed | L4 | Missing ARM role / wrong subscription / still propagating | az role assignment list --all |
LinkedAuthorizationFailed | L4 | Missing permissions on linked resources (environment, identity) | Add minimum permissions based on the error |
ACR unauthorized: authentication required | L5 | Missing AcrPush; registry is in ABAC mode | az acr show --query roleAssignmentMode |
kubectl Forbidden … in Azure | L5 | Missing namespace-level AKS RBAC role | kubectl auth can-i … -n myapp |
| Revision not ready / image pull failed | L6 | Wrong tag, pull identity missing AcrPull, port is not 5000 | az containerapp logs show --type system |
| Build stuck at device code sign-in | L5 | kubeconfig not converted to azurecli mode | kubelogin convert-kubeconfig -l azurecli |
Recommended configuration snippets
- OIDC credential placed in the deployment folder, audience
api://AzureADTokenExchange - Deployment stage:
when { branch 'main' }+ dedicated agent label AZURE_CONFIG_DIR/DOCKER_CONFIG/KUBECONFIGall point to$WORKSPACE_TMPsh '''…'''single quotes, to avoid interpolating sensitive variables
- 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
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.
--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.azure-oidc-token (audience api://AzureADTokenExchange, fallback issuer); decode a token once to confirm sub; on id-jenkins-deploy , create the federated credential.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.
curl https://$FQDN/ shows the new APP_VERSION./healthz to return broken, push. Verify that Smoke fails → post failure rollback → live APP_VERSION=rollback-… and /healthz restored ok. Revert the code.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.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 table
| Topic | Verified finding | Source (access date) |
|---|---|---|
| Jenkins version | LTS 2.580.2; weekly 2.590 | updates.jenkins.io/stable/latestCore.txt,latestCore.txt(2026-11-16) |
| Azure plugin support status | Microsoft support for the Azure Jenkins plugins ended on 2024-02-29; for retired-plugin scenarios, Azure CLI is recommended; some plugins are community-maintained | Jenkins plug-ins for Azure(page updated 2026-01, accessed 2026-11-16) |
| Azure Credentials plugin | 426.v5627e6a_4c7a_7 (2026-07-17); types: service principal (secret / certificate), managed identity, basic Key Vault; variables such as AZURE_CLIENT_ID | plugins.jenkins.io, GitHub README / releases (2026-11-16) |
| OpenID Connect Provider plugin | 234.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 examples | plugins.jenkins.io,GitHub source Keys.java / IdTokenConfiguration.java(2026-11-16) |
| Azure VM Agents | 1124.v89b_2f7a_76f35 (2026-11-03); supports managed identity; required roles by feature | plugins.jenkins.io(2026-11-16) |
| Azure Container Agents | 372.v073266fff4a_7 (2025-02-26); ACI; for AKS scenarios, use the Kubernetes plugin instead | plugins.jenkins.io(2026-11-16) |
| Kubernetes plugin | 4560.vc25b_83890c34 (2026-10-08); “Restrict pipeline support to authorized folders” | plugins.jenkins.io, GitHub README (2026-11-16) |
| Deprecated plugins | azure-acs, azure-app-service, azure-container-registry-tasks are labeled deprecated; last released 2021-02 | plugins.jenkins.io API (2026-11-16) |
| Credentials Binding / Docker Pipeline | 728.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-id | Sign in with a managed identity; local Azure CLI 2.84.0 help (2026-11-16) |
| AKS workload identity | Pod 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_FILE | Workload 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 recommended | ACR authentication(updated 2026-06, accessed 2026-11-16) |
| ACR roles and ABAC | RBAC 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 rbac | Roles overview,ABAC; az acr create -h (2026-11-16) |
| ACR Tasks | Pausing at the Azure free allowance limit | ACR Tasks overview(2026-11-16) |
| Azure CLI container image | mcr.microsoft.com/azure-cli:2.89.1 exists | MCR tags list (2026-11-16) |
| Container Apps free allowance | per 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 behavior | port 5000,/healthz returns ok, hits=N/A when there is no Redis, reads APP_VERSION | Same 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
-hand the official docs. - The UI text, download link location, and
jwksfields 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, taggedlinux docker), credentialgitea-myapp, Jenkins URLhttp://localhost:8080/, the Multibranch job from Lesson 2myapp-multibranch(so the OIDCsubishttp://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.