GitLab Hour 3: Moving to the Cloud Platform (Azure)
id_tokens Keyless OIDC, Entra federated credentials, environments and protected environment approvals, ACR / GitLab Container Registry, Container Apps canary releases, AKS (GitLab agent) and App Service, troubleshooting and cleanup on the cloud- Choose the right Azure deployment target for myapp (Container Apps / AKS / App Service), and clearly explain the differences among GitLab's push-based (CI jobs calling cloud APIs),agent CI/CD workflow (jobs reaching the cluster through a KAS tunnel) and GitOps (Flux).
- Master the GitLab
id_tokens→ Microsoft Entra workload identity federation →az login --federated-tokencomplete token exchange; configure GitLab'ssub:project_path:{group}/{project}:ref_type:{type}:ref:{ref}; know that regular federated credentials do not support wildcards, and how flexible federated credentials (preview) thatclaimsMatchingExpressionmatchv*tags. - Understand GitLab's default
subdoes not include the environment name (unlike GitHub), so you can weigh branch-level / tag-level / custom sub component three trust scopes, and use protected branches, protected tags, protected environments to close the gap of “who can get the token”. - Use environments / deployments /
resource_groupto track and serialize deployments; use protected environments + deployment approval (Premium) to build release gates, and give Free-tier alternatives (when: manual+ protected tags). - “Build once, deploy many”: push the image first to the GitLab Container Registry, then use
az acr importto promote to ACR; Container Apps uses a managed identity to pull from ACR; prod uses a 0%-traffic staging revision → smoke test → shift traffic → roll back in seconds. - Be able to locate within 10 minutes AADSTS70021 / 700212 / 700213 / 7002138 / 501661,
AuthorizationFailed,ID token issuance is disabled, ACR pull 401, deployment blocked, agent context not found and other failures, and finish cost control and full cleanup.
1-hour time allocation table
| # | Time | Module | Core content | Animation / interaction | Lab (mygroup-lab/myapp + rg-gitlab-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and Azure setup | Subscription and permissions, resource providers ~/gitlab-lab.env, ACR + Container Apps environment + two apps (dev/prod), project ID | Readiness self-assessment | Azure base resources ready |
| 1 | 00–05 | From CI to CD: choosing a deployment architecture | ACA / AKS / App Service comparison; push-based vs agent CI/CD workflow vs GitOps; build once, deploy many; identity layering | Deployment target selector | Write the myapp deployment design and walk through one merge request |
| 2 | 05–13 | OIDC federated identity: GitLab → Entra ID | id_tokens and claims,sub format and custom components, FIC triple, no wildcards, flexible federated credentials (preview), UAMI vs app registration,az login --federated-token | OIDC token exchange animation (7 scenarios) + sub / wildcard calculator | 3 managed identities + federated credentials + first keyless sign-in |
| 3 | 13–21 | Environments, deployments and protected environment approvals | environment keywords, deployment records,resource_group, expired deployment protection, protected environments and approvals (Premium), environment-scoped variables | Deployment gate simulator | dev / prod environments, protected tags, approval rules (Premium) |
| 4 | 21–29 | Build and push to ACR (or the GitLab Container Registry) | DinD builds,CI_REGISTRY* and CI_JOB_TOKEN,az acr import promotion, ACR roles (including ABAC mode), comparison of three options | Image flow animation | build → GitLab registry → ACR |
| 5 | 29–37 | Deploy to Azure Container Apps | az containerapp update, revision modes, 0% staging, smoke tests, traffic shifting and rollback, dotenv write-back of environment URLs | Revision and traffic-shifting animation | dev automatic, prod tag + manual/approval + canary |
| 6 | 37–45 | AKS (GitLab agent) and App Service | agentk ↔ KAS,ci_access context path:agent,environment:kubernetes:agent impersonation (Premium), App Service deployment slots | agent tunnel animation | (optional) AKS + agent; App Service snippet |
| 7 | 45–54 | Troubleshooting deployments on the cloud | AADSTS family, RBAC, ACR 401/MANIFEST_UNKNOWN, blocked deployments, expired jobs, agent errors | error message decoder | Deliberately create 3 faults and fix them |
| 8 | 54–60 | Cost, cleanup and self-check | Cost structure, idle costs, cleanup order (cloud resources → FIC/identities → roles → GitLab variables/environments/agent) | Cost estimator + interactive troubleshooting tree | Cleanup script + verification |
| — | After class | Cheat sheet · Comprehensive lab | MR → main → build → import → dev → tag v1.1 → prod approval → canary → rollback → cleanup | Final quiz (12 questions) | Comprehensive lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / configuration | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Deployment target selection and pipeline layering | ✓ | · | · | ✓ | ✓ | ✓ | · | ✓ | Selection table, stages | M1 design document |
id_tokens and GitLab ID token claims | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | · | id_tokens: GITLAB_OIDC_TOKEN: aud: | M2 step 4 |
| Federated credential subject design (branch / tag / custom component / flexible FIC) | · | ✓ | ✓ | · | · | · | ✓ | ✓ | az identity federated-credential create,az rest … claimsMatchingExpression | M2 lab |
| Least-privilege RBAC (pipeline identity vs runtime identity) | ✓ | ✓ | · | ✓ | ✓ | ✓ | ✓ | · | az role assignment create --scope | Import / deploy / AcrPull separation |
| environments, deployment records, resource_group | · | · | ✓ | · | ✓ | ✓ | ✓ | · | environment:,resource_group: | dev / prod |
| protected environments and deployment approval (Premium) | · | · | ✓ | · | ✓ | · | ✓ | · | POST /protected_environments,/deployments/:id/approval | M3 step 4 |
| image registry (GitLab Registry / ACR) | · | · | · | ✓ | ✓ | ✓ | ✓ | ✓ | $CI_REGISTRY_IMAGE,az acr import | M4 lab |
| Container Apps revisions, traffic, rollback | · | · | · | · | ✓ | · | ✓ | · | az containerapp ingress traffic set | prod canary |
| AKS + GitLab agent (CI/CD workflow) / App Service | ✓ | · | · | · | · | ✓ | ✓ | ✓ | ci_access,kubectl config use-context,slot swap | M6 (optional) |
| Diagnosing deployment faults on the cloud | · | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | job logs az role assignment list, token claim decoding | M7 fault injection |
| Cost control and cleanup | · | · | · | · | · | · | · | ✓ | az group delete,glab variable delete | cleanup script |
Topics excluded from this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
.gitlab-ci.yml syntax rules / needs / include, Runner registration and executor, caching and artifacts | Covered in the previous lesson; used directly in this one | Hour 2: GitLab CI/CD core |
| Repository-side basics such as protected branches, push rules and approval rules | Covered in the Git lesson; here we only refer to it from the angle of “who can trigger deployments and who can get tokens” | Git lesson 4 |
GitHub Actions OIDC (azure/login, immutable subject) and environments | Not repeated; modules 2/3 only compare | GitHub lesson 3 |
| Azure Pipelines service connections (workload identity federation) and Environments checks | Not repeated; compared only | Azure DevOps lesson 3 |
| Writing the Dockerfile and slimming the image, myapp source code | belongs to the Docker lesson | Docker 8-hour course |
| AKS cluster design, networking, upgrades, Flux/Argo CD operations | belongs to the AKS / Kubernetes lesson; this lesson only covers how to deploy from the GitLab side | AKS 8-hour course · Kubernetes 8 + 1-hour course |
| AWS (IAM OIDC provider, ECR, ECS/EKS) | next lesson | Hour 4: Moving to the Cloud Platform (AWS) |
| Terraform/Bicep pipelines, JWT authentication for HashiCorp Vault | belongs to infrastructure as code / secrets management | Terraform 8-hour course |
How to use this courseware
Theory · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · voice · video. We suggest reading “Theory” and “Animation” first, then doing the “Labs”. All labs accumulate in the same GitLab project
mygroup-lab/myapp and resource group rg-gitlab-lab , building up step by step.A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (if the browser has local storage disabled, it is cleared on refresh).
The “Voice” tab reads the narration script aloud with the browser's built-in Web Speech API (en-US); English terms are pronounced with en-US. Without a Chinese voice pack, the narration script stays readable.
lab-docker). Azure permissions: on the resource group Owner (or Contributor + Role Based Access Control Administrator), needed to create role assignments.id_tokens Available on Free / Premium / Ultimate,CI_JOB_JWT_V2 removed in 17.0; sub can be set in project settings ci_id_token_sub_claim_components customized, from 18.7 can add ref_protected,environment_protected,deployment_tier and other fields. Protected environments and deployment approvals: Premium / Ultimate; the CI/CD workflow of GitLab agent for Kubernetes: Free (impersonation requires Premium). Azure: Azure CLI image mcr.microsoft.com/azure-cli:2.93.0; federated credentials are limited to 20 per identity and do not support wildcards; flexible federated credentials are still in preview, which supports GitLab-issued tokens and can be configured on app registrations and user-assigned managed identities. Docker image docker:29.10 / docker:29.10-dind.Module 0 · Warm-up and Azure setup (complete before class)
- CompletedHour 2: the GitLab.com
mygroup-lab/myappproject (Python Flask + gunicorn + Redis, port 5000,/healthz, pytest tests and Dockerfile),.gitlab-ci.ymlintestjobs run successfully on merge requests and main; the default branchmainis a protected branch. - Installed locally:
glab(alreadyglab auth login),jq, Azure CLI 2.9x (az version); Docker Engine 29 only for local image verification (optional). - An Azure subscription that can create resources and role assignments; a personal trial subscription is fine.
- (Optional) GitLab Premium / Ultimate: for the protected environments and deployment approvals in module 3. You can complete this lesson without it, since every step gives a Free-tier alternative; you can also apply for a trial on GitLab.com for a top-level group.
Connection with the previous lesson
| Previous lesson output | Use in this lesson |
|---|---|
stages + test job | stays unchanged; new build / promote / deploy / verify stages |
rules and workflow:rules | main branch → build and dev deployment; v* tags → prod deployment; MR runs tests only |
GitLab Container Registry registry.gitlab.com/mygroup-lab/myapp | Build once, tag with the commit SHA, as the source for promotion to ACR |
Self-hosted runner gitlab-runner (tag lab-docker) | Optional: use it to run DinD builds (needs privileged = true), saving managed runner compute minutes |
glab Signed in | Set CI/CD variables, protected tags, query deployments and approvals |
Step 1: sign in to Azure and check permissions
az login # or az login --use-device-code
az account show --query "{name:name, id:id, tenant:tenantId, user:user.name}" -o table
az account set --subscription "<subscription name or ID>" # when you have multiple subscriptions
az role assignment list --assignee "$(az ad signed-in-user show --query id -o tsv)" \
--scope "/subscriptions/$(az account show --query id -o tsv)" --query "[].roleDefinitionName" -o tsv
Name Id Tenant User ------------- ------------------------------------ ------------------------------------ ------------------ Pay-As-You-Go 11111111-2222-3333-4444-555555555555 aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee you@example.com Owner
az role assignment create will fail (Contributor does not include Microsoft.Authorization/roleAssignments/write). Ask your administrator to grant Role Based Access Control Administrator (optionally with a condition, to allow assigning only specified roles), or grant Owner at the resource group level.Step 2: register resource providers, write the environment variable file
az provider register -n Microsoft.App --wait az provider register -n Microsoft.OperationalInsights --wait az provider register -n Microsoft.ContainerRegistry --wait az provider register -n Microsoft.ManagedIdentity --wait az extension add --name containerapp --upgrade --only-show-errors GL_PROJECT=mygroup-lab/myapp # change to your <username>-lab/myapp GL_ENC=$(printf %s "$GL_PROJECT" | jq -sRr @uri) # URL encoding: mygroup-lab%2Fmyapp cat > ~/gitlab-lab.env <<EOF RG=rg-gitlab-lab LOC=canadacentral ACR=acrgitlab$RANDOM # globally unique, 5–50 lowercase letters and digits CAE=cae-gitlab-lab APP_DEV=myapp-dev APP_PROD=myapp-prod PORT=5000 GL_PROJECT=$GL_PROJECT GL_ENC=$GL_ENC GL_PROJECT_ID=$(glab api "projects/$GL_ENC" | jq -r .id) SUB_ID=$(az account show --query id -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv) EOF source ~/gitlab-lab.env && cat ~/gitlab-lab.env
RG=rg-gitlab-lab LOC=canadacentral ACR=acrgitlab21873 CAE=cae-gitlab-lab APP_DEV=myapp-dev APP_PROD=myapp-prod PORT=5000 GL_PROJECT=mygroup-lab/myapp GL_ENC=mygroup-lab%2Fmyapp GL_PROJECT_ID=71234567 SUB_ID=11111111-2222-3333-4444-555555555555 TENANT_ID=aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
Note:$RANDOM and $(…) are expanded when the file is written, so the ACR name and project ID are fixed; in each new terminal, first run source ~/gitlab-lab.env. Project ID (number) used in module 2 for flexible federated credentials and custom sub— it stays the same when the project is renamed or transferred.
Step 3: create the resource group, ACR and Container Apps environment
source ~/gitlab-lab.env
az group create -n $RG -l $LOC --tags course=gitlab-8h part=3 -o none
az acr create -g $RG -n $ACR --sku Basic --admin-enabled false -o none
az containerapp env create -g $RG -n $CAE -l $LOC -o none # creates a Log Analytics workspace by default
az containerapp env show -g $RG -n $CAE --query "{state:properties.provisioningState, domain:properties.defaultDomain}" -o table
State Domain --------- ------------------------------------------ Succeeded happyrock-5c6d7e8f.canadacentral.azurecontainerapps.io
Step 4: create the dev / prod apps (first with a public sample image as a placeholder)
source ~/gitlab-lab.env
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
for APP in $APP_DEV $APP_PROD; do
az containerapp create -g $RG -n $APP --environment $CAE \
--image mcr.microsoft.com/k8se/quickstart:latest --target-port 80 --ingress external \
--min-replicas 0 --max-replicas 2 --system-assigned -o none
# Runtime identity: the app's own system-assigned identity, granted only AcrPull, used to pull images from ACR
PID=$(az containerapp show -g $RG -n $APP --query identity.principalId -o tsv)
az role assignment create --assignee-object-id $PID --assignee-principal-type ServicePrincipal \
--role AcrPull --scope $ACR_ID -o none
az containerapp registry set -g $RG -n $APP --server $ACR.azurecr.io --identity system -o none
done
az containerapp revision set-mode -g $RG -n $APP_PROD --mode multiple -o none # prod: multiple revisions, for canary releases
az containerapp list -g $RG --query "[].{name:name, fqdn:properties.configuration.ingress.fqdn, mode:properties.configuration.activeRevisionsMode}" -o table
Name Fqdn Mode ---------- -------------------------------------------------------------------- -------- myapp-dev myapp-dev.happyrock-5c6d7e8f.canadacentral.azurecontainerapps.io Single myapp-prod myapp-prod.happyrock-5c6d7e8f.canadacentral.azurecontainerapps.io Multiple
mcr.microsoft.com/k8se/quickstart (port 80) to set up the app, ingress and runtime identity; the first pipeline deployment in module 5 will swap the image to myapp and change the port to 5000. New role assignments can take a few minutes to take effect, so grant AcrPull in advance. If your ACR is in “RBAC Registry + ABAC Repository Permissions” mode, the pull role should be Container Registry Repository Reader (see module 4).Warm-up: answer from memory (30 seconds)
What is the difference between the CI_JOB_TOKEN and the id_tokens ?
CI_JOB_TOKEN is the token GitLab issues to jobs for accessing GitLab itself (API, Container Registry, package registry, other projects) tokens; the id_tokens id_tokens keyword defines the tokens GitLab issues as an OIDC identity provider JWT, used to external services (Azure, AWS, Vault) prove “I am a job on a particular project branch/tag”, and the external service exchanges this for its own short-lived credentials.
A CI/CD variable is set to “protected”: which pipelines can read it?
Only pipelines running on a protected branch or protected tag pipelines. This lesson uses the same idea: prod deployments only trigger from protected v* tags. Note: id_tokens ID tokens are not governed by the “protected variables” mechanism —any branch that can run jobs can request an ID token; trust scope relies on the cloud federated credential's sub to limit it.
Readiness self-assessment (8 items)
Tick what you can currently do items (saved in this browser). Come back and tick again after completing this lesson and the comprehensive lab.
Module 1 · From CI to CD: deployment architecture selection
- Explain the difference between continuous delivery and continuous deployment, and the standard form of “build once, promote across environments” on GitLab (stages + environments + deployment records).
- Based on team skills and application type, make reasoned choices among Container Apps, AKS and App Service.
- Compare GitLab's three deployment models: push-based (jobs call cloud APIs),agent CI/CD workflow (jobs call the cluster API through a KAS tunnel),GitOps (Flux pulls from inside the cluster).
rules artifacts and container registries. Importance:★★★★☆ (choosing the wrong architecture means patching holes at every later step)What: what CI to CD adds
CI output is “a tested commit”; CD output is “an artifact running in some environment, traceable to a commit”. On GitLab, CD consists of four things:
- Artifacts: container images (GitLab Container Registry / ACR), tagged with the commit SHA (
$CI_COMMIT_SHORT_SHA), ideally traced by digest —immutable and traceable. - Identity: how a job proves “I am authorized to deploy”. This lesson uses all of
id_tokens+ Entra workload identity federation,no cloud passwords stored in the project (module 2). - Environments and deployment records: jobs that declare an
environment:will create records in Operate → Environments deployment records, which let you review “which commit is in which environment”, and redeploy or roll back (module 3). - Gates: protected branches / tags (who can trigger), protected environments and deployment approvals (who can deploy and who approves, Premium),
resource_group(only one deployment at a time), post-deployment smoke tests and rollback.
Continuous delivery: every commit that passes CI can be deployed to production, but a human makes the decision; Continuous deployment: goes live automatically once all automated checks pass. In this lesson, for myapp: dev is continuous deployment (deploys when merged to main), prod is continuous delivery (tagging v* + manual/approval).
Why: why choose the architecture first
The deployment target determines what the last mile of the pipeline looks like: which API to call, what RBAC role is needed, how to do canary releases, and what the rollback granularity is. Container Apps rollback is “shift traffic back to the old revision”; AKS is kubectl rollout undo or revert in the GitOps repository; App Service is “swap the slot once more”.
How: three common Azure deployment targets (myapp perspective)
| Azure Container Apps (ACA) | AKS | App Service (containers) | |
|---|---|---|---|
| Abstraction level | Serverless containers (underlying Kubernetes + KEDA + Envoy, invisible to users) | Managed Kubernetes; you are responsible for nodes and cluster components | Managed web platform |
| GitLab deployment method | az containerapp update (after OIDC sign-in) | agent CI/CD workflow (kubectl kubectl/Helm via KAS) or GitOps (Flux); or OIDC + az aks get-credentials | az webapp config container set + slot swap |
| canary / rollback | revisions + traffic percentage | Deployment rolling update, Gateway weights, Flux revert | deployment slot swap, percentage routing to slots |
| scale to 0 | yes (Consumption) | requires KEDA; nodes are still billed | no (planned always-on billing) |
| Permissions required by the pipeline identity | write permission on application resources | agent approach: no Azure credentials needed, permissions determined by the agent's Kubernetes RBAC | write permission on the site (and slots) |
| Suitable for | microservices and APIs; the team does not want to operate Kubernetes | needs the full Kubernetes API, CRDs, a platform team | traditional web apps that need slots and built-in authentication |
GitLab's three deployment models
| push-based (CI job + OIDC) | agent CI/CD workflow | GitOps (agent + Flux) | |
|---|---|---|---|
| Who calls the target API | The job on the Runner calls ARM directly | job's kubectl request goes through KAS → agentk tunnel to the cluster API | Flux inside the cluster pulls Git/OCI and reconciles |
| Where credentials live | In the job: short-lived Azure token exchanged from the ID token | GitLab-injected KUBECONFIG (authenticates to KAS with a job token); cluster-side permissions = agent service account or impersonated identity | inside the cluster; GitLab only needs repo write access |
| Does the cluster need inbound reachability | — | no: agentk connects outward on its own kas.gitlab.com | no |
| Drift handling | until next deployment | until next deployment | continuous correction |
| Official recommendation | general approach for non-Kubernetes targets | simple scenarios; the docs recommend GitOps first for production | recommended for Kubernetes production |
When: how to choose
- team has no Kubernetes operations capability, service is an HTTP container → ACA + push-based (this lesson's main line, module 5).
- already have an AKS cluster and a platform team → GitLab agent: for simple projects use the CI/CD workflow (module 6); for production, Flux GitOps is recommended (
glab cluster agent bootstrap). - traditional web apps that need zero-downtime “warm then swap” → App Service + deployment slots.
- Whichever target: build once, promote across environments— the same image goes from dev to prod; never rebuild for prod.
environment: environment keyword will change the ID token's sub” — by default does not, which is the biggest difference from GitHub (module 2).Architecture diagram: myapp's push-based CD (this lesson's main line)
Comparison diagram: credential and network boundaries of GitLab's three deployment models
Interactive selector: choose a deployment target and deployment model for your service
Answer 5 questions; the selector gives a recommended target, the GitLab deployment method, the identity and minimum permissions needed, the rollback method, and the GitLab tier required. You can change any question, and the result refreshes immediately.
Core commands: find out “what the deployment target looks like now”
| Command | Purpose | Notes |
|---|---|---|
az containerapp show -g RG -n APP --query properties.template.containers[0].image | current image | verify after deployment that “the SHA that went live is this one” |
az containerapp revision list -g RG -n APP -o table | revisions and traffic | ACA's “deployment history” |
glab api "projects/$GL_ENC/environments" | GitLab environment list | with environment: jobs automatically create on first run |
glab api "projects/$GL_ENC/deployments?environment=dev&order_by=id&sort=desc&per_page=5" | recent deployment records | status: created / running / success / failed / canceled / skipped / blocked |
glab ci list | recent pipelines | run history on the GitLab side |
glab api "projects/$GL_ENC/registry/repositories?tags=true" | container registry and tags | confirm which SHA the build job pushed |
source ~/gitlab-lab.env
az containerapp show -g $RG -n $APP_DEV --query "{image:properties.template.containers[0].image, rev:properties.latestRevisionName, fqdn:properties.configuration.ingress.fqdn}" -o table
glab api "projects/$GL_ENC/environments" | jq 'length'
Image Rev Fqdn ---------------------------------------- ------------------- ---------------------------------------------------------------- mcr.microsoft.com/k8se/quickstart:latest myapp-dev--0000001 myapp-dev.happyrock-5c6d7e8f.canadacentral.azurecontainerapps.io 0
How to verify: After module 5, the image should become acrgitlab….azurecr.io/myapp:<short-sha>, and the environment count becomes 2 (dev, prod). Common errors: assuming latestRevisionName is the revision receiving traffic; in multiple revision mode that is not necessarily so, so check ingress.traffic. Production use: put these two commands into the release checklist to answer “which commit is running in production right now”.
Lab 1: write the myapp deployment design (about 4 minutes)
docs/deploy.md in the project root.
cd ~/myapp && git switch main && git pull && mkdir -p docs cat > docs/deploy.md <<'EOF' # myapp deployment design (Azure) - Artifact: GitLab container registry registry.gitlab.com/mygroup-lab/myapp:<short-sha>, promoted to ACR (az acr import), not rebuilt - Target: Azure Container Apps (myapp-dev: Single; myapp-prod: Multiple), port 5000, /healthz - Method: push-based (id_tokens + Entra federated credentials), no cloud passwords stored in the project - Environments: dev (automatic after merge to main) → prod (protected tag v* + manual; add deployment approval on Premium) - Identities: build = ACR import; dev = write myapp-dev; prod = write myapp-prod; app runtime = AcrPull - Rollback: new prod revision at 0% traffic for staging; if the smoke test fails, traffic stays on the old revision EOF
az containerapp show from the Commands page, and record both FQDNs in docs/deploy.md.git switch -c docs/deploy-design git add docs/deploy.md && git commit -m "docs: deployment design for Azure" git push -u origin HEAD glab mr create --fill --yes glab ci status --live
(passed) • 00m 41s test test https://gitlab.com/mygroup-lab/myapp/-/pipelines/1834567890 SHA: 3f9c2ab1… Pipeline state: success
glab mr merge --squash --remove-source-branch --yes. No deployment jobs exist yet, so merging deploys nothing. Cleanup: none (documentation kept).Case 1: rebuilding for prod made “what was tested isn't what shipped”
Problem: The team runs the build once each in the dev and prod stages docker build. Between the two builds, the upstream python:3.13-slim was updated; the prod image gained an OpenSSL patch, changing certificate chain behavior, so prod failed while dev worked. Approach: Build only once in the main pipeline, tagging the image by SHA; prod (tag pipeline) deploys the image with the same SHA. Configuration:IMAGE_TAG: $CI_COMMIT_SHORT_SHA, the prod job has no docker build. Constraint: differences between dev and prod can only come from configuration (environment variables, secret references).
Case 2: multiple services share AKS; moving from “every project has cluster credentials” to agent
Problem: 30 projects each store a copy of a kubeconfig in CI/CD variables, a huge exposure surface, and the cluster API must be publicly exposed. Approach: the platform team installs a GitLab agent in the cluster and configures the project .gitlab/agents/aks-platform/config.yaml in ci_access.groups to authorize application groups, and use access_as: ci_job (Premium) to map jobs to identities that RBAC rules can constrain. Effect: all kubeconfig variables deleted, API server made private. Limitation: the CI/CD workflow is still push-based; critical services further migrate to Flux GitOps.
Case 3: small team migrates App Service to Container Apps
Problem: 3 low-traffic internal APIs each occupy an App Service plan (always-on billing). Approach: migrate to the same Container Apps environment, minimum replicas 0. Limitation: after scaling to 0, the first request has a cold start; for APIs with an SLA, set --min-replicas 1.
Common design errors and symptoms
after prod goes live its version differs from dev, though both jobs correspond to the same commit
Cause: the two stages each build separately, or deployment uses a mutable tag (:latest,:main) which gets overwritten in the meantime.
az containerapp revision list -g $RG -n $APP_PROD --query "[].{rev:name, image:properties.template.containers[0].image}" -o table
az acr manifest list-metadata -r $ACR -n myapp --query "[].{digest:digest, tags:tags}" -o table
Fix: build only once, promote by SHA tag (or digest); forbid deploying :latest.
a deployment job also ran in the MR pipeline
Cause: the deployment job has no rules or rules only wrote when: on_success.
deploy-dev:
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
Prevention: always explicitly write rules; the cloud federated credential only trusts main / v* tags, so even if an MR branch runs it cannot get a token (defense in depth).
using one high-privilege identity for build, dev deployment and prod deployment
Risk: anyone who can run jobs on main (including poisoned dependencies, modified include templates) can get prod write access.
Fix: split identities per job (module 2), the prod identity trusts only protected v* tags, and on GitLab restrict who can trigger via protected tags and protected environments (module 3).
1. Use one command to list the names, revision modes and current images of all Container Apps in rg-gitlab-lab.
az containerapp list -g rg-gitlab-lab --query "[].{name:name, mode:properties.configuration.activeRevisionsMode, image:properties.template.containers[0].image}" -o table2. Use glab to view the status and commit SHA of the 3 most recent deployment records for the prod environment.
glab api "projects/$GL_ENC/deployments?environment=prod&order_by=id&sort=desc&per_page=3" | jq -r '.[] | "\(.id) \(.status) \(.sha[0:8]) \(.created_at)"'
A 6-person team maintains 5 Python APIs with no Kubernetes experience. They require approval before prod release and rollback within 1 minute, and GitLab only has the Free tier. How would you design this?
Choose Container Apps + push-based: one container app per API, sharing one environment. On GitLab: main → build → import → dev (automatic); prod is triggered only from protected tags v* and the deployment job uses when: manual— the Free tier has no deployment approval, so use “only Maintainers can create v* tags + manual click” as the gate. Prod uses multiple revision mode, 0% staging → smoke test → shift traffic; rollback = shift traffic back to the old revision (in seconds). Identities are split per job; prod's federated credential trusts only ref_type:tag. If you upgrade to Premium, add a protected environment + 1 approver.
Verified instructional videos
Official docs
- Comparing Container Apps with other Azure container options
- GitLab Docs: Environments
- GitLab Docs: Connecting a Kubernetes cluster with GitLab
Video storyboard script (about 75 seconds)
This courseware cannot directly generate video or MP3; the storyboard and narration script are provided for production with a video tool.
Visual: GitLab pipeline view all green, with a question mark pointing to Azure beside it.
Narration: a green pipeline only means the code can be merged. CD must answer: which artifact, with what identity, approved by whom, going to where.
Visual: three cards for ACA, AKS and App Service flip open in turn, each showing its “rollback method”.
Narration: the deployment target determines the pipeline's last mile: ACA shifts traffic, AKS rolls back the Deployment, App Service swaps slots.
Visual: three parallel lines: a job connects directly to ARM; a job reaches the cluster through a KAS tunnel; Flux inside the cluster pulls from the repository.
Narration: GitLab has three deployment models: push-based, the agent's CI/CD workflow, and GitOps. The further down, the further the power to “write to production” sits from CI.
Visual: an image with the same SHA tag moves from the dev box to the prod box.
Narration: whichever you choose, build once and promote across environments: what goes live must be the one that was tested.
Module 2 · OIDC federated identity: GitLab → Microsoft Entra ID
- Fully describe the token exchange:
id_tokens→ GitLab issues an RS256 JWT and injects it into job variablesGITLAB_OIDC_TOKEN→az login --service-principal --federated-tokenpresent it as client assertion submitted to Entra → Entra useshttps://gitlab.comJWKS to verify the signature and compares issuer / audience / subject → returns an Azure access token → ARM authorizes per RBAC. - Configure GitLab's
sub:project_path:mygroup-lab/myapp:ref_type:branch:ref:main/…:ref_type:tag:ref:v1.1; know that the defaultsubdoes not include the environment, can be changed viaci_id_token_sub_claim_componentscustom (e.g., starting withproject_id). - Know that regular federated credentials do not support wildcards, at most 20 per identity; will use flexible federated credentials (preview) to match
v*tags (GitLab must match bothsubandproject_id), and be able to explain the trade-offs among branch-level, tag-level and environment-level trust.
What: workload identity federation + GitLab ID token
The old approach was to create a client secret for a service principal in Entra and store it as a masked GitLab variable (AZURE_CLIENT_SECRET). Workload identity federation takes a different approach: register a federated identity credential (FIC) on the Azure identity (user-assigned managed identity or app registration): “I trust issuer as subject issuing tokens with audience audience . GitLab issues a JWT on the spot for each job; after Entra verifies it, it issues an Azure token. There is no password in the project that could be stolen and used long-term.
deploy-dev:
image: mcr.microsoft.com/azure-cli:2.93.0
id_tokens:
GITLAB_OIDC_TOKEN: # the variable name is up to you; this lesson uses this one throughout
aud: api://AzureADTokenExchange
script:
- az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$GITLAB_OIDC_TOKEN" -o none
- az account set --subscription "$AZURE_SUBSCRIPTION_ID"
| JWT claim / FIC field | GitLab.com value | Description |
|---|---|---|
iss ↔ issuer | https://gitlab.com | GitLab instance domain; for self-managed instances it is https://gitlab.example.com. Entra fetches keys via /.well-known/openid-configuration and /oauth/discovery/keys to verify signatures —a self-managed instance must be publicly reachable by Entra, otherwise AADSTS501661 |
aud ↔ audiences | This lesson: api://AzureADTokenExchange | is determined by id_tokens.<name>.aud (can be a string or an array). Microsoft recommends api://AzureADTokenExchange; the GitLab docs example uses https://gitlab.com— as long as both sides match; a mismatch reports AADSTS700212 |
sub ↔ subject | project_path:mygroup-lab/myapp:ref_type:branch:ref:main | exact character-by-character match, case-sensitive,no wildcards |
| name | e.g. gl-main | 3–120 characters, letters/digits/-/_, cannot be changed after creation |
Microsoft Learn limit: each app registration or user-assigned managed identity can have at most 20 FICs; issuer + subject must be unique on the same identity; all attribute values do not support wildcards; a wrong subject still lets the FIC be created successfully, and the error appears only at token exchange; newly created FICs take a moment to propagate, so using one immediately may show AADSTS70021, so retrying is recommended. The GitLab ID token's validity equals the job timeout (5 minutes if no timeout is set), RS256 signed.
How: GitLab's sub and other claims
| job situation | default sub | description |
|---|---|---|
| main branch pipeline | project_path:mygroup-lab/myapp:ref_type:branch:ref:main | on main any job gets the same sub, whether or not environment |
| v1.1 tag pipeline | project_path:mygroup-lab/myapp:ref_type:tag:ref:v1.1 | each tag differs; a regular FIC cannot write v* |
| MR pipeline (same-project branch) | …:ref_type:branch:ref:feature-x | in MR pipeline ref is the source branch name |
custom component ["project_id","ref_type","ref"] | project_id:71234567:ref_type:branch:ref:main | Project settings ci_id_token_sub_claim_components (Projects API); the first value should be the ID component matching the path |
Other common claims (for flexible FICs or troubleshooting): project_id,namespace_id,ref_protected,environment,environment_protected,deployment_tier (the last three exist only if the job declares an environment),user_login,pipeline_source,runner_environment (gitlab-hosted / self-hosted),sha,ci_config_ref_uri,job_project_path (18.4+),source_project_path (19.5+).
environment: prod the sub automatically becomes …:environment:prod, so “trust only the prod environment” is natural (see GitHub lesson 3); GitLab default sub does not include the environment. From GitLab 18.7, sub can include ref_protected, and when the job declares an environment, include environment_protected,deployment_tier— via the project's ci_id_token_sub_claim_components setting. The official docs do not give a complete example string containing these fields; this lesson lists them as advanced options: first print the sub in a token in a test project (see the “Commands” page), then create the FIC with the actual value. Azure DevOps service connections have their subject managed by the platform (sc://org/project/connection), see Azure DevOps lesson 3.Three designs for trust scope and their trade-offs
| Design | FIC format | Advantages | Risks / costs | GitLab controls to pair with |
|---|---|---|---|---|
| A. Branch-level (for dev) | regular FIC: …:ref_type:branch:ref:main | simple, GA, no preview dependency | on main any job (including test jobs and tampered include templates) can get this identity | protect main (only Maintainers can merge, force-push forbidden); this identity gets only dev permissions |
| B. Tag-level (for prod) | flexible FIC (preview): claims['sub'] matches '…:ref_type:tag:ref:v*' and claims['project_id'] eq '…'; or one regular FIC per release tag (≤20) | release is isolated from routine commits; only those who can create v* tags can trigger it | preview feature; the native Azure CLI command does not support it, so it requires az rest; once a FIC is set to v*, the tag must be protected | protected tags v* (Free): only Maintainers can create |
| C. Environment-level | custom sub component adds deployment_tier / environment_protected (18.7+), with the FIC set to the corresponding string | closest to GitHub's environment subject; only jobs declaring a production-tier environment can match | changing the sub affects all cloud-side trust for all project (AWS, Vault, etc.), so update them together; the format should follow the actual token | a protected environment (Premium) restricts who can deploy to it; otherwise anyone who can edit the YAML can declare deployment_tier: production |
This lesson's lab uses A + B:id-gitlab-build and id-gitlab-dev trust the main branch; id-gitlab-prod use a flexible FIC to trust v* tags (and bind project_id), and set v* as a protected tag. Fallback without flexible FICs: before each release, add a regular FIC for that tag, and delete it after release.
Why bind project_id
The default sub uses the path. After a project is renamed or transferred, the old path may be recreated by someone else; GitLab reports an error when the path has been used by another project ID token issuance is disabled in CI because a project path in the sub claim was previously used by a different project, and recommends switching to a sub component starting with the ID. Microsoft also requires GitLab's flexible FIC, when using a mutable subject, to also match sub and project_id. Numeric IDs are never reused, so binding trust to the ID is more robust.
User-assigned managed identity (UAMI) vs app registration
| UAMI | app registration + service principal | |
|---|---|---|
| create | az identity create (Azure resources inside a resource group) | az ad app create + az ad sp create (the GitLab docs example uses this) |
| Required permissions | Managed Identity Contributor / Contributor on the resource group | permission to register apps in the directory (many enterprise tenants forbid ordinary users from doing so) |
| can create secrets | cannot, so it can only federate | can (must be blocked by policy) |
| FIC management | az identity federated-credential create; flexible FIC goes through ARM (az rest --method put) | az ad app federated-credential create; flexible FIC goes through Graph beta |
| lifecycle | deleted with the resource group | directory objects must be cleaned up separately |
This lesson uses UAMI. az login The format is the same for both: -u enter the UAMI's clientId (not principalId) or the app's Application (client) ID.
When: design principles
- one identity per trust boundary: build / dev / prod three identities; RBAC is granted per identity, so sharing one would give dev jobs prod permissions.
- OIDC cannot replace GitLab-side controls: the ID token is available to any job in the project (not restricted by “protected variables”), so you must rely on protected branches, protected tags and protected environments to limit “who can make a job run on that ref”.
- MR jobs get no identity: this lesson's MR pipeline only runs tests; if you need what-if/plan, give a read-only identity and a separate FIC. MR pipelines from forks run by default in the fork project, so the sub contains
project_pathis the fork's path and naturally does not match. - Before changing the sub component, first add the new FIC in the cloud, then switch, and delete the old FIC after confirming.
id_tokens is a Premium feature” — it is available on Free. ② “A FIC can use ref:*” — regular FICs do not support wildcards; use a flexible FIC (preview). ③ “Setting environment: prod then only prod jobs can use the prod identity” — the default sub does not include the environment. ④ “AZURE_CLIENT_ID is a secret” — it is not a password and can go in a regular variable; the real boundary is the FIC subject and RBAC. ⑤ “Should echo $GITLAB_OIDC_TOKEN debug” — do not print the full token (it is valid during the job and can be replayed); decode only the claims in the payload.Sequence diagram: one keyless GitLab → Azure sign-in
Trust scope diagram: what each of the three identities trusts
Core animation: OIDC token exchange (failure scenarios can be switched)
Choose a scenario, then click “Run job”. Each step highlights the parties involved, and the terminal shows what you would actually see in the job log or in Azure. The last two scenarios show “GitLab refuses to issue” and “authentication succeeds but authorization fails” respectively.
sub / wildcard calculator
Enter the project and pipeline information; the calculator gives the sub in the token and compares it with the FIC you plan to write: a regular FIC compares character-by-character (case-sensitive); if the FIC contains * / ?, it is compared with the flexible FIC's matches rules, and reminds you that GitLab must match both project_id.
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
az identity create -g RG -n NAME | Create UAMI | Output clientId (for az login -u) and principalId (for role assignments) |
az identity federated-credential create | Add a regular FIC on the UAMI | --identity-name --name --issuer https://gitlab.com --subject … --audiences api://AzureADTokenExchange |
az rest --method put --url …/federatedIdentityCredentials/NAME?api-version=2025-01-31-preview | Add a flexible FIC (preview) on the UAMI | in the body claimsMatchingExpression,languageVersion: 1, do not write subject |
az ad app federated-credential create --id APP --parameters fic.json | Add a regular FIC on the app registration | Flexible FIC via Graph beta: az rest --method post --url https://graph.microsoft.com/beta/applications/{objectId}/federatedIdentityCredentials |
az role assignment create --assignee-object-id PID --assignee-principal-type ServicePrincipal --role R --scope S | Grant RBAC | use object ID + principal type to avoid failures caused by directory replication delay |
az login --service-principal -u CLIENT_ID -t TENANT --federated-token "$GITLAB_OIDC_TOKEN" | Keyless sign-in inside a job | afterwards az account set --subscription |
glab api -X PUT "projects/$GL_ENC" -f 'ci_id_token_sub_claim_components[]=project_id' … | custom sub component | changes affect all OIDC trust in the project; add the new FIC before switching |
glab variable set KEY VALUE --scope ENV | Set (environment-scoped) CI/CD variables | environment-scoped variables are available on the Free tier |
Safely view claims in a token (decode the payload only, do not print the token)
whoami-oidc: # temporary debug job; delete after confirming
image: alpine:3.22
id_tokens:
GITLAB_OIDC_TOKEN:
aud: api://AzureADTokenExchange
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual
script:
- apk add --no-cache jq >/dev/null
- P=$(echo "$GITLAB_OIDC_TOKEN" | cut -d. -f2 | tr '_-' '/+')
- while [ $(( ${#P} % 4 )) -ne 0 ]; do P="$P="; done
- echo "$P" | base64 -d | jq '{iss, aud, sub, project_id, ref_type, ref, ref_protected, environment, deployment_tier, runner_environment, exp}'
{
"iss": "https://gitlab.com",
"aud": "api://AzureADTokenExchange",
"sub": "project_path:mygroup-lab/myapp:ref_type:branch:ref:main",
"project_id": "71234567",
"ref_type": "branch",
"ref": "main",
"ref_protected": "true",
"environment": null,
"deployment_tier": null,
"runner_environment": "gitlab-hosted",
"exp": 1794830400
}
Note: The JWT payload is base64url-encoded; you need to convert -_ back to +/ and pad =. Printing only the payload does not leak the signature and cannot be replayed. Some boolean claims appear as strings in GitLab examples ("true"). Common errors: directly echo $GITLAB_OIDC_TOKEN— the full token remains valid until the job times out.
Custom sub component (advanced, optional)
source ~/gitlab-lab.env # view current settings (field names follow the Projects API) glab api "projects/$GL_ENC" | jq '.ci_id_token_sub_claim_components' # change to start with project_id (first add the FIC for the new sub in Azure!) glab api -X PUT "projects/$GL_ENC" \ -f 'ci_id_token_sub_claim_components[]=project_id' \ -f 'ci_id_token_sub_claim_components[]=ref_type' \ -f 'ci_id_token_sub_claim_components[]=ref'
[ "project_path", "ref_type", "ref" ]
After switching, the sub on main becomes project_id:71234567:ref_type:branch:ref:main. This lesson's main line does not switch; keep the default so as not to affect the AWS trust policy in lesson 4.
Lab 2: three identities, three federated credentials, the first keyless sign-in (about 10 minutes)
Cost: managed identities and federated credentials are free. Permissions: resource group Owner (or Managed Identity Contributor + RBAC Administrator); GitLab project Maintainer. Risk: after writing a flexible FIC as v* anyone who can create v tags can get the prod identity; step 3 must protect the tags.
source ~/gitlab-lab.env
for ID in id-gitlab-build id-gitlab-dev id-gitlab-prod; do
az identity create -g $RG -n $ID -l $LOC -o none
done
az identity list -g $RG --query "[].{name:name, clientId:clientId, principalId:principalId}" -o table
Name ClientId PrincipalId --------------- ------------------------------------ ------------------------------------ id-gitlab-build 2b8f1c3d-1111-4a5b-9c8d-0e1f2a3b4c5d 7a1b2c3d-aaaa-4bbb-8ccc-1d2e3f4a5b6c id-gitlab-dev 3c9a2d4e-2222-4b6c-8d9e-1f2a3b4c5d6e 8b2c3d4e-bbbb-4ccc-9ddd-2e3f4a5b6c7d id-gitlab-prod 4d0b3e5f-3333-4c7d-9e0f-2a3b4c5d6e7f 9c3d4e5f-cccc-4ddd-8eee-3f4a5b6c7d8e
source ~/gitlab-lab.env
SUB_MAIN="project_path:$GL_PROJECT:ref_type:branch:ref:main"
for ID in id-gitlab-build id-gitlab-dev; do
az identity federated-credential create -g $RG --identity-name $ID --name gl-main \
--issuer https://gitlab.com --subject "$SUB_MAIN" --audiences api://AzureADTokenExchange -o none
done
az identity federated-credential list -g $RG --identity-name id-gitlab-dev --query "[].{name:name, issuer:issuer, subject:subject}" -o table
Name Issuer Subject ------- ------------------ -------------------------------------------------------- gl-main https://gitlab.com project_path:mygroup-lab/myapp:ref_type:branch:ref:main
Note: do not include a trailing slash in the issuer; multiple FICs on the same identity must be created in sequence (concurrent creation returns 409 Conflict).
source ~/gitlab-lab.env
cat > /tmp/fic-prod.json <<EOF
{"properties":{
"issuer":"https://gitlab.com",
"audiences":["api://AzureADTokenExchange"],
"claimsMatchingExpression":{
"value":"claims['sub'] matches 'project_path:$GL_PROJECT:ref_type:tag:ref:v*' and claims['project_id'] eq '$GL_PROJECT_ID'",
"languageVersion":1}}}
EOF
az rest --method put \
--url "https://management.azure.com/subscriptions/$SUB_ID/resourceGroups/$RG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id-gitlab-prod/federatedIdentityCredentials/gl-tags-v?api-version=2025-01-31-preview" \
--body @/tmp/fic-prod.json --query "properties.claimsMatchingExpression.value" -o tsv
# Protected tags (Free): only Maintainers can create v* tags
glab api -X POST "projects/$GL_ENC/protected_tags" -f name='v*' -f create_access_level=40 | jq '{name, create_access_levels}'
claims['sub'] matches 'project_path:mygroup-lab/myapp:ref_type:tag:ref:v*' and claims['project_id'] eq '71234567'
{
"name": "v*",
"create_access_levels": [ { "access_level": 40, "access_level_description": "Maintainers" } ]
}
az identity federated-credential list) — for management, use az rest. If you don't want to use the preview: run before publishing az identity federated-credential create … --name gl-v1-1 --subject "project_path:$GL_PROJECT:ref_type:tag:ref:v1.1", then delete it after publishing (max 20 per identity).source ~/gitlab-lab.env
pid(){ az identity show -g $RG -n $1 --query principalId -o tsv; }
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment create --assignee-object-id $(pid id-gitlab-build) --assignee-principal-type ServicePrincipal \
--role "Container Registry Data Importer and Data Reader" --scope $ACR_ID -o none
for E in dev prod; do
APP_ID=$(az containerapp show -g $RG -n myapp-$E --query id -o tsv)
az role assignment create --assignee-object-id $(pid id-gitlab-$E) --assignee-principal-type ServicePrincipal \
--role Contributor --scope $APP_ID -o none
done
az role assignment list -g $RG --query "[?principalType=='ServicePrincipal'].{role:roleDefinitionName, scope:scope}" -o table
Scope Contributor only to the individual container app resource. If az containerapp update reports Microsoft.App/managedEnvironments/join/action unauthorized, then in the environment cae-gitlab-lab on it, grant a role that includes that action (see Module 7).
AZURE_CLIENT_ID differentiated by environment scope):
source ~/gitlab-lab.env
cid(){ az identity show -g $RG -n $1 --query clientId -o tsv; }
glab variable set AZURE_TENANT_ID "$TENANT_ID"
glab variable set AZURE_SUBSCRIPTION_ID "$SUB_ID"
glab variable set AZURE_CLIENT_ID_BUILD "$(cid id-gitlab-build)"
glab variable set AZURE_CLIENT_ID "$(cid id-gitlab-dev)" --scope dev
glab variable set AZURE_CLIENT_ID "$(cid id-gitlab-prod)" --scope prod
glab variable list
KEY PROTECTED MASKED EXPANDED SCOPE AZURE_TENANT_ID false false true * AZURE_SUBSCRIPTION_ID false false true * AZURE_CLIENT_ID_BUILD false false true * AZURE_CLIENT_ID false false true dev AZURE_CLIENT_ID false false true prod
Why build uses a different variable name: The promote job has no environment, so it cannot get the dev/prod-scoped AZURE_CLIENT_ID; it sets it at the job level variables writes it in AZURE_CLIENT_ID: $AZURE_CLIENT_ID_BUILD (project variables take precedence over YAML variables, so do not redefine * it in the same scope AZURE_CLIENT_ID otherwise it will override it).
.gitlab-ci.yml temporarily add the job below at the end and push to main (via merge request):
oidc-smoke:
stage: test
image: mcr.microsoft.com/azure-cli:2.93.0
variables:
AZURE_CLIENT_ID: $AZURE_CLIENT_ID_BUILD
id_tokens:
GITLAB_OIDC_TOKEN:
aud: api://AzureADTokenExchange
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$GITLAB_OIDC_TOKEN" -o none
- az account set --subscription "$AZURE_SUBSCRIPTION_ID"
- az account show --query "{user:user.name, type:user.type}" -o table
- az acr list --query "[].name" -o tsv
$ az account show --query "{user:user.name, type:user.type}" -o table
User Type
------------------------------------ ----------------
2b8f1c3d-1111-4a5b-9c8d-0e1f2a3b4c5d servicePrincipal
$ az acr list --query "[].name" -o tsv
acrgitlab21873
Job succeeded
Verify: The signed-in user is the clientId of the build identity. If you see AADSTS70021, wait 1–2 minutes (FIC propagation) before retrying; if it still fails, check the “Troubleshooting” tab. Cleanup: After verification, delete the oidc-smoke job (Module 4 replaces it with the real job).
Case 1: Migrating from client secrets to OIDC with zero downtime
Problem: The project uses AZURE_CLIENT_SECRET masked variables; a secret expiring after a year once caused an early-morning deployment failure, and the security team required secrets to be disabled. Solution: (1) Add an FIC to the same app registration (main branch); (2) in the deploy job, add id_tokens,az login and switch to --federated-token; (3) once it works, delete the secret from the CI/CD variables and delete the client secret in Entra; (4) use an app management policy to block creating new secrets. Limitation: Self-managed GitLab must let Entra reach its OIDC discovery endpoint and JWKS, otherwise AADSTS501661.
Case 2: All deployments fail after the project is renamed
Problem:platform/payments Renamed to platform/payments-api, the value in sub project_path changed, so all FIC matches failed. Solution: Change the sub component to ["project_id","ref_type","ref"], and change the FIC to project_id:…:ref_type:branch:ref:main. Afterwards, renaming or transferring no longer affects trust, and it also avoids the trust-reclaim risk from an “old path being recreated by someone else.”Limitation: The AWS and Vault trusts for the same project must also be updated.
Case 3: Too many release tags exhaust the FIC limit
Problem: The team adds one FIC for every new release tag, and quickly hits the limit of 20 per identity. Solution: Switch to one flexible FIC: claims['sub'] matches 'project_path:…:ref_type:tag:ref:v*' and claims['project_id'] eq '…', and also set v* as a protected tag. Limitation: Preview feature; requires az rest management; Terraform azurerm does not support it yet, so in IaC use azapi or similar methods (see the official documentation).
Common OIDC sign-in errors
AADSTS70021: No matching federated identity record found for presented assertion.
Cause: at least one of issuer / subject / audience does not match, or the FIC was just created and has not propagated yet.
az identity federated-credential list -g $RG --identity-name id-gitlab-dev --query "[].{issuer:issuer, subject:subject, aud:audiences[0]}" -o table
Fix: Run the job from the “Commands” tab whoami-oidc and compare each item iss (https://gitlab.com, no trailing slash),sub (branch or tag? path case?),aud. Wait 1–2 minutes after creating a new FIC before retrying.
AADSTS700212: No matching federated identity record found for presented assertion audience 'https://gitlab.com'.
Cause:id_tokens the aud reuses the GitLab docs example's https://gitlab.com, but the FIC's audience is api://AzureADTokenExchange (or vice versa).
Fix: Make both sides the same value; this lesson standardizes on api://AzureADTokenExchange.
AADSTS700213 / AADSTS7002138: No matching federated identity record found for presented assertion subject 'project_path:mygroup-lab/myapp:ref_type:tag:ref:v1.1'
Cause: the subject does not match (700213), or differs only in case (7002138, e.g. the FIC is written as MyGroup-Lab). A common case: the prod identity has only a main-branch FIC, but the job runs from a tag pipeline.
Fix: Add or recreate the FIC using the subject shown in the error (the name cannot be changed, so delete and recreate it); for tag scenarios, use a flexible FIC or add one per tag.
ERROR: argument --federated-token: expected one argument
Cause:$GITLAB_OIDC_TOKEN is empty: the job does not have id_tokens (it is only defined in another job or template), or the variable name is misspelled.
Fix: Check extends the template contains id_tokens, and the job does not override it with its own id_tokens value; the variable names must match.
ID token issuance is disabled in CI because a project path in the sub claim was previously used by a different project.
Cause: This project path previously belonged to another project (renamed or deleted and then recreated). GitLab refuses to issue the token to prevent inheriting the old project's cloud trust.
Fix: Following the GitLab docs, set ci_id_token_sub_claim_components to start with the ID (e.g. project_id), and add a matching FIC in Azure.
1. Add a standard FIC for id-gitlab-dev that trusts the release/2026.11 branch.
az identity federated-credential create -g rg-gitlab-lab --identity-name id-gitlab-dev --name gl-release-2026-11 \ --issuer https://gitlab.com --subject "project_path:mygroup-lab/myapp:ref_type:branch:ref:release/2026.11" \ --audiences api://AzureADTokenExchange
FIC names may only contain letters, digits, - and _, so the name cannot include / and .; the subject can.
2. Write the minimal YAML that declares an ID token in a job and signs in to Azure.
job:
image: mcr.microsoft.com/azure-cli:2.93.0
id_tokens:
GITLAB_OIDC_TOKEN:
aud: api://AzureADTokenExchange
script:
- az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$GITLAB_OIDC_TOKEN" -o noneThe security team found that any developer who adds a job on main can obtain the prod identity. Currently the prod identity's FIC trusts the main branch. How would you change this?
The root cause is that GitLab's default sub does not include the environment, so every job on main has the same sub. Fixes (choose one or combine): (1) change the prod identity to trust only protected v* tags (flexible FIC + project_id, or per-tag FICs), and set v* so that only Maintainers can create them; (2) on 18.7+, use a custom sub claim component to add deployment_tier / environment_protected, with the FIC trusting only the production tier, and use Premium protected environments to restrict who can deploy; (3) also tighten main: only Maintainers can merge into protected branches, with CODEOWNERS review .gitlab-ci.yml. The dev identity can keep trusting main, because it only has dev permissions.
Verified training videos
No verified video specifically on GitLab → Azure workload identity federation was found. The two videos below cover the same mechanism in Azure DevOps and GitHub. The principles (issuer / subject / audience, keyless) are identical, so you can watch them alongside the GitLab details in this module.
Official documentation
- GitLab Docs: Configure OpenID Connect in Azure to retrieve temporary credentials
- GitLab Docs: OpenID Connect (OIDC) authentication using ID tokens
- Microsoft Learn: Workload identity federation considerations
- Microsoft Learn: Flexible federated identity credentials (preview)
Video storyboard script (about 90 seconds)
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided.
Visual: in the CI/CD variables list, one
AZURE_CLIENT_SECRET entry is crossed out with a red pen.Narration: long-lived secrets expire, can leak, and can be used from anywhere. We want the project to have no cloud passwords at all.
Visual: the job starts, and GitLab hands it an “ID card” JWT with iss, aud, and sub written on it.
Narration: when the job starts, GitLab issues a JWT based on id_tokens; the sub states the project path, the ref type, and the ref.
Visual: the Entra gatekeeper checks a three-column list word by word, with the public key fetched from gitlab.com in the background.
Narration: az login hands this ID card to Entra. Entra verifies the signature with GitLab's public key, then compares three values word by word against the federated credential. Only if all three match does it issue an Azure token valid for about an hour.
Visual: three keys tagged main, main, and v*, corresponding to the three doors: ACR, dev, and prod.
Narration: GitLab's default sub does not include the environment, so trust is divided by branches, tags, and protection rules, with one identity per boundary.
Module 3 · Environments, deployments, and protected environment approvals
- Write
environment:(name,url,deployment_tier,action,on_stop,auto_stop_in), and understand where deployment records, redeploys, and rollbacks come from. - Use
resource_groupto serialize deployments, and use “Prevent outdated deployment jobs” to keep old pipelines from overwriting newer versions. - Configure protected environments (allowed deployers + approval rules, Premium), explain that self-approval is blocked by default and that jobs still need to be run manually after approval, and provide Free-tier alternative gates.
rules and when: manual. Importance:★★★★★What: environments, deployments, and deployment jobs
Set environment: on a job, and that job becomes a deployment job: when the job starts, GitLab creates one deployment record (deployment), which records the commit, job, triggerer, and status; the environment page (Operate → Environments) shows which commit is currently deployed to each environment and provides “Redeploy / Rollback” buttons (in essence, retrying the corresponding old deployment job).
deploy-prod:
stage: deploy
environment:
name: prod
deployment_tier: production # development / testing / staging / production / other
url: $DYNAMIC_URL # can come from artifacts:reports:dotenv
action: start # default; others are prepare / verify / access / stop
resource_group: prod # only one prod deployment job can run at a time
| Keyword | Purpose | Usage in this lesson |
|---|---|---|
name | Environment name; variables can be used (e.g. review/$CI_COMMIT_REF_SLUG) | dev,prod (matches the environment scope of CI/CD variables) |
deployment_tier | Environment tier; if not set, GitLab guesses from the name, and if the guess misses it becomes other; it cannot be changed in the UI, and values added later do not update existing environments | dev=development, prod=production (set explicitly to avoid wrong guesses) |
url | “Open” button on the environment page; can be provided dynamically by a dotenv report | FQDN of Container Apps |
action | start Creates a deployment; prepare/verify/access does not create a deployment; stop Stops the environment | Used by smoke-test jobs verify |
on_stop / auto_stop_in | Job that stops the environment / auto-stop time | Commonly used for review environments (review apps) |
kubernetes: agent: | Link a GitLab agent (17.6+); the environment page shows the Kubernetes dashboard | Module 6 |
resource_group | Mutual exclusion across pipelines: jobs in the same group never run at the same time; later ones wait. Default processing mode unordered | dev,prod |
Why: three kinds of risk map to three kinds of control
| Risk | Control | Layer |
|---|---|---|
| Two merges happen almost simultaneously, and two deployment jobs modify prod concurrently | resource_group: prod | Free |
| An old pipeline arrives late (retries, queuing) and overwrites the new version with the old one | “Prevent outdated deployment jobs” under Settings → CI/CD → General pipelines: the old job fails and displays The deployment job is older than the latest deployment, and therefore failed. | Free |
| Anyone who can push or create tags can deploy to production; nobody reviews it | Protected environment (Allowed to deploy) + deployment approval (Approvers, required number of approvals) | Premium / Ultimate |
How: protected environments and deployment approvals (Premium)
- Protect: Settings → CI/CD → Protected environments → Protect an environment; select the environment,Allowed to deploy (Maintainers / Developers + Maintainers / specified users or invited groups) and Approvers. Requires the Maintainer role. You can also use
POST /projects/:id/protected_environments(deploy_access_levelsrequired,approval_rulesoptional; rules can includerequired_approvals). - Users who are not allowed to run deployment jobs: the job fails. Only allowed users can run or retry; GitLab administrators can use all environments.
- Approval: when a deployment job with approval rules starts, its deployment status is blocked (visible on the job page and via the API). Approvers can, in Operate → Environments → environment → deployment status badge Approve / Reject (with an optional comment), or call
POST /projects/:id/deployments/:deployment_id/approval(status=approved|rejected,comment,represented_as). - Self-approval: by default,not allowed the pipeline triggerer approving their own deployment; enable “Allow pipeline triggerer to approve deployment” under Protected environments → Approval options. Each user can approve a deployment only once (even if they belong to several approval groups).
- After approval: approval does not start the job automatically; someone must manually run the deployment job. The required number of approvals should be less than the number of people allowed to deploy; otherwise there may be no one left to approve.
- Group level: a top-level group can protect by deployment tier (for example, all production-tier environments); when both project-level and group-level protection apply, both must allow the action.
Comparison with GitHub / Azure DevOps
| GitLab | GitHub | Azure DevOps | |
|---|---|---|---|
| Environment declaration | Job environment: | Job environment: | deployment job's environment: |
| approval | Protected environment approval rules (Premium) | Required reviewers (for plan and visibility limits, see the GitHub lesson) | Approvals and checks for the environment |
| Concurrency | resource_group | concurrency | Exclusive lock check |
| Affects the OIDC subject? | Not by default (customizable component) | Yes: …:environment:NAME | determined by the service connection |
| See | this module | GitHub Lesson 3 · Module 3 | Azure DevOps Lesson 3 |
When: how to build a release gate on the Free tier
- prod is triggered only from protected tags
v*(only Maintainers can create tags) + deployment jobwhen: manual(runs only when someone clicks it). - Set CI/CD variables to protected (readable only from protected branches/tags) + environment scope
prod. - The prod identity's FIC trusts only
ref_type:tag— even if someone writes a prod job in a feature branch, they still cannot obtain a token. - When “review by someone other than the triggerer” is required, the Free tier cannot enforce it; this is the typical reason to upgrade to Premium (or require review at the merge request approval rule level; see Git lesson 4).
environment_protected claims appear in the token, and by default they are not part of sub). (2) “Approval automatically deploys” — after approval, the job still must be run manually. (3) “resource_group will cancel old jobs” — it only queues mutually exclusive jobs and does not cancel them; to stop old jobs from overwriting new ones, rely on “Prevent outdated deployment jobs”. (4) “Environment-scoped variables are a Premium feature” — they are available on Free.State diagram: lifecycle of one prod deployment
Control layers diagram: each layer answers one question
Deployment gate simulator
Set the project tier, protection rules, and trigger conditions, then click “Trigger deploy-prod” to see which checks the job passes, where it stops, and what appears in the log.
Core commands (glab api / REST)
| Command | Purpose | Notes |
|---|---|---|
glab api "projects/$GL_ENC/environments" | List environments | includes state,tier,external_url |
glab api "projects/$GL_ENC/deployments?environment=prod&status=blocked" | Find deployments awaiting approval | Status filter: created / running / success / failed / canceled / skipped / blocked |
glab api -X POST "projects/$GL_ENC/deployments/ID/approval" -f status=approved -f comment=… | Approve / reject | Premium; represented_as used when the deployment belongs to multiple rules |
glab api -X POST "projects/$GL_ENC/protected_environments" --input pe.json -H "Content-Type: application/json" | Protect environment | Premium; deploy_access_levels required |
glab api "projects/$GL_ENC/protected_environments/prod" | View protection and approval rules | includes approval_rules |
glab api -X POST "projects/$GL_ENC/protected_tags" -f name='v*' -f create_access_level=40 | Protect release tags | Free; 40 = Maintainer |
glab ci retry JOB_ID | Retry deployment job | CLI approach to “Redeploy” |
source ~/gitlab-lab.env
cat > /tmp/pe.json <<'EOF'
{
"name": "prod",
"deploy_access_levels": [ { "access_level": 40 } ],
"approval_rules": [ { "access_level": 40, "required_approvals": 1 } ]
}
EOF
glab api -X POST "projects/$GL_ENC/protected_environments" -H "Content-Type: application/json" --input /tmp/pe.json \
| jq '{name, deploy:[.deploy_access_levels[].access_level_description], approval_rules:[.approval_rules[] | {who:.access_level_description, required_approvals}]}'
{
"name": "prod",
"deploy": [ "Maintainers" ],
"approval_rules": [ { "who": "Maintainers", "required_approvals": 1 } ]
}
Common errors: Calls on the Free tier return 403/404; the environment must already exist (it is created automatically the first time a deployment job runs, or you can create it manually under Operate → Environments). How to verify: Run deploy-prod with a Developer account; the job should fail.
# Find the blocked deployment and approve it (run by an approver; the triggerer cannot approve their own by default)
DEP=$(glab api "projects/$GL_ENC/deployments?environment=prod&status=blocked&order_by=id&sort=desc" | jq -r '.[0].id')
glab api -X POST "projects/$GL_ENC/deployments/$DEP/approval" -f status=approved -f comment="v1.1 smoke OK on dev" \
| jq '{status, user: .user.username, comment}'
{
"status": "approved",
"user": "reviewer-maint",
"comment": "v1.1 smoke OK on dev"
}
Lab 3: dev / prod environments, protected tags, and (Premium) approvals (about 8 minutes)
.gitlab-ci.yml , declare the environment and resource group for the deployment job (the full pipeline is in Module 5; here we look at the environment-related parts first):
deploy-dev:
environment: { name: dev, deployment_tier: development, url: $DYNAMIC_URL }
resource_group: dev
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-prod:
environment: { name: prod, deployment_tier: production, url: $DYNAMIC_URL }
resource_group: prod
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/
when: manualglab api "projects/$GL_ENC/protected_tags" | jq -r '.[] | "\(.name) → \(.create_access_levels[0].access_level_description)"'
v* → Maintainers
protected_environments call from the “Commands” tab; or in the UI: Settings → CI/CD → Protected environments → Protect an environment → prod, Allowed to deploy = Maintainers, Approvers = Maintainers, Required approvals = 1. Without Premium: skip this step; the gate = protected tags + when: manual.v1.0 → in the tag pipeline, deploy-prod shows as manual → click run → under Premium, the deployment status is blocked → another Maintainer approves → click run again → succeeds.
glab api "projects/$GL_ENC/environments?name=prod" | jq '.[0] | {name, tier, state, last: .last_deployment.status}'
{ "name": "prod", "tier": "production", "state": "available", "last": "success" }
Cleanup: Module 8 removes the environments (stop them first), protected environments, and tag protections together.
Case 1: Concurrent merges roll prod back to an older version
Problem: Two MRs were merged one minute apart; the second pipeline's deployment finished first, and then the first one finished and overwrote prod with the older commit. Solution: Add resource_group: prod (mutual exclusion) and enable “Prevent outdated deployment jobs” (old jobs fail immediately). Limitation:resource_group By default, the process mode is unordered, so queue order is not guaranteed; if strict ordering is needed, change it to oldest_first / newest_first (through the resource group API; see the official documentation).
Case 2: Only one approver; releases get stuck when that person is on vacation
Problem: The prod approval rule named only one user; that user went on vacation, and the deployment stayed blocked. Solution: Change the approval rule to a group (invite the group to the project first) with 1 required approval, and the group has 3 members; also grant “Allowed to deploy” to that group. Limitation: The number of required approvals must be less than the number of eligible approvers; self-approval is blocked by default, and the triggerer does not count.
Case 3: Uniformly protect the production tier across multiple projects
Problem: 40 projects each name their production environment differently (prod, production, live), so per-project protection is easy to miss. Solution: Set deployment_tier: production, and in the top-level group, under Settings → CI/CD → Protected environments, protect by tier so that only the operations subgroup can deploy. Limitation: Premium; when project-level and group-level protections both exist, both must allow the action.
Common errors and symptoms
The deployment job shows “blocked” and does not move
Cause: The protected environment has approval rules and has not yet received enough approvals; or approval was granted but no one has run the job again.
glab api "projects/$GL_ENC/deployments?environment=prod&status=blocked" | jq '.[] | {id, sha: .sha[0:8], user: .user.username}'
glab api "projects/$GL_ENC/protected_environments/prod" | jq '.approval_rules'
Fix: Have an approver who is not the triggerer approve it; after approval, click “Run” on the job page.
The deployment job is older than the latest deployment, and therefore failed.
Cause:“Prevent outdated deployment jobs” is enabled, and a newer deployment has already succeeded. This is usually correct protection.
Fix: If you really need to roll back, use the rollback button on the environment page (retry rollback must be allowed), or run a new pipeline on the old commit.
Developer runs deploy-prod: the job fails, or the job page has no “Run” button
Cause: prod is a protected environment, and Developer is not in Allowed to deploy.
Fix: Run it with an allowed role; or, as needed, add the specified users/groups to Allowed to deploy (groups must first be invited to the project).
Waiting for resource: prod
Cause: Within the same resource_group resource group, another job is running (possibly a stuck manual or blocked job).
glab api "projects/$GL_ENC/resource_groups/prod/upcoming_jobs" | jq '.[] | {id, name, status}'
Fix: Finish or cancel the job that is occupying the resource group.
The environment tier shows as other, and the group-level protection is not in effect
Cause: not setting deployment_tier, so GitLab's name-based guess failed, and existing environments are not updated just because deployment_tier was added later.
Fix: Explicitly set deployment_tier: production; for existing environments, stop and delete them and redeploy (or update the tier through the environments API; see the official documentation).
1. List the IDs of all deployments awaiting approval in the prod environment.
glab api "projects/$GL_ENC/deployments?environment=prod&status=blocked" | jq -r '.[].id'
2. Set v* tags so that only Maintainers can create them.
glab api -X POST "projects/$GL_ENC/protected_tags" -f name='v*' -f create_access_level=40
On the Free tier, the team requires that “prod releases must be confirmed by someone other than the triggerer.” How far can you go?
The Free tier has no deployment approvals, so you cannot enforce “approval by a non-triggerer” on a deployment job. A feasible combination: (1) releases are triggered only from protected tags v* so that only a few Maintainers can create tags; (2) before tagging, require a merge request (for example, updating the CHANGELOG/version number), and an MR approval rule requires someone else to approve it (for the levels of MR approval rules, see Git lesson 4); (3) the prod job is set to when: manual; (4) the prod identity's FIC trusts only tags. If “approval by someone else before deployment” must be enforced, Premium protected environment approvals are required.
Verified training videos
No verified official GitLab video on protected environments / deployment approvals was found. Here are related verified videos:
Official documentation
- GitLab Docs: Protected environments
- GitLab Docs: Deployment approvals
- GitLab Docs: Deployment safety
- GitLab Docs: Deployments API
Video storyboard script (about 80 seconds)
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided.
Visual: on the environments page, two rows for dev and prod, each showing the current commit SHA and deployment time.
Narration: add environment to a job and it becomes a deployment job; GitLab records each deployment: which commit, who triggered it, and whether it succeeded.
Visual: two pipelines rush toward prod at the same time, and a gate labeled resource_group makes them queue.
Narration: resource_group allows only one prod deployment at a time; Prevent outdated deployment jobs stops an old pipeline from overwriting the new version.
Visual: the deployment status badge turns yellow (blocked); the approver clicks Approve; after the badge turns green, someone clicks run.
Narration: Premium protected environments decide who can deploy, and approval rules decide how many people must approve. By default the triggerer cannot approve their own deployment, and after approval the job still has to be run manually.
Visual: the Free-tier combination: a locked v* tag + a manual button + an Azure key that trusts only tags.
Narration: without Premium, build the gate from protected tags, a manual job, and federated credentials that trust only tags.
Module 4 · Build and push to ACR (or the GitLab Container Registry)
- Build myapp on a GitLab Runner using Docker-in-Docker, and use predefined variables
CI_REGISTRY/CI_REGISTRY_IMAGE/CI_REGISTRY_USER/CI_REGISTRY_PASSWORDto push, without any self-managed credentials. - Use the OIDC identity to run
az acr import, to promote the image from the GitLab Container Registry to ACR, and explain the ACR roles required (including the ABAC repository permission mode). - Compare three approaches: GitLab Registry + import (this lesson), pushing directly to ACR (token exchange),
az acr build(ACR Tasks), and the cost of “pulling directly from the GitLab registry at runtime.”
What: two image registries, each with its own identity
| GitLab Container Registry | Azure Container Registry | |
|---|---|---|
| Address | registry.gitlab.com/mygroup-lab/myapp ($CI_REGISTRY_IMAGE) | acrgitlabNNNNN.azurecr.io/myapp |
| Authentication in CI | $CI_REGISTRY_USER + $CI_REGISTRY_PASSWORD (job token; expires when the job ends) | Entra token (obtained via OIDC) → ACR refresh token |
| Runtime pull (Azure service) | Requires long-lived credentials such as a deploy token | Managed identity + AcrPull, passwordless |
| Network | Public internet | Same region; can use a private endpoint |
| Cost | Counted against GitLab namespace storage | ACR SKU daily rate + storage |
Trade-off in this lesson: Build and retain in GitLab (naturally linked with MRs, pipelines, and vulnerability scanning; the build job needs no Azure permissions),run in Azure (at runtime it pulls from ACR with a managed identity, so GitLab credentials do not need to be placed in Azure). What connects the two is promote-acr in the job, the az acr import command: ACR's server side pulls image layers directly from the GitLab registry; the Runner does not need Docker.
How: the build and promote jobs in this lesson
variables:
IMAGE_TAG: $CI_COMMIT_SHORT_SHA
ACR_NAME: acrgitlab21873 # change to your ACR name (not secret; can be written in YAML)
build-image:
stage: build
image: docker:29.10
services:
- docker:29.10-dind
variables:
DOCKER_TLS_CERTDIR: "/certs"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin
- docker build --pull -t "$CI_REGISTRY_IMAGE:$IMAGE_TAG" .
- docker push "$CI_REGISTRY_IMAGE:$IMAGE_TAG"
- docker inspect --format '{{index .RepoDigests 0}}' "$CI_REGISTRY_IMAGE:$IMAGE_TAG"
promote-acr:
stage: promote
extends: .azure-login # the template includes id_tokens and az login; see the “Commands” tab
variables:
AZURE_CLIENT_ID: $AZURE_CLIENT_ID_BUILD
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- az acr import -n "$ACR_NAME" --source "$CI_REGISTRY_IMAGE:$IMAGE_TAG" --image "myapp:$IMAGE_TAG"
-u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" --force
- az acr repository show -n "$ACR_NAME" --image "myapp:$IMAGE_TAG" --query "{digest:digest, created:createdTime}" -o table
Note: --source When using the full address, ACR accesses the external registry with the username/password provided; $CI_REGISTRY_PASSWORD is the job token, valid only while the job runs; the import completes synchronously, so it is sufficient. --force Re-runs may overwrite a tag with the same name (SHA tags have identical content).
How to choose ACR roles
| Identity | What it needs to do | “RBAC Registry Permissions” mode | “RBAC Registry + ABAC Repository Permissions” mode |
|---|---|---|---|
| id-gitlab-build (promote) | az acr import and read the result | Container Registry Data Importer and Data Reader (same in both modes; ABAC conditions are not supported) | |
| Pipelines that run docker push directly | push and tag | AcrPush | Container Registry Repository Writer (can be scoped with ABAC to myapp repository) |
| App runtime (ACA / AKS kubelet) | Pull | AcrPull | Container Registry Repository Reader |
Use az acr build | run ACR Tasks | Container Registry Tasks Contributor (does not include data-plane permissions) | |
The mode can be checked in the portal under ACR → Properties. Microsoft Learn also notes: az acr login and other control-plane commands require Container Registry Contributor and Data Access Configuration Administrator. An identity that only pulls or pushes does not need it; this is one reason this lesson chooses az acr import, rather than in the job az acr login as one of the reasons.
When: comparing three approaches
| Approach | How | Pros | Cons |
|---|---|---|---|
| (1) GitLab Registry + import (this lesson) | DinD builds and pushes to GitLab; OIDC job az acr import | The build job has no Azure permissions; the image also stays in GitLab for easy scanning and traceability; no need to install az in the Docker image | One extra stage; images stored in two places |
| (2) Push directly to ACR | In the same job: ID token → Entra token → ACR /oauth2/exchange refresh token exchange → docker login | One step | Requires handling token exchange in the DinD job (or installing the az CLI); the build job holds ACR write permissions |
③ az acr build | Upload the build context and let ACR Tasks build it in Azure | The Runner does not need Docker or privileged mode | Builds are billed in Azure; some subscription types may restrict ACR Tasks (see the official documentation) |
| ✗ Pull directly from the GitLab registry at runtime | Configure a deploy token as the registry password in ACA | No ACR needed | Long-lived GitLab credentials are stored in Azure, which violates “keyless”; pulls cross the public internet |
CI_JOB_TOKEN can push to any project's registry” — it can only access this project; cross-project access requires adding it to the job token allowlist. (2) “Using :latest is more convenient” — deployments always use immutable SHA tags or digests. (3) “DinD runs on any Runner” — it requires the Docker executor's privileged = true; GitLab-hosted Linux Runners support this, and a self-managed Runner must have it enabled in config.toml (previous lesson). (4) “AcrPush alone can az acr import” — importing is a control-plane action and requires the Data Importer role.Image flow diagram
Token chain for approach (2) (what happens when pushing directly to ACR)
Image flow animation
Step through how an image in a main pipeline goes from source code to an artifact in ACR that Container Apps can pull; each step shows the real command or API.
Core commands and reusable templates
| Command / variable | Purpose | Notes |
|---|---|---|
$CI_REGISTRY / $CI_REGISTRY_IMAGE | Registry address / image path for this project | registry.gitlab.com / registry.gitlab.com/mygroup-lab/myapp |
$CI_REGISTRY_USER / $CI_REGISTRY_PASSWORD | Job-level registry credentials | Expire when the job ends |
az acr import -n ACR --source REG/IMG:TAG --image IMG:TAG -u U -p P | Server-side import | Requires Data Importer role |
az acr repository show-tags -n ACR --repository myapp --orderby time_desc | View tags | Data-plane read |
az acr manifest list-metadata -r ACR -n myapp | Digest and tag | Compare digests on both sides |
az acr build -r ACR -t myapp:TAG . | ACR Tasks build | Approach (3) |
glab api "projects/$GL_ENC/registry/repositories?tags=true" | GitLab registry contents | Confirm pushed |
Reusable Azure sign-in template (shared by Modules 4–6)
.azure-login:
image: mcr.microsoft.com/azure-cli:2.93.0
id_tokens:
GITLAB_OIDC_TOKEN:
aud: api://AzureADTokenExchange
before_script:
- az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$GITLAB_OIDC_TOKEN" -o none
- az account set --subscription "$AZURE_SUBSCRIPTION_ID"
- echo "Logged in as $(az account show --query user.name -o tsv)"
Verify the digest locally (whether GitLab and ACR hold the same image)
source ~/gitlab-lab.env TAG=$(glab api "projects/$GL_ENC/repository/commits/main" | jq -r .short_id) az acr repository show -n $ACR --image myapp:$TAG --query digest -o tsv glab api "projects/$GL_ENC/registry/repositories?tags=true" | jq -r --arg t "$TAG" '.[0].tags[] | select(.name==$t) | .location'
sha256:77c0e5d8a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c registry.gitlab.com/mygroup-lab/myapp:3f9c2ab1
How to verify: Locally, run docker buildx imagetools inspect registry.gitlab.com/mygroup-lab/myapp:3f9c2ab1 and you should see the same digest. Production use: During an audit, it proves that “the image running in prod is the one the MR pipeline scanned.”
(Advanced) Approach (2): token exchange for pushing directly to ACR from a DinD job
# In a docker:29.10 job (needs apk add curl jq); the identity needs AcrPush; for illustrating the principle only, not used in this lesson's main path AAD=$(curl -s -X POST "https://login.microsoftonline.com/$AZURE_TENANT_ID/oauth2/v2.0/token" \ -d client_id="$AZURE_CLIENT_ID" -d grant_type=client_credentials \ -d scope="https://management.azure.com/.default" \ -d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \ --data-urlencode client_assertion="$GITLAB_OIDC_TOKEN" | jq -r .access_token) RT=$(curl -s -X POST "https://$ACR_NAME.azurecr.io/oauth2/exchange" \ -d grant_type=access_token -d service="$ACR_NAME.azurecr.io" -d tenant="$AZURE_TENANT_ID" \ --data-urlencode access_token="$AAD" | jq -r .refresh_token) echo "$RT" | docker login "$ACR_NAME.azurecr.io" -u 00000000-0000-0000-0000-000000000000 --password-stdin
Endpoints and parameters follow the ACR authentication documentation (AAD-OAuth); if ACR has disabled “authentication-as-arm”, the Entra token scope must change to the ACR-specific audience.
Lab 4: build → GitLab Registry → ACR (about 8 minutes)
Cost: A hosted Runner uses about 3–5 compute minutes; ACR Basic storage is negligible. Permissions: The build identity was already granted the Data Importer role in Module 2.
ci/azure-cd): in .gitlab-ci.yml add at the top stages: [test, build, promote, deploy, verify], global variables (IMAGE_TAG,ACR_NAME,RG: rg-gitlab-lab),.azure-login template, and in the “Concepts” tab, the build-image and promote-acr jobs; delete the Module 2 oidc-smoke.
cd ~/myapp && git switch -c ci/azure-cd # After editing .gitlab-ci.yml: glab ci lint git add .gitlab-ci.yml && git commit -m "ci: build once, promote to ACR via OIDC" git push -u origin HEAD && glab mr create --fill --yes
Validating... ✓ CI/CD YAML is valid!
glab ci view should not show build / promote (their rules only match the default branch).glab mr merge --squash --remove-source-branch --yes glab ci status --live --branch main
$ az acr import -n "$ACR_NAME" --source "$CI_REGISTRY_IMAGE:$IMAGE_TAG" --image "myapp:$IMAGE_TAG" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" --force
$ az acr repository show -n "$ACR_NAME" --image "myapp:$IMAGE_TAG" --query "{digest:digest, created:createdTime}" -o table
Digest Created
----------------------------------------------------------------------- ----------------------------
sha256:77c0e5d8a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c 2026-11-16T15:02:11.4171Z
Job succeededaz acr build -r $ACR -t myapp:local-test . (requires the Tasks role), then az acr repository delete -n $ACR --image myapp:local-test --yes clean up.Case 1: Security scan and running image do not match
Problem: Container scanning in GitLab runs against the :main tag, but deployment builds separately in Azure. Audits cannot prove that the running image was scanned. Solution: Switch to approach (1): build and scan in GitLab :SHA,az acr import import it unchanged, and record the digest in the deployment record. Limitation: Images are stored in two places; the GitLab registry needs a cleanup policy to control storage.
Case 2: Self-managed Runner does not allow privileged mode
Problem: The security baseline prohibits privileged = true, so DinD cannot run. Solution: Switch to az acr build (builds run in ACR Tasks), or use a daemonless build tool on the Runner (follow GitLab's documentation recommendations). Limitation: ACR Tasks bills by build duration; build logs are in Azure.
Case 3: Pulls fail after ACR enables ABAC repository permissions
Problem: The newly created ACR uses the “RBAC Registry + ABAC Repository Permissions” mode; the Container Apps system identity has only AcrPull, so revision startup reports that image pull is unauthorized. Solution: Instead, grant Container Registry Repository Reader (you can add a condition to allow only myapp repository). Limitation: Roles do not carry over between the two modes; team documentation should clearly state which mode the ACR uses.
Common errors
(AuthorizationFailed) … does not have authorization to perform action 'Microsoft.ContainerRegistry/registries/importImage/action'
Cause: The build identity has only AcrPush (data plane), but import is a control-plane action.
az role assignment list --assignee $(az identity show -g $RG -n id-gitlab-build --query principalId -o tsv) --all -o table
Fix: Grant Container Registry Data Importer and Data Reader (scoped to the ACR), then wait a few minutes and rerun.
(InvalidParameters) … Unauthorized / 401 when accessing registry.gitlab.com during az acr import
Cause: Not passing -u/-p, the credential variables are empty, or the job token has expired (for example, reused in another job).
Fix: Use it within the same job $CI_REGISTRY_USER / $CI_REGISTRY_PASSWORD; confirm the project has the Container Registry enabled and the image actually exists.
error during connect: Get "http://docker:2375/v1.xx/info": dial tcp: lookup docker … no such host
Cause: No services: docker:29.10-dind, or TLS settings are inconsistent (2375/2376).
Fix: Add the service and set DOCKER_TLS_CERTDIR: "/certs"; a self-managed Runner needs privileged = true.
MANIFEST_UNKNOWN: manifest tagged by "3f9c2ab1" is not found
Cause: A tag that does not exist in ACR was deployed: for example, the commit the tag pipeline points to was never built on main (the tag was created on a feature branch).
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 5 -o tsv
Fix: Only create release tags on commits on main; or have the prod pipeline check that the image exists before deploying.
1. Import myapp:1.1 from the GitLab registry into ACR (run in a job).
az acr import -n "$ACR_NAME" --source "$CI_REGISTRY_IMAGE:1.1" --image myapp:1.1 -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
2. List the 5 most recent tags for myapp in ACR.
az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 5 -o table
The team wants to merge build and promote into one job to save time. What would the impact be, and how would you weigh it?
After merging, that job needs both Docker (DinD/privileged) and an Azure identity: you would need to install az in the Docker image or do the token exchange yourself (approach (2)), and the build stage would hold ACR write permissions from the start. Anything that can affect the build process (dependencies, scripts in the Dockerfile) would then run in an environment that holds an Azure token. The benefit of keeping them separate is that the build job has zero cloud permissions, and the promote job runs only a single import command. If speed is the priority, you can keep them separate but chain promote and deploy-dev using needs to chain them together and reduce waiting time.
Verified training videos
Official documentation
- GitLab Docs: Container registry
- GitLab Docs: Use Docker to build Docker images
- Microsoft Learn: Import container images to a container registry
- Microsoft Learn: ACR Entra permissions and role assignments overview
Video storyboard script (about 70 seconds)
This courseware cannot generate a video or MP3 directly, so a storyboard and narration script are provided.
Visual: in the DinD job, image layers stack up one by one and are pushed to the GitLab registry, tagged with the commit SHA.
Narration: the build happens only once. The job pushes with the job token that GitLab provides automatically; the build job needs no Azure permissions.
Visual: the promote job sends one ARM request, and ACR reaches out and pulls the image layers directly from the GitLab registry.
Narration: after signing in with OIDC, the promote job runs az acr import; the image is transferred between servers, and the digest stays the same.
Visual: three role cards: Data Importer, AcrPull, Repository Reader.
Narration: import requires the Data Importer role, and runtime pulls require AcrPull; if ACR has ABAC repository permissions enabled, the pull role must be changed to Repository Reader.
Module 5 · Deploy to Azure Container Apps
- Write a complete
.gitlab-ci.yml: test → build → promote → deploy-dev → verify-dev; the tag pipeline runs deploy-prod → verify-prod → release-traffic. - Understand Container Apps revisions, single/multiple revision modes, and traffic weights; use
--revision-suffixto make revision names traceable to the pipeline. - Use a dotenv artifact to write the runtime FQDN back as the environment URL; use
environment:action: verifysmoke-test job to include health checks in the deployment flow.
What: revisions and traffic
Every change to a Container Apps template (image, environment variables, resources, revision suffix, etc.) generates a new immutable revision. Single revision mode (Single): once the new revision is ready, it automatically takes all traffic, and the old revision is deactivated; Multiple revision mode (Multiple): multiple revisions are active at once, and traffic is split according to the traffic weights configured in ingress; each revision also has its own FQDN (<app>--<suffix>.<environment domain>), which can be accessed directly at 0% traffic for smoke testing.
| myapp-dev (Single) | myapp-prod (Multiple) | |
|---|---|---|
| Trigger | Merge to main | Protected tag v*,when: manual (+ Premium approval) |
| Deployment command | az containerapp update --image … --revision-suffix … | Same as left; traffic was previously pinned to the old revision, so the new revision gets 0% |
| Verification | Smoke test the app FQDN's /healthz | smoke test the new revision's FQDN's /healthz |
| go live | automatically | az containerapp ingress traffic set --revision-weight NEW=100 (can start at 10%) |
| Rollback | Redeploy the previous SHA (“Rollback” on the environment page) | Shift traffic back to the old revision (within seconds), then deactivate the new revision |
How: the complete pipeline (final version for this lesson)
stages: [test, build, promote, deploy, verify]
variables:
IMAGE_TAG: $CI_COMMIT_SHORT_SHA
ACR_NAME: acrgitlab21873 # change to your
RG: rg-gitlab-lab
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/
.azure-login:
image: mcr.microsoft.com/azure-cli:2.93.0
id_tokens:
GITLAB_OIDC_TOKEN:
aud: api://AzureADTokenExchange
before_script:
- az login --service-principal -u "$AZURE_CLIENT_ID" -t "$AZURE_TENANT_ID" --federated-token "$GITLAB_OIDC_TOKEN" -o none
- az account set --subscription "$AZURE_SUBSCRIPTION_ID"
- az extension add --name containerapp --upgrade --only-show-errors
test:
stage: test
image: python:3.13-slim
rules:
- if: $CI_COMMIT_TAG == null
script:
- pip install -q -r requirements.txt pytest
- pytest -q
# build-image and promote-acr: see Module 4 (rules only match the default branch)
deploy-dev:
stage: deploy
extends: .azure-login
environment: { name: dev, deployment_tier: development, url: $DYNAMIC_URL }
resource_group: dev
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- az containerapp update -g "$RG" -n myapp-dev --image "$ACR_NAME.azurecr.io/myapp:$IMAGE_TAG"
--revision-suffix "p$CI_PIPELINE_IID" -o none
- az containerapp ingress update -g "$RG" -n myapp-dev --target-port 5000 -o none
- echo "DYNAMIC_URL=https://$(az containerapp show -g "$RG" -n myapp-dev --query properties.configuration.ingress.fqdn -o tsv)" >> deploy.env
artifacts:
reports:
dotenv: deploy.env
verify-dev:
stage: verify
image: alpine:3.22
needs: [deploy-dev]
environment: { name: dev, action: verify }
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
script:
- apk add --no-cache curl >/dev/null
- curl -fsS --retry 10 --retry-delay 6 --retry-all-errors "$DYNAMIC_URL/healthz"
deploy-prod:
stage: deploy
extends: .azure-login
environment: { name: prod, deployment_tier: production, url: $DYNAMIC_URL }
resource_group: prod
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/
when: manual
script:
- SUFFIX=$(echo "$CI_COMMIT_TAG" | tr '.' '-') # v1.1 → v1-1
- OLD=$(az containerapp revision list -g "$RG" -n myapp-prod
--query "[?properties.trafficWeight==\`100\`].name | [0]" -o tsv)
- az containerapp ingress traffic set -g "$RG" -n myapp-prod --revision-weight "$OLD=100" -o none
- az containerapp update -g "$RG" -n myapp-prod --image "$ACR_NAME.azurecr.io/myapp:$IMAGE_TAG"
--revision-suffix "$SUFFIX" -o none
- NEW="myapp-prod--$SUFFIX"
- FQDN=$(az containerapp revision show -g "$RG" -n myapp-prod --revision "$NEW" --query properties.fqdn -o tsv)
- printf 'OLD_REV=%s\nNEW_REV=%s\nREV_URL=https://%s\nDYNAMIC_URL=https://%s\n' "$OLD" "$NEW" "$FQDN"
"$(az containerapp show -g "$RG" -n myapp-prod --query properties.configuration.ingress.fqdn -o tsv)" > deploy.env
artifacts:
reports:
dotenv: deploy.env
verify-prod:
stage: verify
image: alpine:3.22
needs: [deploy-prod]
environment: { name: prod, action: verify }
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/
script:
- apk add --no-cache curl >/dev/null
- curl -fsS --retry 10 --retry-delay 6 --retry-all-errors "$REV_URL/healthz"
release-traffic:
stage: verify
extends: .azure-login
needs: [deploy-prod, verify-prod]
environment: { name: prod, action: access }
resource_group: prod
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/
script:
- az containerapp ingress traffic set -g "$RG" -n myapp-prod --revision-weight "$NEW_REV=100" "$OLD_REV=0" -o none
- az containerapp revision deactivate -g "$RG" -n myapp-prod --revision "$OLD_REV" -o none || true
Key points: (1) deploy-prod first pin traffic to the current revision so that the new revision gets 0%; (2) the new revision suffix comes from the tag, so the revision name myapp-prod--v1-1 can be traced directly to the release; (3) verify-prod the smoke test accesses the new revision's own FQDN; (4) if the smoke test fails, release-traffic does not run, and user traffic stays on the old revision — this is the “automatic rollback”; (5) release-traffic also uses the prod identity (tag pipeline, prod environment-scoped variables). action: access does not create a new deployment record.
Why: why prod does not use Single mode
In Single mode, once the new revision passes Container Apps' own health probes, it takes all traffic, so your business-level smoke test happens “after it is already live.” Multiple mode splits “deployment” and “traffic shifting” into two steps, with any verification you want in between (smoke test, manual check, approval).
When: phased traffic rollout
- Low risk: 0% → smoke test → 100% (this lesson).
- Medium risk: 0% → smoke test → 10% (watch the error rate for 15 minutes) → 100%: split
release-trafficinto two jobs, with the second onewhen: manual. - To “test the new version in production with real requests”: add a revision label (
az containerapp revision label add), accessed through the label URL.
update the new revision automatically gets 0% after deployment” — this holds only when traffic is explicitly assigned to specific revisions; if traffic is configured as latestRevision=true, the new revision receives traffic directly, so you must first “pin” the old revision. (2) “Revision suffixes can be anything” — they must be lowercase letters, digits, and hyphens, and must be unique within the same app (rerunning the deployment for the same tag fails on a suffix conflict; see Troubleshooting). (3) “The rollback button on the environment page can switch ACA traffic” — it reruns the old deployment job; a second-level rollback at the ACA level is a traffic switch.Pipeline diagram: two pipelines, same image
Traffic diagram: three moments for the prod revision
Revision and traffic switching animation
Choose “Smoke test passed” or “Smoke test failed” and step through how Container Apps revisions and traffic change during a prod release, along with the CLI / ARM operation for each step.
Core commands
| Command | Purpose | Key parameters / notes |
|---|---|---|
az containerapp update -g RG -n APP --image IMG --revision-suffix S | Deploy a new revision | Suffix: lowercase letters, digits, and -, unique within the app |
az containerapp ingress update -g RG -n APP --target-port 5000 | Change target port | First switch from the sample image (80) to myapp (5000) |
az containerapp revision list -g RG -n APP -o table | Revisions, status, traffic | Add --all to show deactivated revisions |
az containerapp revision show -g RG -n APP --revision R --query properties.fqdn | The revision's own FQDN | Used for smoke testing in multiple revision mode |
az containerapp ingress traffic set -g RG -n APP --revision-weight A=90 B=10 | Set traffic | weights must sum to 100; latest=100 denotes following the latest |
az containerapp revision activate | deactivate --revision R | Activate/deactivate revision | Activate first before rolling back to a deactivated revision |
az containerapp logs show -g RG -n APP --revision R --tail 50 | Console logs | Troubleshoot startup failures |
source ~/gitlab-lab.env
az containerapp revision list -g $RG -n $APP_PROD \
--query "[].{rev:name, active:properties.active, weight:properties.trafficWeight, health:properties.healthState, image:properties.template.containers[0].image}" -o table
Rev Active Weight Health Image ---------------- -------- -------- -------- ------------------------------------------ myapp-prod--v1-0 True 100 Healthy acrgitlab21873.azurecr.io/myapp:1a2b3c4d myapp-prod--v1-1 True 0 Healthy acrgitlab21873.azurecr.io/myapp:3f9c2ab1
Manual rollback (problem found after T2)
az containerapp revision activate -g $RG -n $APP_PROD --revision myapp-prod--v1-0 az containerapp ingress traffic set -g $RG -n $APP_PROD --revision-weight myapp-prod--v1-0=100 myapp-prod--v1-1=0 curl -fsS https://$(az containerapp show -g $RG -n $APP_PROD --query properties.configuration.ingress.fqdn -o tsv)/healthz
{"status":"ok"}
Common errors: Running on a Single-mode app traffic set is rejected; setting weights fails when the revision is deactivated — activate it first. Production use: Put the rollback commands in the runbook and record them on the GitLab environment page (rerunning deploy-prod for an old tag can also roll back, but more slowly).
Lab 5: automatic dev deployment, prod tag release + canary (about 10 minutes)
Cost: Container Apps Consumption minimum replicas 0; lab traffic usually stays within the free allowance; the hosted Runner uses about 6–10 compute minutes. Risk: myapp's Redis dependency — if /healthz the health check looks for Redis but the environment has no Redis, the smoke test will fail; you can first point REDIS_HOST to the Redis from the Docker lesson, or make /healthz only check that the process is alive (depending on your myapp implementation).
.gitlab-ci.yml, merged to main via MR.
glab ci lint && git commit -am "ci: deploy to ACA dev/prod" && git push glab mr create --fill --yes && glab mr merge --squash --remove-source-branch --yes
verify-dev passes.
glab ci status --branch main
az containerapp show -g $RG -n $APP_DEV --query "{image:properties.template.containers[0].image, rev:properties.latestRevisionName}" -o table
Image Rev ------------------------------------------ ------------------ acrgitlab21873.azurecr.io/myapp:3f9c2ab1 myapp-dev--p42
git switch main && git pull git tag -a v1.0 -m "myapp 1.0" && git push origin v1.0 glab ci status --branch v1.0
In the tag pipeline, click deploy-prod the ▶ button; with Premium and approvals configured, have another Maintainer approve first, then click run again. For the first release, the old revision is the sample-image revision; the process is the same.
az containerapp ingress update -g $RG -n $APP_PROD --target-port 5000 (the sample revision becomes unavailable immediately, which is expected). Afterwards the release port no longer changes, so the canary flow is completely seamless.v1.1; in release-traffic before running it, run the revision list command from the “Commands” tab, and you should see v1-1 at 0%./healthz return 503, merge, and tag v1.2: verify-prod fails,release-traffic does not run, and prod traffic stays on v1-1. Then revert that commit and tag v1.3.
$ curl -fsS --retry 10 --retry-delay 6 --retry-all-errors "$REV_URL/healthz" curl: (22) The requested URL returned error: 503 ERROR: Job failed: exit code 22
Cleanup: Deactivate the failed revision az containerapp revision deactivate -g $RG -n $APP_PROD --revision myapp-prod--v1-2.
Case 1: A “healthy but buggy” version goes live directly in Single mode
Problem: The new version /healthz appears healthy, but the order API returns 500; in Single mode, the revision takes all traffic as soon as it is ready. Solution: Change prod to Multiple; the smoke test covers key business APIs (read-only); traffic shifts in two steps, 10% → 100%, with manual confirmation in between. Limitation: Two revisions run at the same time, so costs briefly double; stateful database migrations must be backward compatible (expand/contract).
Case 2: Rerunning the deployment for the same tag fails
Problem: Approval was delayed, and rerunning deploy-prod reports that the revision suffix already exists. Solution: Change the suffix to ${SUFFIX}-p$CI_PIPELINE_IID, or check at the start of the job whether the revision already exists and skip the update. Limitation: Revision names become longer, but they remain traceable.
Case 3: Pipeline identity has excessive permissions
Problem: To save effort, the prod identity was granted Contributor on the resource group, and a faulty script deleted the Log Analytics workspace. Solution: Grant Contributor only at myapp-prod scope; when environment-level operations are needed, grant the minimum required action separately. Limitation: Initial app creation and other infrastructure changes are handled by the IaC pipeline (a separate identity).
Common errors
(AuthorizationFailed) … does not have authorization to perform action 'Microsoft.App/managedEnvironments/join/action' over scope '…/managedEnvironments/cae-gitlab-lab'
Cause: When updating a container app, ARM checks join permission on the environment it belongs to, but the identity has Contributor only at the app scope.
CAE_ID=$(az containerapp env show -g $RG -n $CAE --query id -o tsv) az role assignment create --assignee-object-id $(az identity show -g $RG -n id-gitlab-prod --query principalId -o tsv) \ --assignee-principal-type ServicePrincipal --role Contributor --scope $CAE_ID
Smaller permissions: Create a custom role that contains only Microsoft.App/managedEnvironments/join/action and read permissions, and grant it at the environment scope.
Revision with suffix 'v1-1' already exists / revision name conflict
Cause: The deployment job for the same tag was rerun, so the revision suffix is duplicated.
Fix: Add the pipeline IID to the suffix; or, if it already exists, only perform the traffic operations.
New revision ProvisioningState=Failed; log: Container 'myapp' … failed to pull image … unauthorized
Cause: The app's system identity does not have AcrPull (or Repository Reader in ABAC mode), or registry set the registry identity is not set up --identity system.
az containerapp show -g $RG -n $APP_PROD --query "properties.configuration.registries" -o json az role assignment list --assignee $(az containerapp show -g $RG -n $APP_PROD --query identity.principalId -o tsv) --all -o table
Fix: Grant the pull role, wait a few minutes, and then reactivate the revision.
curl: (22) The requested URL returned error: 404 / 502 — the new revision stays unhealthy
Cause: The target port is still 80 from the sample image, but gunicorn listens on 5000; or gunicorn is bound to 127.0.0.1.
az containerapp show -g $RG -n $APP_PROD --query properties.configuration.ingress.targetPort az containerapp logs show -g $RG -n $APP_PROD --revision myapp-prod--v1-1 --tail 50
Fix:--target-port 5000; bind gunicorn to 0.0.0.0:5000.
1. Set the traffic for myapp-prod so that v1-1 gets 10% and v1-0 gets 90%.
az containerapp ingress traffic set -g rg-gitlab-lab -n myapp-prod --revision-weight myapp-prod--v1-0=90 myapp-prod--v1-1=10
2. Find the FQDN of the new revision myapp-prod--v1-1 and request /healthz.
curl -fsS "https://$(az containerapp revision show -g rg-gitlab-lab -n myapp-prod --revision myapp-prod--v1-1 --query properties.fqdn -o tsv)/healthz"
The product requirement is: “Give the new version to 10% of users for 30 minutes; if there are no issues, roll out to everyone; if there are problems, roll back within 1 minute.” Modify this lesson's pipeline.
Split release-traffic into two jobs: canary-10 (automatic, set new=10 / old=90) and promote-100 (when: manual, Premium can also add protected-environment approval); both use resource_group: prod. During the observation period, check Container Apps metrics/logs (error rate, latency). The rollback job rollback (manual) runs old=100 / new=0. Because the old revision is still active during the 10% phase, rollback is just one ARM call and completes within seconds. You can also use start_in: 30 minutes 's delayed job to shift traffic automatically (when: delayed), but pair it with automated metric checks.
Verified teaching videos
Official docs
- Microsoft Learn: Update and deploy changes in Azure Container Apps (Revisions)
- Microsoft Learn: Traffic splitting in Azure Container Apps
- Microsoft Learn: Azure Container Apps image pull with managed identity
- GitLab Docs: artifacts:reports (dotenv)
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3 files, so a storyboard and narration script are provided instead.
Visual: after merging to main, the dev revision is automatically replaced and the health check turns green.
Narration: dev uses single-revision mode, so merging deploys immediately; then a verify job hits healthz as a smoke test.
Visual: tag v1.1 is pushed and the prod deploy button is clicked; a new revision appears, and the traffic bar is still at 100% on the old revision.
Narration: prod uses multiple-revision mode. Before deploying, traffic is pinned to the old revision; the new revision gets zero traffic but has its own address.
Visual: the smoke job hits the new revision's address and turns green; the traffic bar slides from left to right.
Narration: the smoke test passes and release-traffic shifts traffic to the new revision. If it fails, this step never runs.
Visual: red alert; one command slides the traffic bar back to the old revision.
Narration: found a problem only after going live? One traffic switch, rollback in seconds.
Module 6 · Deploying to AKS (GitLab agent for Kubernetes) and App Service
- Explain the components of the GitLab agent: the in-cluster agentk component that actively connects to GitLab's KAS (GitLab.com:
wss://kas.gitlab.com/grpcs://kas.gitlab.com), CI job'skubectlrequests are forwarded through the KAS tunnel to the API server. - It registers the agent, installs it with Helm, and in
.gitlab/agents/<name>/config.yamlusesci_accessto authorize projects/groups and restrict environments, and in jobskubectl config use-context path/to/agent/project:agent-name. - Know that the default permissions match those of the service account that installed the agent, and can use
access_as: ci_job(Premium) to tighten them; understand how App Service container deployment and slot swaps are written in GitLab.
What: GitLab agent for Kubernetes
The agent has two parts: the in-cluster agentk (Helm chart gitlab/gitlab-agent) and the GitLab-side KAS (Kubernetes Agent Server). agentk uses the agent token generated at registration to actively open a long-lived connection to KAS. The cluster does not need any inbound ports, and the API server can be fully private. The agent supports two workflows:
| CI/CD workflow (this module) | GitOps workflow (Flux) | |
|---|---|---|
| Model | Push-based: job runs kubectl / Helm, via the KAS tunnel | Pull-based: Flux reconciles Git / OCI inside the cluster |
| Configuration | In the agent configuration file, the ci_access | glab cluster agent bootstrap (the officially recommended install method, which also bootstraps Flux) |
| Permissions | By default, inherits all permissions of the agent's service account; they can be tightened with impersonation | Flux controller permissions |
| Tier | Free (emulating Premium) | Free |
How: configuration and usage
# File: .gitlab/agents/aks-lab/config.yaml on the default branch of mygroup-lab/myapp
ci_access:
projects:
- id: mygroup-lab/myapp
environments: # Only jobs in these environments may use the agent (supports * wildcards, such as review/*)
- dev-aks
# protected_branches_only: true # The docs note this option is not yet production-ready
# access_as:
# ci_job: {} # Premium: impersonate the job identity, combined with RBAC to tighten
- Register: Operate → Kubernetes clusters → Connect a cluster (agent) → enter a name
aks-lab→ Create and register, get the agent token (shown only once). - Install:
helm upgrade --install aks-lab gitlab/gitlab-agent --namespace gitlab-agent-aks-lab --create-namespace --set config.token=… --set config.kasAddress=wss://kas.gitlab.com. - Authorize:
ci_access.projects/ci_access.groups, up to 500 each; configuration changes take effect in 1–2 minutes. - Use: After authorization, GitLab injects
KUBECONFIG, one context per available agent, named<agent config project path>:<agent name>, and in this lesson it ismygroup-lab/myapp:aks-lab. In jobs, usekubectl config get-contextsto view. - Environment association:
environment:kubernetes:agent: mygroup-lab/myapp:aks-lab(17.6+), the environment page can display Kubernetes resource status;dashboard:namespace/dashboard:flux_resource_pathis the new syntax starting from 18.4.
deploy-aks:
stage: deploy
image: alpine:3.22
environment:
name: dev-aks
deployment_tier: development
kubernetes:
agent: mygroup-lab/myapp:aks-lab
resource_group: dev-aks
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
when: manual # Optional module, triggered manually
script:
- apk add --no-cache curl >/dev/null
- curl -fsSLo /usr/local/bin/kubectl "https://dl.k8s.io/release/$(curl -fsSL https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"
- chmod +x /usr/local/bin/kubectl
- kubectl config get-contexts
- kubectl config use-context mygroup-lab/myapp:aks-lab
- kubectl -n myapp set image deployment/myapp myapp="$ACR_NAME.azurecr.io/myapp:$IMAGE_TAG"
- kubectl -n myapp annotate deployment/myapp kubernetes.io/change-cause="pipeline $CI_PIPELINE_ID $CI_COMMIT_SHORT_SHA" --overwrite
- kubectl -n myapp rollout status deployment/myapp --timeout=180s
Note that this job has no id_tokens, no Azure login: access to the cluster is determined entirely by the agent. AKS nodes pull ACR images through the AcrPull role on the kubelet identity (az aks create/update --attach-acr).
agent approach vs OIDC + az aks
| GitLab agent (CI/CD workflow) | OIDC login to Azure + az aks get-credentials + kubelogin | |
|---|---|---|
| Credentials in the pipeline | None (injected by GitLab, job-level) | ID token exchanged for Azure token |
| API server networking | Can be private; agentk connects outbound | Runner must be able to reach the API server (public or private Runner) |
| Authorization | Kubernetes RBAC for the agent SA or impersonated identity | Azure RBAC for Kubernetes or Kubernetes RBAC (Entra groups) |
| Requires installing in cluster | agentk | None |
| Best for | Private clusters, multi-project shared clusters | No components to install in the cluster; existing Azure RBAC setup |
App Service (containers) + deployment slots
App Service “warm up then swap”: first deploy the new image to the staging slot, and after the smoke test passes, run a slot swap, with no production downtime; rollback = swap again. Deployment slots require the Standard tier or higher (Basic has no slots; see the official pricing page). Container configuration: enable a managed identity on the app (and on each slot) and grant it AcrPull, and set acrUseManagedIdentityCreds=true, with the port set via app settings WEBSITES_PORT=5000 to tell the platform.
deploy-webapp:
stage: deploy
extends: .azure-login
environment: { name: prod-webapp, deployment_tier: production }
resource_group: prod-webapp
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/
when: manual
script:
- az webapp config container set -g "$RG" -n "$WEB" --slot staging
--container-image-name "$ACR_NAME.azurecr.io/myapp:$IMAGE_TAG" -o none
- HOST=$(az webapp show -g "$RG" -n "$WEB" --slot staging --query defaultHostName -o tsv)
- for i in $(seq 1 20); do curl -fsS "https://$HOST/healthz" && break; sleep 6; done
- az webapp deployment slot swap -g "$RG" -n "$WEB" --slot staging --target-slot production
Whether the azure-cli image includes curl ; check the image's actual contents. If it doesn't, split the smoke test into a separate alpine:3.22 job (same as module 5). The OIDC identity for prod-webapp likewise trusts only v* tags, and grants Website Contributor only at the scope of that web app.
When
- Existing AKS, private cluster, multiple projects to deploy → agent; for production-critical services, further use Flux GitOps.
- Only one project, cluster publicly reachable, team familiar with Azure RBAC → OIDC +
az aks get-credentialsalso works. - Traditional web app, needs built-in authentication and slots → App Service.
config project path:agent name. ③ “The legacy certificate-based cluster integration still works”—GitLab has moved to the agent; the old integration is deprecated, so do not use it in new projects. ④ “App Service can scale to 0”—no, the plan is billed continuously.Architecture diagram: network path of the agent CI/CD workflow
App Service slot swap
agent tunnel animation: one kubectl set image request's journey
Choose an agent configuration and step through each stage of the request as it passes through KAS and agentk, and see at which step it is rejected.
Core commands
| Command | Purpose | Notes |
|---|---|---|
glab api -X POST "projects/$GL_ENC/cluster_agents" -f name=aks-lab | Register agent (API) | Can also be done in the UI |
glab api -X POST "projects/$GL_ENC/cluster_agents/ID/tokens" -f name=aks-lab-token | Create agent token | The returned token is returned only once |
helm upgrade --install aks-lab gitlab/gitlab-agent … --set config.kasAddress=wss://kas.gitlab.com | Install agentk | can add --set image.tag= to pin a version |
glab cluster agent list | List agents | Checking connection status can also be done in the UI |
glab cluster agent bootstrap NAME | Bootstrap the agent with Flux | GitOps workflow (officially recommended install method) |
kubectl config get-contexts (in a job) | List available agent contexts | Name project path:agent name |
az aks update -g RG -n AKS --attach-acr ACR | kubelet gets AcrPull | Requires permission to assign roles |
az webapp deployment slot swap -g RG -n WEB --slot staging --target-slot production | Slot swap | Roll back by running it again |
source ~/gitlab-lab.env AGENT_ID=$(glab api -X POST "projects/$GL_ENC/cluster_agents" -f name=aks-lab | jq -r .id) AGENT_TOKEN=$(glab api -X POST "projects/$GL_ENC/cluster_agents/$AGENT_ID/tokens" -f name=aks-lab-token | jq -r .token) helm repo add gitlab https://charts.gitlab.io && helm repo update helm upgrade --install aks-lab gitlab/gitlab-agent \ --namespace gitlab-agent-aks-lab --create-namespace \ --set config.token="$AGENT_TOKEN" \ --set config.kasAddress=wss://kas.gitlab.com unset AGENT_TOKEN kubectl -n gitlab-agent-aks-lab get pods
NAME READY STATUS RESTARTS AGE aks-lab-gitlab-agent-v2-6d9f8c7b5-7xk2p 1/1 Running 0 40s aks-lab-gitlab-agent-v2-6d9f8c7b5-q4w8n 1/1 Running 0 40s
How to verify: In Operate → Kubernetes clusters, aks-lab shows Connected. Common mistakes: Writing the token into shell history or a repository—pass it in via a variable and immediately unset; if a token leaks, revoke and recreate it in the UI. Pod names depend on the actual chart version.
Lab 6 (optional, incurs AKS costs): AKS + GitLab agent
Cost: The AKS Free tier control plane is free, but node VMs, disks, and load balancers are billed hourly (a small single-node setup costs a few US dollars per day; check the Azure pricing calculator for accurate figures). Permissions: Resource group Owner (--attach-acr requires role assignment). Run the step 6 cleanup immediately after finishing.
source ~/gitlab-lab.env az aks create -g $RG -n aks-gitlab-lab -l $LOC --tier free --node-count 1 \ --node-vm-size Standard_D2s_v5 --attach-acr $ACR --generate-ssh-keys -o none # VM size depends on regional availability and quota az aks get-credentials -g $RG -n aks-gitlab-lab --overwrite-existing kubectl get nodes
kubectl create namespace myapp kubectl -n myapp create deployment myapp --image=$ACR.azurecr.io/myapp:$(az acr repository show-tags -n $ACR --repository myapp --orderby time_desc --top 1 -o tsv) --port=5000 kubectl -n myapp expose deployment myapp --port 80 --target-port 5000 kubectl -n myapp rollout status deployment/myapp
.gitlab/agents/aks-lab/config.yaml (content from the “Theory” tab) to main.myapp a namespace's edit role, and refer to the chart documentation to disable the default cluster-wide binding (see chart values); Premium can use access_as: ci_job: {} + RoleBinding for the group gitlab:ci_job.deploy-aks job to the pipeline. After merging, run it manually in the main pipeline.
$ kubectl config get-contexts
CURRENT NAME CLUSTER AUTHINFO NAMESPACE
mygroup-lab/myapp:aks-lab gitlab agent:12345
$ kubectl config use-context mygroup-lab/myapp:aks-lab
Switched to context "mygroup-lab/myapp:aks-lab".
$ kubectl -n myapp set image deployment/myapp myapp="acrgitlab21873.azurecr.io/myapp:3f9c2ab1"
deployment.apps/myapp image updated
$ kubectl -n myapp rollout status deployment/myapp --timeout=180s
deployment "myapp" successfully rolled outhelm uninstall aks-lab -n gitlab-agent-aks-lab az aks delete -g $RG -n aks-gitlab-lab --yes --no-wait glab api -X DELETE "projects/$GL_ENC/cluster_agents/$AGENT_ID" git rm -r .gitlab/agents/aks-lab && git commit -m "chore: remove lab agent" && git push
App Service snippet (not created by default)
source ~/gitlab-lab.env
WEB=web-gitlab-lab-$RANDOM
az appservice plan create -g $RG -n asp-gitlab-lab --is-linux --sku S1 -o none # Slots require Standard or higher
az webapp create -g $RG -p asp-gitlab-lab -n $WEB --container-image-name mcr.microsoft.com/k8se/quickstart:latest -o none
az webapp deployment slot create -g $RG -n $WEB --slot staging -o none
for S in "" "--slot staging"; do
PID=$(az webapp identity assign -g $RG -n $WEB $S --query principalId -o tsv)
az role assignment create --assignee-object-id $PID --assignee-principal-type ServicePrincipal --role AcrPull --scope $(az acr show -n $ACR --query id -o tsv) -o none
az webapp config set -g $RG -n $WEB $S --generic-configurations '{"acrUseManagedIdentityCreds": true}' -o none
az webapp config appsettings set -g $RG -n $WEB $S --settings WEBSITES_PORT=5000 -o none
done
Cleanup: az webapp delete -g $RG -n $WEB and az appservice plan delete -g $RG -n asp-gitlab-lab --yes (or delete along with the resource group).
Case 1: private AKS, Runner cannot reach the API server
Problem: After enabling a private cluster, all kubectl calls on hosted Runners time out. Approach: Install the GitLab agent and switch jobs to the agent context; agentk only needs outbound access to kas.gitlab.com (443). Limitations: The outbound firewall must allow KAS; the agent itself must be included in cluster upgrades and monitoring.
Case 2: every project can delete any namespace
Problem: The platform agent was installed with default permissions,ci_access.groups and authorization covered the entire top-level group; a cleanup script in one project accidentally deleted another team's namespace. Approach: (Premium) access_as: ci_job: {}, use RoleBinding per project/environment to grant access only within each namespace; on the Free tier, deploy different agents for different teams, each bound to namespace-scoped roles. Limitations: The RBAC design must be maintained by the platform team.
Case 3: after an App Service slot swap, the app connected to the staging database
Problem: The connection string was not marked as a “slot setting”, so during the swap it moved to production along with the code. Approach: Environment-specific settings (connection strings,WEBSITES_PORT , etc.) set as slot settings (--slot-settings), so they do not move during the swap. Limitations: The swap restarts some instances in the target slot, so health checks and warm-up must be configured.
Common errors
error: no context exists with the name: "mygroup-lab/myapp:aks-lab"
Cause: The project is not listed in ci_access authorization; the configuration file is not on the default branch or has the wrong path (it must be .gitlab/agents/<agent name>/config.yaml); the job environment is not in environments list; the configuration was just changed and has not taken effect yet (1–2 minutes).
kubectl config get-contexts # Run in a job to see the contexts actually available
Fix: Correct the configuration and wait for it to take effect; confirm the context name is “config project path:agent name”.
Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "gitlab:ci_job:…" cannot patch resource "deployments"
Cause: Enabled access_as: ci_job, but no RoleBinding was created for the group the impersonated identity belongs to.
kubectl -n myapp create rolebinding gitlab-ci-edit --clusterrole=edit --group=gitlab:ci_job
Fix: Bind at the smallest necessary scope (example uses the entire gitlab:ci_job group; in production, break this down by project/environment; check the official docs for the exact group name).
Unable to connect to the server: … / the agent shows Not connected in the UI
Cause: The agentk Pod is not running, the token was revoked, or outbound traffic to kas.gitlab.com is blocked.
kubectl -n gitlab-agent-aks-lab get pods kubectl -n gitlab-agent-aks-lab logs deploy/aks-lab-gitlab-agent-v2 --tail 50 # Name depends on the actual deployment
Fix: Fix the network or regenerate the token and helm upgrade --set config.token=….
Pod ErrImagePull … 401 Unauthorized (AKS)
Cause: The kubelet identity does not have AcrPull (not --attach-acr), or ACR is in ABAC mode.
az aks check-acr -g $RG -n aks-gitlab-lab --acr $ACR.azurecr.io
Fix:az aks update --attach-acr, and in ABAC mode grant Repository Reader.
1. Write the agent configuration: allow all projects under the mygroup-lab group, but only allow the review/* and dev-aks environments to use the agent.
ci_access:
groups:
- id: mygroup-lab
environments:
- review/*
- dev-aks2. In a job, switch to the agent context and list the Pods in the myapp namespace.
kubectl config use-context mygroup-lab/myapp:aks-lab kubectl -n myapp get pods -o wide
The company requires a private AKS API server, 10 projects need to deploy, and auditing must be able to tell “which job in which project changed what.” GitLab is Premium. How would you design this?
One platform agent is installed in the cluster, with the configuration project maintained by the platform team; ci_access.groups authorize the application groups and use environments to restrict the available environments; access_as: ci_job: {} Have requests reach the API server with the job's identity so that job-related users/groups appear in audit logs; create RoleBindings per project/environment that grant only edit within each namespace. Production for critical services switches to Flux GitOps, and CI only updates the manifest repository. The API server is private, and agentk only needs outbound access to KAS.
Verified teaching videos
Official docs
- GitLab Docs: Installing the agent for Kubernetes
- GitLab Docs: Using GitLab CI/CD with a Kubernetes cluster
- Microsoft Learn: Set up staging environments in Azure App Service
- Microsoft Learn: Integrate ACR with AKS
Video storyboard script (about 80 seconds)
This courseware cannot directly generate video or MP3 files, so a storyboard and narration script are provided instead.
Visual: a private cluster with no doors; inside it, agentk extends a pipe outward to KAS.
Narration: the GitLab agent runs in the cluster and actively connects to GitLab's KAS. The cluster does not need to open any inbound ports.
Visual: a kubectl request from a job travels along the pipe into the cluster, passing the ci_access checkpoint.
Narration: the CI job receives the kubeconfig injected by GitLab, and its request enters the cluster through KAS along the agent's connection. Only projects and environments authorized in ci_access can pass.
Visual: the request enters the API server wearing a “gitlab:ci_job” mask; RBAC only lets the myapp namespace through.
Narration: by default, jobs inherit all of the agent's permissions; Premium can impersonate the job identity and then tighten with RBAC.
Visual: two App Service slots swap places.
Narration: App Service instead deploys to the staging slot first, then swaps after the smoke test; rollback is simply swapping again.
Module 7 · Hands-on cloud deployment troubleshooting
- Use the “four-layer triage method” to identify the failing layer within 1 minute: GitLab side (job did not run / token not issued),authentication (AADSTS),authorization (AuthorizationFailed / 403),runtime (image pulls, ports, health checks).
- Memorize the AADSTS error families for GitLab → Azure scenarios: 70021, 700212, 700213, 7002138, 700016, 501661, 700024, and GitLab's
ID token issuance is disabled. - Master safe diagnostic techniques: decode token payloads, list FICs, list role assignments, check revisions and logs, and practice fixes through fault injection.
What: four-layer triage method
| Layer | Typical symptoms | Where to look first |
|---|---|---|
| ① GitLab side | Job not created / stuck at manual, blocked, Waiting for resource; --federated-token is empty; ID token issuance is disabled | pipeline graph, job page, environment page,rules |
| ② Authentication (Entra) | AADSTS… | In the job log, the az login output; token payload; FIC list |
| ③ Authorization (Azure RBAC / K8s RBAC) | AuthorizationFailed,Forbidden | action and scope in the error; az role assignment list |
| ④ Runtime | revision Failed / Unhealthy, ErrImagePull, smoke 404/502/503 | az containerapp revision list,logs show,kubectl describe |
How: AADSTS error quick reference (GitLab → Azure)
| Code | Meaning | Common causes in GitLab scenarios | Fix |
|---|---|---|---|
AADSTS70021 | No matching federated identity record found for presented assertion | issuer/subject/audience mismatch; FIC just created and not yet propagated | Compare each field; wait and retry |
AADSTS700212 | … presented assertion audience | id_tokens.aud Does not match the FIC audience (https://gitlab.com vs api://AzureADTokenExchange) | Unify aud |
AADSTS700213 | … presented assertion subject | Wrong branch/tag; a tag pipeline used an identity that only trusts main; path renamed | Add a FIC for the subject in the error |
AADSTS7002138 | subject differs only in capitalization | Group/project path capitalization | Delete and recreate the FIC |
AADSTS700016 | Application with identifier … was not found in the directory | -u Used principalId or a clientId from another tenant; wrong environment-scoped variable | Use the UAMI's clientId; check variable scope |
AADSTS501661 | Request to External OIDC endpoint failed | Entra cannot reach the OIDC discovery / JWKS endpoints of a self-managed GitLab | Make publicly reachable /.well-known/openid-configuration and /oauth/discovery/keys |
AADSTS700024 | Client assertion is not within its valid time range | Token expired (job timeout / 5-minute default) or Runner clock skew | Log in early in the job; calibrate Runner time |
Error codes and text should follow what Entra actually returns; the Azure troubleshooting section of the GitLab docs lists 70021, 501661, and 700212.
Why: why “authentication succeeded but authorization failed” is the easiest to misfix
az login Success only means Entra accepts the identity; afterward, ARM evaluates each operation against RBAC. When you see AuthorizationFailed , changing the FIC is pointless—the error already states the client id, action, scope, so just add the minimum permissions accordingly. Note that new role assignments may take a few minutes to take effect.
When: boundaries of safe diagnostics
- You may print: the token payload claims (unsigned),
az account show, role assignment lists, FIC lists. - Do not print: the complete
$GITLAB_OIDC_TOKEN,$CI_REGISTRY_PASSWORD, Azure access tokens (az account get-access-tokenoutput). - Keep debugging jobs in
when: manualand delete them after the fix; do not temporarily loosen the FIC for debugging (such as trusting all branches).
Four-layer triage diagram
Comparison diagram: three-way comparison of token and FIC
Error decoder
Paste the error from the job log (or click an example); the decoder identifies the failing layer and gives the most likely cause, diagnostic commands, and fix. The rules are based on the error families compiled in this lesson and run entirely locally.
Diagnostic command list
| Purpose | Command |
|---|---|
| Pipeline and job status | glab ci view,glab ci trace JOB_ID |
| Token claims (safe) | Module 2's whoami-oidc job |
| FIC list (standard) | az identity federated-credential list -g RG --identity-name ID -o table |
| FIC (including flexible FIC) | az rest --method get --url ".../userAssignedIdentities/ID/federatedIdentityCredentials?api-version=2025-01-31-preview" |
| identity's clientId / principalId | az identity show -g RG -n ID --query "{c:clientId,p:principalId}" |
| Role assignments | az role assignment list --assignee PRINCIPAL_ID --all -o table |
| Activity log (who was denied, and when) | az monitor activity-log list -g RG --offset 1h --query "[?status.value=='Failed']" |
| ACA revisions and logs | az containerapp revision list …,az containerapp logs show … --type system |
| CI/CD variables (with scope) | glab variable list |
| Environments and deployments | glab api "projects/$GL_ENC/deployments?environment=prod&per_page=5" |
source ~/gitlab-lab.env
# One-step health check: FICs and roles for the three identities
for ID in id-gitlab-build id-gitlab-dev id-gitlab-prod; do
echo "== $ID"
az rest --method get --url "https://management.azure.com/subscriptions/$SUB_ID/resourceGroups/$RG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/$ID/federatedIdentityCredentials?api-version=2025-01-31-preview" \
--query "value[].{name:name, subject:properties.subject, expr:properties.claimsMatchingExpression.value}" -o tsv
az role assignment list --assignee $(az identity show -g $RG -n $ID --query principalId -o tsv) --all --query "[].{role:roleDefinitionName, scope:scope}" -o tsv
done
== id-gitlab-build gl-main project_path:mygroup-lab/myapp:ref_type:branch:ref:main None Container Registry Data Importer and Data Reader /subscriptions/…/registries/acrgitlab21873 == id-gitlab-dev gl-main project_path:mygroup-lab/myapp:ref_type:branch:ref:main None Contributor /subscriptions/…/containerApps/myapp-dev == id-gitlab-prod gl-tags-v None claims['sub'] matches 'project_path:mygroup-lab/myapp:ref_type:tag:ref:v*' and claims['project_id'] eq '71234567' Contributor /subscriptions/…/containerApps/myapp-prod
Read via ARM REST (preview API version), because for identities with flexible FICs, using az identity federated-credential list to read may error (Microsoft Learn documents this).
Lab 7: three fault injections (about 9 minutes)
For each fault: inject → observe the error → locate it with diagnostic commands → fix → restore. All are done on dev and do not affect prod.
.azure-login in aud to https://gitlab.com, and merge into main.
AADSTS700212: No matching federated identity record found for presented assertion audience 'https://gitlab.com'. …
Diagnosis: the error directly states the audience; compare it with the FIC's api://AzureADTokenExchange comparison. Fix: revert to the original value (revert commit).
az identity federated-credential delete -g $RG --identity-name id-gitlab-dev --name gl-main --yes az identity federated-credential create -g $RG --identity-name id-gitlab-dev --name gl-main \ --issuer https://gitlab.com --subject "project_path:MyGroup-Lab/myapp:ref_type:branch:ref:main" --audiences api://AzureADTokenExchange -o none
Retry in the main pipeline deploy-dev, you should see AADSTS7002138 (or 700213). Fix: delete it and recreate it with the correct capitalization.
az role assignment delete --assignee $(az identity show -g $RG -n id-gitlab-dev --query principalId -o tsv) \ --role Contributor --scope $(az containerapp show -g $RG -n $APP_DEV --query id -o tsv)
(AuthorizationFailed) The client '3c9a2d4e-…' with object id '8b2c3d4e-…' does not have authorization to perform action 'Microsoft.App/containerApps/write' over scope '/subscriptions/…/resourceGroups/rg-gitlab-lab/providers/Microsoft.App/containerApps/myapp-dev' or the scope is invalid.
Diagnosis: login succeeds, update fails → layer ③. Fix: re-grant the role (module 2, step 4), wait 1–5 minutes, then retry the job.
docs/deploy.md , add a “Fault Runbook” section recording the three original error messages, diagnostic commands, and fixes.Case 1: all deployments failed on Friday night with AADSTS700213
Problem: The group was renamed from Payments to payments-team, so all project paths changed. Diagnosis: The subject in the error contains the new path. Fix: Short term: add FICs for the new path; long term: change the sub component to start with project_id . Prevention: Include group renames in the change process and check OIDC trust in advance.
Case 2: intermittent AADSTS70021
Problem: The IaC deletes and recreates the FIC on every pipeline run, causing occasional deployment failures for the next few minutes. Fix: Change the FIC to an idempotent update (no change if nothing differs); in the deployment job's az login add limited retries. Microsoft Learn explicitly recommends adding retry logic to token requests.
Case 3: AADSTS700016 appears only in prod
Problem:AZURE_CLIENT_ID 's prod-scoped variable was mistakenly set to principalId. Dev works, while prod reports that the application does not exist. Fix:glab variable list Compare the scope and value, and change it to clientId. Prevention: Script the variable setup (module 2, step 5), with values taken from az identity show --query clientId.
More field errors
AADSTS700016: Application with identifier '9c3d4e5f-…' was not found in the directory
Cause:-u Passed principalId (object ID) instead of clientId; or the tenant ID is wrong.
az identity show -g $RG -n id-gitlab-prod --query "{clientId:clientId, principalId:principalId, tenant:tenantId}" -o table
glab variable list
Fix: Change the variable to clientId; verify AZURE_TENANT_ID.
AADSTS501661: Request to External OIDC endpoint failed.
Cause: The self-managed GitLab is on an internal network, so Entra cannot fetch its OIDC discovery document and JWKS.
curl -s https://gitlab.example.com/.well-known/openid-configuration | jq .jwks_uri curl -s https://gitlab.example.com/oauth/discovery/keys | jq '.keys | length'
Fix: Make these two endpoints publicly reachable (the GitLab docs also note that after firewall changes you may need to clear the Redis cache).
AADSTS700024: Client assertion is not within its valid time range.
Cause: The ID token has expired: the job logs in only after a long wait (for example, a long build), or the Runner clock is skewed.
Fix: Log in early in jobs that need Azure; split long jobs; calibrate NTP on self-hosted Runners.
ERROR: Please run 'az login' to setup account. (subsequent commands)
Cause:before_script The job's own before_script overrides (extends does not merge arrays), so the login never runs.
Fix: Do not write before_script again in jobs that inherit the template; if extra steps are needed, put them at the start of script , or use !reference [.azure-login, before_script].
1. List all role assignments for id-gitlab-dev (including scope).
az role assignment list --assignee $(az identity show -g rg-gitlab-lab -n id-gitlab-dev --query principalId -o tsv) --all --query "[].{role:roleDefinitionName, scope:scope}" -o table2. Check failed ARM operations in the resource group over the past 1 hour.
az monitor activity-log list -g rg-gitlab-lab --offset 1h --query "[?status.value=='Failed'].{op:operationName.value, caller:caller, time:eventTimestamp}" -o tabledeploy-dev succeeds on main, but after tagging the same commit v2.0, deploy-prod reports AADSTS700213, and the subject in the error is project_path:mygroup-lab/myapp:ref_type:tag:ref:v2.0. What are the possible causes? In what order should you check them?
① The prod identity's FIC only has the main branch or an old tag (with per-tag FICs, you forgot to add v2.0) → list the FICs; ② the flexible FIC expression is wrong (for example, ref:v*.*, a different project path,project_id being wrong) → use ARM REST to read the expression and compare it with the token payload; ③ the deployment job got the wrong AZURE_CLIENT_ID (environment scope is not prod) → compare the client id in the error with the prod identity; ④ the FIC was just created and has not propagated yet → retry later. Do not change the prod FIC to trust main for this.
Verified teaching videos
No verified GitLab → Azure OIDC troubleshooting video was found. Related verified videos are listed below:
Official docs
- GitLab Docs: Azure OIDC Troubleshooting
- Microsoft Learn: Microsoft Entra authentication and authorization error codes
- Microsoft Learn: Troubleshoot Azure RBAC
- Microsoft Learn: Troubleshoot Azure Container Apps
Video storyboard script (about 75 seconds)
This courseware cannot directly generate video or MP3 files, so a storyboard and narration script are provided instead.
Visual: four doors lined up in order: GitLab, Entra, RBAC, runtime; a red light is on at the second door.
Narration: when a cloud deployment fails, first determine which layer failed. If one layer fails, the next layer never happens.
Visual: token payload and FIC side by side; three rows are checked off one by one, and one row is crossed out.
Narration: when you see AADSTS, compare the token claims and the federated credential side by side: issuer, audience, subject—not a single character can differ.
Visual: the action and scope in the AuthorizationFailed error are highlighted.
Narration: login succeeded but the operation was denied—that is an authorization problem. The error already says which action is missing and at what scope; add the minimum permission and leave the federated credential alone.
Module 8 · Cost, cleanup, and self-check
- List the billing model for each resource in this lesson, estimate idle costs, and know which resources charge even when unused (ACR SKUs, AKS nodes, App Service plans, Log Analytics ingestion).
- Clean up in order: GitLab side (environments, protected environments/tags, variables, agent, images) → Azure side (resource group: apps, ACR, managed identities and their FICs and role assignments) → verify nothing is left over.
- Use the interactive troubleshooting tree to tie together the fault diagnosis from this lesson.
What: billing model for this lesson's resources
| Resource | Billing model | Idle cost | Notes |
|---|---|---|---|
| ACR Basic | Per-day SKU fee + storage overage | Yes (about a few dollars per month) | Standard/Premium cost more; import is not charged extra (see the pricing page) |
| Container Apps (Consumption) | vCPU-seconds, GiB-seconds, request count; there is a monthly free grant | Near 0 when min replicas is 0 | --min-replicas 1 Billed continuously |
| Log Analytics | Per GB ingested | Depends on log volume | Created by default with the Container Apps environment |
| User-assigned managed identity / FIC / role assignments | Free | None | but leftovers are a security risk |
| AKS (optional) | Free-tier control plane is free; node VMs, disks, load balancers, and public IPs are billed | Yes, the most expensive item | Delete immediately after the lab, or az aks stop |
| App Service S1 (optional) | Plan is billed hourly and always on | Yes | Cannot scale to 0 |
| GitLab hosted Runners | Compute minutes (Free includes 400 per month; small Linux cost factor 1) | None | Can switch to self-managed Runners |
| GitLab Container Registry | Counts toward namespace storage | Storage used | Configure cleanup policies |
Amounts vary by region and time; this lesson gives only orders of magnitude. Refer to the Azure pricing calculator and the GitLab pricing page.
How: cleanup order and reasons
- GitLab side first: stop and delete environments (an environment must be stopped before it can be deleted), remove protected environments and protected tags, delete CI/CD variables, delete the agent and its tokens, and delete container registry images as needed. Reason: first cut off any possibility that jobs can still trigger deployments.
- Then Azure side:
az group delete -n rg-gitlab-labDelete the app, ACR, Container Apps environment, Log Analytics, and managed identities (along with their FICs) in one go, along with role assignments scoped within the resource group. - Final verification: the resource group no longer exists; there are no leftover subscription-level role assignments pointing to deleted identities (shown as “Unknown” principals); and GitLab has no
AZURE_*variables. - If you used an app registration (rather than a UAMI): delete it separately
az ad app delete—deleting the resource group does not clean up directory objects.
Why: security risks of leftovers
- Leftover FICs + subscription-level role assignments = anyone who can run jobs on the project's main branch can obtain Azure permissions in the future.
- A leftover agent token = someone can impersonate agentk to connect to KAS (it should be revoked in the UI).
- Leftover deploy tokens / personal access tokens: this lesson does not create any; if you created them for testing, revoke them too.
When
Clean up on the day of the lab; if you keep resources for later lessons, at minimum keep Container Apps min replicas at 0, delete AKS and the App Service plan, and set a budget alert on the subscription (az consumption budget create, see the docs for details).
Cleanup order diagram
Cost breakdown (illustrative)
Monthly cost estimator (order of magnitude)
Adjust resources and run time; the estimator gives an order of magnitude based on editable unit prices. The unit prices are example defaults,so replace them with current prices for your region from the pricing calculator.
Cleanup commands
| Command | Purpose |
|---|---|
glab api -X POST "projects/$GL_ENC/environments/ID/stop" | Stop environment (required before deletion) |
glab api -X DELETE "projects/$GL_ENC/environments/ID" | Delete environment |
glab api -X DELETE "projects/$GL_ENC/protected_environments/prod" | Unprotect environment (Premium) |
glab api -X DELETE "projects/$GL_ENC/protected_tags/v%2A" | Remove v* tag protection (name must be URL-encoded) |
glab variable delete KEY [--scope ENV] | Delete variable |
az group delete -n rg-gitlab-lab --yes --no-wait | Delete all Azure resources |
az group exists -n rg-gitlab-lab | Verify |
az role assignment list --all --query "[?principalName=='']" | Find leftover assignments pointing to deleted principals |
#!/usr/bin/env bash # cleanup-gitlab-azure.sh —— one-step cleanup for this lesson (GitLab first, then Azure) set -u source ~/gitlab-lab.env for E in dev prod dev-aks prod-webapp; do EID=$(glab api "projects/$GL_ENC/environments?name=$E" | jq -r '.[0].id // empty') [ -n "$EID" ] || continue glab api -X POST "projects/$GL_ENC/environments/$EID/stop" >/dev/null glab api -X DELETE "projects/$GL_ENC/environments/$EID" && echo "deleted environment $E" done glab api -X DELETE "projects/$GL_ENC/protected_environments/prod" 2>/dev/null || true # Premium glab api -X DELETE "projects/$GL_ENC/protected_tags/v%2A" 2>/dev/null || true for K in AZURE_TENANT_ID AZURE_SUBSCRIPTION_ID AZURE_CLIENT_ID_BUILD; do glab variable delete $K; done glab variable delete AZURE_CLIENT_ID --scope dev glab variable delete AZURE_CLIENT_ID --scope prod for A in $(glab api "projects/$GL_ENC/cluster_agents" | jq -r '.[].id'); do glab api -X DELETE "projects/$GL_ENC/cluster_agents/$A"; done az group delete -n $RG --yes # Waits synchronously, about 5–15 minutes az group exists -n $RG glab variable list
deleted environment dev deleted environment prod false (variable list is empty)
Note: Project settings such as “Prevent outdated deployment jobs” from module 3 need no cleanup. To delete GitLab Container Registry images, delete them under Deploy → Container registry, or glab api -X DELETE "projects/$GL_ENC/registry/repositories/ID". Git tags v1.* can be kept as a record of the exercise.
Lab 8: cleanup and verification (about 5 minutes + waiting)
~/cleanup-gitlab-azure.sh and then bash ~/cleanup-gitlab-azure.sh.az group exists -n rg-gitlab-lab
az role assignment list --all --query "[?principalName==''].{id:id, role:roleDefinitionName, scope:scope}" -o table
glab variable list
glab api "projects/$GL_ENC/environments" | jq length
false (empty table) (empty) 0
.gitlab-ci.yml delete or comment out the promote / deploy jobs (otherwise the next merge will fail because there are no Azure resources).Case 1: lab AKS forgotten and not deleted
Problem: After practice, the AKS was forgotten and not deleted; a node charge turned up at month-end. Approach: Subscription budget alerts + resource group tags course=gitlab-8h, check weekly using az group list --tag course=gitlab-8h to verify. Limitations: Budget alerts are delayed and cannot replace same-day cleanup.
Case 2: after a project transfer, the old FIC still trusts the old path
Problem: The project moved from a personal namespace to a company group, and the old project_path:alice/app:… FIC was not deleted; later, someone created a personal project with the same name. Approach: Delete the old FIC; switch to a sub claim starting with project_id . GitLab also refuses to issue tokens when the path was previously used by another project, as an extra safeguard. Prevention: Add “OIDC trust” to the project migration checklist.
Case 3: a flood of failure alerts on the next merge after cleanup
Problem: The Azure resources were deleted but the pipeline remained; after merging, promote/deploy failed, triggering alert noise. Approach: Update the pipeline during cleanup, or in the deployment job's rules , add if: $AZURE_SUBSCRIPTION_ID (the job is no longer generated once the variable is deleted).
Interactive troubleshooting tree: GitLab → Azure deployment failures
Start from the symptom, answer questions step by step, and get the diagnosis and fix commands. Covers all modules in this lesson.
Cannot delete an environment that is available / failed to delete environment
Cause: The environment has not been stopped. Fix: First POST …/environments/ID/stop, then delete it.
(ScopeLocked) … failed to delete resource group
Cause: The resource group or a resource has a delete lock.
az lock list -g rg-gitlab-lab -o table az lock delete -g rg-gitlab-lab -n <lock name>
glab variable delete: 404 Variable Not Found
Cause: The same-named variable has multiple environment scopes, and no --scope was specified, or it has already been deleted. Fix:glab variable list Check the scopes, then include --scope when you delete.
1. Delete the AZURE_CLIENT_ID variable scoped to prod.
glab variable delete AZURE_CLIENT_ID --scope prod
2. Find role assignments in the subscription that point to deleted principals.
az role assignment list --all --query "[?principalName==''].{id:id, role:roleDefinitionName, scope:scope}" -o tableYou want to keep this lesson's environment for 2 weeks for a demo, with minimal cost and minimal risk. How would you do it?
Keep: resource group, ACR (Basic), Container Apps (min replicas 0), managed identities and FICs. Delete: AKS, App Service plan. Security: the prod identity's flexible FIC keeps trusting only protected v* tags; confirm there are no subscription-level role assignments; set a budget alert and resource group tags; add a cleanup reminder to your calendar. GitLab: keep the variables, but if you are not publishing for now, temporarily remove the prod-scoped AZURE_CLIENT_ID, so prod deployments cannot log in.
Verified teaching videos
Official docs
- Azure Container Apps pricing · ACR pricing
- GitLab Docs: Compute minutes
- GitLab Docs: Environments API
Video storyboard script (about 60 seconds)
This courseware cannot directly generate video or MP3 files, so a storyboard and narration script are provided instead.
Visual: a billing pie chart with two slices, ACR daily rate and log ingestion, next to a large dashed slice for AKS.
Narration: the default resources in this lesson cost only a few dollars for a day or two; the real big-ticket items are the optional AKS and App Service plan.
Visual: two pairs of scissors; first cut the line from GitLab to Azure, then delete the Azure box.
Narration: clean up GitLab first, then Azure: delete environments, protection rules, variables, and the agent first, then delete the resource group.
Visual: checklist items checked off one by one.
Narration: final verification: the resource group no longer exists, there are no leftover role assignments, and the variable list is empty.
Command cheat sheet
1. Declare the ID token in a job and log in
.azure-login:
image: mcr.microsoft.com/azure-cli:2.93.0
id_tokens:
GITLAB_OIDC_TOKEN:
aud: api://AzureADTokenExchange
before_script:
- az login --service-principal -u "$AZURE_CLIENT_ID"
-t "$AZURE_TENANT_ID" --federated-token "$GITLAB_OIDC_TOKEN" -o none
- az account set --subscription "$AZURE_SUBSCRIPTION_ID"2. Managed identity + standard FIC
az identity create -g rg-gitlab-lab -n id-gitlab-dev az identity federated-credential create -g rg-gitlab-lab \ --identity-name id-gitlab-dev --name gl-main \ --issuer https://gitlab.com \ --subject "project_path:mygroup-lab/myapp:ref_type:branch:ref:main" \ --audiences api://AzureADTokenExchange
3. Flexible FIC (preview, tag v*)
cat > fic.json <<EOF
{"properties":{"issuer":"https://gitlab.com","audiences":["api://AzureADTokenExchange"],
"claimsMatchingExpression":{"languageVersion":1,
"value":"claims['sub'] matches 'project_path:$GL_PROJECT:ref_type:tag:ref:v*' and claims['project_id'] eq '$GL_PROJECT_ID'"}}}
EOF
az rest --method put --body @fic.json --url "https://management.azure.com/subscriptions/$SUB_ID/resourceGroups/$RG/providers/Microsoft.ManagedIdentity/userAssignedIdentities/id-gitlab-prod/federatedIdentityCredentials/gl-tags-v?api-version=2025-01-31-preview"4. Minimal RBAC
az role assignment create --assignee-object-id $PID \ --assignee-principal-type ServicePrincipal \ --role "Container Registry Data Importer and Data Reader" --scope $ACR_ID az role assignment create --assignee-object-id $PID \ --assignee-principal-type ServicePrincipal \ --role Contributor --scope $CONTAINERAPP_ID
5. GitLab variables, protected tags, and environments
glab variable set AZURE_CLIENT_ID "$DEV_CID" --scope dev glab variable set AZURE_CLIENT_ID "$PROD_CID" --scope prod glab api -X POST "projects/$GL_ENC/protected_tags" -f name='v*' -f create_access_level=40 glab api -X POST "projects/$GL_ENC/protected_environments" \ -H "Content-Type: application/json" --input pe.json # Premium
6. Build and promote
echo "$CI_REGISTRY_PASSWORD" | docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" --password-stdin docker build -t "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" . && docker push "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" az acr import -n $ACR_NAME --source "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA" \ --image "myapp:$CI_COMMIT_SHORT_SHA" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD"
7. Container Apps deployment and canary rollout
az containerapp ingress traffic set -g $RG -n myapp-prod --revision-weight "$OLD=100" az containerapp update -g $RG -n myapp-prod --image "$ACR.azurecr.io/myapp:$SHA" --revision-suffix v1-1 az containerapp revision show -g $RG -n myapp-prod --revision myapp-prod--v1-1 --query properties.fqdn -o tsv az containerapp ingress traffic set -g $RG -n myapp-prod --revision-weight myapp-prod--v1-1=100 "$OLD=0"
8. GitLab agent (AKS)
helm upgrade --install aks-lab gitlab/gitlab-agent -n gitlab-agent-aks-lab --create-namespace \ --set config.token="$AGENT_TOKEN" --set config.kasAddress=wss://kas.gitlab.com # In a job: kubectl config use-context mygroup-lab/myapp:aks-lab kubectl -n myapp set image deployment/myapp myapp="$ACR_NAME.azurecr.io/myapp:$IMAGE_TAG"
Quick troubleshooting table
| Symptom / error | Layer | Most likely cause | First command |
|---|---|---|---|
--federated-token: expected one argument | GitLab | Job has no id_tokens | Check extends and the job YAML |
ID token issuance is disabled … | GitLab | Path previously belonged to another project | Settings ci_id_token_sub_claim_components |
AADSTS700212 | Authentication | aud mismatch | Compare id_tokens.aud with FIC |
AADSTS700213 / 70021 | Authentication | sub mismatch (branch vs tag) / propagation delay | whoami-oidc + FIC list |
AADSTS7002138 | Authentication | Capitalization | Delete and recreate FIC |
AADSTS700016 | Authentication | Used principalId / wrong variable scope | az identity show,glab variable list |
AADSTS501661 | Authentication | Self-managed GitLab OIDC endpoints unreachable | curl …/.well-known/openid-configuration |
AuthorizationFailed … importImage/action | Authorization | build identity has only AcrPush | az role assignment list |
… managedEnvironments/join/action | Authorization | Missing environment join permission | Grant the minimum role at environment scope |
| Deployment blocked | GitLab | Waiting for approval (Premium) | …/deployments?status=blocked |
The deployment job is older than the latest deployment… | GitLab | Outdated deployment protection (expected) | Deploy in a new pipeline |
no context exists with the name … | GitLab agent | ci_access Not authorized / environment not in list | In job kubectl config get-contexts |
| Revision Failed, pull 401 | Runtime | App identity missing AcrPull (or ABAC role) | az containerapp show … registries |
| Smoke 404/502 | Runtime | targetPort is not 5000 | … ingress.targetPort |
Recommended configuration snippet: prod release rule
deploy-prod:
extends: .azure-login
environment: { name: prod, deployment_tier: production }
resource_group: prod
rules:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+(\.\d+)?$/ # v* is a protected tag
when: manual # Free gate; Premium adds protected environment approval
# Azure side: id-gitlab-prod trusts only project_path:…:ref_type:tag:ref:v* with a matching project_id
Capstone lab + final quiz
Scenario
You are the platform engineer for myapp. The security team requires: ① no Azure secrets may exist in the project; ② only release tags created by a Maintainer may deploy to prod, and prod deployments require manual confirmation beforehand (on Premium, approval must come from someone other than the triggerer); ③ the image deployed must exactly match the one tested on main; ④ failed releases must not affect users; ⑤ no permissions may be left behind after the lab ends.
id-gitlab-build / id-gitlab-dev / id-gitlab-prod; build/dev standard FICs trust main; prod flexible FIC trusts v* tags and bind project_id; grant minimal roles per module 2; set AZURE_* variables (clientId scoped per environment).main protected (only Maintainers can merge); v* protected tags; enable “Prevent outdated deployment jobs”; (Premium) prod protected environment + 1 approval..gitlab-ci.yml set of module 5 jobs (test / build-image / promote-acr / deploy-dev / verify-dev / deploy-prod / verify-prod / release-traffic), merged via MR.v1.1 → manually run deploy-prod (Premium: run after another person approves) → watch the 0% revision → ramp up traffic./healthz build that returns 503 v1.2, confirm release-traffic did not run and user traffic is still on v1-1; then revert and release v1.3.source ~/gitlab-lab.env
glab api "projects/$GL_ENC/deployments?environment=prod&order_by=id&sort=desc&per_page=5" | jq -r '.[] | "\(.id) \(.status) \(.ref) \(.sha[0:8])"'
az containerapp revision list -g $RG -n $APP_PROD --all --query "[].{rev:name, active:properties.active, weight:properties.trafficWeight, image:properties.template.containers[0].image}" -o table
glab variable list | grep -i secret || echo "no secrets"
1123456791 success v1.3 9e8d7c6b 1123456790 success v1.2 5a4b3c2d 1123456789 success v1.1 3f9c2ab1 Rev Active Weight Image ---------------- -------- -------- ------------------------------------------ myapp-prod--v1-1 False 0 acrgitlab21873.azurecr.io/myapp:3f9c2ab1 myapp-prod--v1-2 True 0 acrgitlab21873.azurecr.io/myapp:5a4b3c2d myapp-prod--v1-3 True 100 acrgitlab21873.azurecr.io/myapp:9e8d7c6b no secrets
The v1.2 deployment record shows success (the deploy job itself succeeded), but its verify-prod failed and it never received traffic—this is exactly the value of separating “deploy” from “ramp-up”. You can also declare the environment in the release-traffic job so the environment page more clearly reflects the traffic-ramp status.
Open-ended self-check (think first, then read)
1. In three sentences, explain to a colleague the most critical difference between GitLab and GitHub for Azure OIDC.
After a GitHub job declares an environment, the token sub becomes environment-level, so Azure can trust only the prod environment. By default, the GitLab sub contains only the project path, ref type, and ref, with no environment. So on GitLab, trust must be split using branches/tags (together with protected branches/tags) or custom sub components. Neither supports wildcards in standard FICs, but flexible FICs (preview) support them in both.
2. Why does the promote-acr job need neither Docker nor AcrPush?
az acr import It is a single ARM control-plane call; the ACR server pulls the image layers from the source registry, and the Runner only initiates the request. The required permission is the importImage action, which is provided by Container Registry Data Importer and Data Reader .
3. If the team must automatically deploy commits on main to prod (continuous deployment), how should the identity and gates be adjusted?
The prod identity should trust main (or, on 18.7+, add a custom sub claim including deployment_tier), so protections on main must be stricter: only Maintainers can merge, MRs require approval, and CODEOWNERS covers .gitlab-ci.yml; the pipeline keeps 0% pre-release, automatic smoke tests, automatic traffic ramp-up and rollback; Premium can use protected environments to restrict who may trigger prod jobs.
4. Flexible FIC is a preview feature; how would you reduce risk in production?
Keep a fallback path (a script for per-tag standard FICs); manage it in IaC with ARM REST/azapi and record the API version; the expression must match both project_id; monitor Entra sign-in logs; re-review when the preview goes GA or the semantics change.
5. How do you choose between the agent CI/CD workflow and OIDC + az aks get-credentials?
Private cluster, shared across multiple projects, and you do not want pipelines to hold Azure permissions → agent; you do not want to install components in the cluster, the Runner can reach the API server, and you already have an Azure RBAC for Kubernetes setup → OIDC approach. For production-critical services, prefer GitOps.
6. List all the ways the “build once” principle can be broken in this lesson.
Rebuilding in the prod stage; deploying mutable tags (:latest,:main); tagging release tags on commits not built from main; overwriting a same-named tag with different content during import; manually pushing a same-named tag to ACR. Countermeasures: SHA tags + recording the digest + tagging only commits on main + checking that the image exists before release.
Sources and version notes
Source table
| Topic | Verified finding | Source (access date) |
|---|---|---|
| GitLab version | 19.5 is the latest released version; the 19.6 release notes page is marked Upcoming release | docs.gitlab.com/releases/19(2026-11-16) |
| GitLab → Azure OIDC | Free/Premium/Ultimate; CI_JOB_JWT_V2 was removed in 17.0; example az login --service-principal … --federated-token $GITLAB_OIDC_TOKEN; branch subject format; wildcards require flexible FICs; troubleshooting AADSTS70021 / 501661 / 700212 | GitLab: Azure OIDC(2026-11-16) |
| ID token claims and sub | Default project_path:{group}/{project}:ref_type:{type}:ref:{branch_name}; can be customized via ci_id_token_sub_claim_components ; from 18.7 onward can include ref_protected / environment_protected / deployment_tier; validity = job timeout (otherwise 5 minutes); RS256; job_project_* 18.4,source_project_* 19.5; “ID token issuance is disabled” error | GitLab: ID token authentication(2026-11-16) |
id_tokens / environment / resource_group Keyword | aud can be a string or an array; environment:kubernetes:agent 17.6; dashboard:* 18.4; deployment_tier variable support 18.5; resource_group Default unordered | GitLab: CI/CD YAML reference(2026-11-16) |
| Environments, deployment safety | Environments and environment-scoped variables Free; “Prevent outdated deployment jobs” failure message; rollback retries can be turned off; Auto Rollback is Ultimate | Environments · Deployment safety(2026-11-16) |
| Protected environments and approvals | Premium/Ultimate; by default, the triggerer cannot approve their own run; manual run needed after approval; blocked status; group-level protection by tier; approvals API POST /projects/:id/deployments/:deployment_id/approval | Protected environments · Deployment approvals · Deployments API · Protected environments API(2026-11-16) |
| GitLab agent | CI/CD workflow Free, emulating Premium; context path:agent-name; ci_access up to 500 projects / 500 groups; environments supports *; protected_branches_only not yet production-ready; KAS wss://kas.gitlab.com; glab cluster agent bootstrap is the recommended install method | CI/CD workflow · Install(2026-11-16) |
| Compute minutes | Free includes 400 compute minutes per month; small Linux cost factor 1 | Compute minutes(2026-11-16) |
| glab variable | glab variable set <key> <value>,-s/--scope,-m,-p,--hidden etc. | gitlab-org/cli docs(2026-11-16) |
| FIC limits | Up to 20 per identity; issuer+subject must be unique; no wildcards; audience recommended api://AzureADTokenExchange; name is 3–120 characters and cannot be changed; propagation delay can cause AADSTS70021; concurrent creation on the same UAMI returns 409 | Microsoft Learn: considerations(2026-11-16) |
| Flexible FIC | preview; supports GitHub, GitLab, and Terraform Cloud; works for both applications and UAMIs; the GitLab issuer includes https://gitlab.com; with a variable subject, it must also match sub and project_id; operators matches/eq/and; CLI, PowerShell, and Terraform do not support it natively yet, so use az rest; UAMI API version 2025-01-31-preview | Microsoft Learn: Flexible FIC(page ms.date 2026-09-18, accessed 2026-11-16) |
| ACR roles | Import: Container Registry Data Importer and Data Reader; push: AcrPush / Repository Writer (ABAC mode); pull: AcrPull / Repository Reader; az acr login requires Contributor and Data Access Configuration Administrator; Tasks: Tasks Contributor | Microsoft Learn: ACR roles(2026-11-16) |
| image version | mcr.microsoft.com/azure-cli:2.93.0 is the latest tag; docker:29.10 / docker:29.10-dind (29.10.0) exists | MCR tag list, Docker Hub tags API (2026-11-16) |
Video verification note
All videos were checked through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-16 to verify titles and channels:
- Nom9JtjZ8Js — Kubernetes-Free Microservices: The Azure Container Apps Advantage — Microsoft Reactor
- A0w_3DvOf6M — AKS vs App Service vs Container Apps: Which Service Should You Choose? — Brayan Ortiz
- qP8kir2GUgo — GitLab CI CD Tutorial for Beginners [Crash Course] — TechWorld with Nana
- saTUeR_U3lA — Azure DevOps Workload Identity Federation with Azure Overview. NO MORE SECRETS! — John Savill's Technical Training
- XkhkkLBkAT4 — GitHub Azure AD OIDC Authentication — John Savill's Technical Training
- PGyhBwLyK2U — DevOps with GitLab CI Course - Build Pipelines and Deploy to AWS — freeCodeCamp.org
- tCZ3958W3WI — Environments and approvals in Azure DevOps — Azure Infrastructure, Security & DevOps Series
- FtZTm58wgMc — Azure Container Registry (ACR) Explained | AKS Image Pull From ACR With Managed Identity | Part-5 — Harshalkumar Jain
- 5vPM94kpIO4 — Azure Container Apps - Revisions Explained | Step by Step — Kamal Rathnayake - MVP
- k29K-GkJApE — Traffic Splitting in Azure Container Apps | Step-by-Step Lab Demo — MadeForCloud
- tbj2Nv-Z96Y — How to deploy your Azure Container Apps using Azure CLI command and GitHub Action — Learn with Jon
- Sr3X5-O9HWA — Deploying the GitLab Kubernetes Agent with Limited Permissions — GitLab Unfiltered
- rE8LJvoWxj4 — Integrate AKS and ACR to allow pulling images (multiple methods) — Andrei Barbu - courscape com
- 5rR5C4Z5dU4 — How to use Deployment Slots in Azure App Service for Containers | Azure Tips and Tricks — Microsoft Azure
- rZuC6m4WH10 — How to troubleshoot common issues with AKS Diagnostics — Microsoft Azure
- mQYR7icumaU — How to configure Azure budgets and costs alerts — A Cloud Guru
- sQsLI-OaSHk — 8. Azure Cost Analysis, Budgets and Cost Alerts |Azure Beginners Tutorials — Mr. K Talks Tech
No verified videos specifically covering GitLab → Azure OIDC,GitLab protected environments / deployment approvals and GitLab → Azure troubleshooting were found: the corresponding modules are marked and provide storyboard scripts. Some videos were recorded earlier or come from community authors, so follow this lesson and the official docs for commands and versions.
Voice narration notes
The “Voice” page uses the browser's built-in Web Speech API (Chinese zh-CN, English terms en-US) for real-time synthesis; the slides do not embed MP3 files; narration scripts can be passed directly to other TTS tools to generate audio. If no Chinese voice pack is installed, follow the on-page prompt to install one, or read the narration script directly.
Known limitations
- commands were not actually run in these slides: all “expected output” and “job log” entries are examples, and the IDs, GUIDs, SHAs, domain names, times, and deployment numbers in them are fictitious values; their formats follow the official docs and CLI conventions.
- Full format of custom sub components: the GitLab docs only give
["project_id","ref_type","ref"]→project_id:<id>:ref_type:<type>:ref:<ref>examples, do not list all allowed values, and do not includeenvironment_protected/deployment_tiercomplete example strings; this lesson therefore lists “environment-level trust” as an advanced option and requires checking against the actual token. - Flexible FIC is in preview: API versions, expression syntax, and tool support may change; this lesson provides a per-tag fallback using standard FICs.
- ACA authorization granularity:
az containerapp updatewhether the environment'sjoin/actiondepends on platform behavior and CLI version; this lesson grants permissions as errors come up and does not give a definitive conclusion. glabOutput format (such asglab variable listtable columns) vary between versions; the set/delete behavior of same-named variables across multiple environment scopes depends on the actual glab version; use the UI or REST API if needed.- Tools in the image:
mcr.microsoft.com/azure-cliWhether the image includescurlis unverified, so the smoke test is placed in a separatealpine:3.22job. - Cost: only orders of magnitude are given; actual prices for ACR, Log Analytics, AKS, and App Service should be taken from the Azure pricing calculator.
- GitLab tier: protected environments, approvals, and agent impersonation require Premium/Ultimate; the Free-tier alternative cannot enforce “approval by someone other than the triggerer.”
- Connection to Lessons 1–2: Lessons 1–2 are written in parallel with this lesson, and this lesson relies only on shared conventions (
mygroup-lab/myapp, port 5000,registry.gitlab.com/mygroup-lab/myapp, runner taglab-docker).