AKS Hour 3: Identity and Security
- Understand AKS's three identity channels: people → API server (Entra ID authentication + Kubernetes RBAC / Azure RBAC authorization), cluster → Azure (control plane identity, kubelet identity), and pod → Azure (Microsoft Entra Workload ID).
- Enable Entra integration for
aks-lab, authorize by group, disable local accounts (--disable-local-accounts), and use control plane audit logs to answer "who did what, and when". - Build the full Workload Identity chain by hand: OIDC issuer → user-assigned managed identity
id-myapp→ federated credential → annotated ServiceAccount → pod gets an Entra access token → reads Key Vaultkv-aks-lab-<suffix>. Be able to explain each JWT field (iss/sub/aud) and theAADSTSerror code for each failure mode. - Mount secrets into myapp with the Key Vault secrets store CSI driver. Understand automatic rotation (default 2-minute polling), the cost of syncing to a Kubernetes Secret, and the
subPathpitfall. - Set up image supply chain controls: ACR pull authorization (the difference between
--attach-acrand ACR ABAC mode), signature verification (Image Integrity, in preview), vulnerability scanning, and gated deployment with Defender. - Use the Azure Policy add-on and Deployment Safeguards (Warn / Enforce + Pod Security Standards) to constrain workload configuration. Use Defender for Containers for runtime threat detection. Finish by reviewing the whole cluster against a single baseline checklist.
1-hour timetable
| # | Time | Module | Core content | Animation / interaction | Lab (aks-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up: identity inventory and least privilege | Reuse the cluster from hours 1–2; list every identity involved in the cluster; turn on the features this hour needs | Identity inventory self-check | OIDC / WI / KV CSI / Policy add-ons ready |
| 1 | 00–06 | Entra ID integration with Kubernetes RBAC / Azure RBAC | Managed Entra integration, kubelogin, two authorization modes, four built-in roles, namespace-scoped assignments, custom roles | Request simulator for the authentication and authorization path of a single kubectl request | Authorize the myapp namespace by Entra group |
| 2 | 06–13 | Disable local accounts and access auditing | --admin back door, --disable-local-accounts, certificate rotation, break-glass, control plane logs (kube-audit-admin, guard), activity log | How local certificates and Entra tokens look in audit logs | Disable local accounts + query the audit log with KQL |
| 3 | 13–21 | Workload Identity | OIDC issuer, federated credentials, mutating webhook, projected token, token exchange, identity bindings | Core animation: full token exchange + fault injection | myapp reads Key Vault with id-myapp |
| 4 | 21–28 | Key Vault secrets store CSI driver | Add-on, SecretProviderClass, three identity methods, rotation, sync to Secret, metrics | Mount and rotation timeline | myapp's Redis password comes from Key Vault |
| 5 | 28–35 | Images and supply chain: ACR, image integrity and scanning | kubelet identity and AcrPull, ACR ABAC mode, Notation signing, Image Integrity (preview), vulnerability assessment, gated deployment | The four checkpoints an image must pass | Push myapp:1.1 to ACR and pull it from AKS |
| 6 | 35–42 | Azure Policy and Pod security | Azure Policy add-on (Gatekeeper), built-in initiatives, Deployment Safeguards (Warn/Enforce, mutator), Pod Security Standards | Admission pipeline: mutate → validate → reject | Warn → Enforce, fix the myapp manifests |
| 7 | 42–50 | Microsoft Defender for Containers | Agentless discovery and vulnerability assessment, Defender sensor (eBPF), audit log analysis, binary drift, anti-malware, XDR | Attack chain and detection point simulator | Enable the sensor and trigger a test alert |
| 8 | 50–60 | Security baseline review | Review item by item across six areas (identity / network / nodes / workloads / supply chain / detection), with automated checks | Baseline scorer + troubleshooting tree | Generate a review report for aks-lab |
| — | After class | Cheat sheet · Capstone lab | Turn myapp into a secure deployment with zero static credentials | Final quiz (12 questions) | Capstone lab |
Knowledge coverage matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Access the cluster with an Entra identity and authorize by group | ✓ | ✓ | · | · | · | · | · | ✓ | az aks update --enable-aad --enable-azure-rbac | M1 lab |
| Eliminate unauditable admin back doors | · | ✓ | · | · | · | · | · | ✓ | --disable-local-accounts | M2 lab |
| Answer "who did what" | · | ✓ | · | · | · | · | ✓ | ✓ | az monitor diagnostic-settings create, KQL | AKSAuditAdmin |
| Pods access Azure without keys | · | · | ✓ | ✓ | · | · | · | ✓ | az identity federated-credential create | myapp + id-myapp |
| Move secrets out to Key Vault and rotate them | · | · | ✓ | ✓ | · | · | · | ✓ | az aks addon update --enable-secret-rotation | Redis password |
| Controlled image sources and integrity | · | · | · | · | ✓ | ✓ | ✓ | ✓ | az aks check-acr, notation sign | myapp:1.1 |
| Admission control: policy, PSS, Safeguards | · | · | · | · | ✓ | ✓ | · | ✓ | az aks safeguards create/update | Warn → Enforce |
| Runtime detection and response | · | · | · | · | ✓ | · | ✓ | ✓ | az aks update --enable-defender | Test alert |
| Identity and security troubleshooting | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | · | ✓ | kubectl auth can-i, describe pod | Troubleshooting tree |
Out of scope for this hour (and where to learn it)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| Kubernetes RBAC objects (Role/ClusterRole/Binding), ServiceAccount, Pod Security Admission, and general NetworkPolicy principles | General Kubernetes knowledge; this hour covers only the AKS-specific differences | Kubernetes Hour 5 (for AKS basics, see Hour 6) |
| Private clusters, authorized API server IP ranges, API server VNet integration, outbound firewall | Networking topic; this hour only references it in the baseline review | AKS Hour 2 |
| Pipelines deploy to AKS with OIDC (GitHub Actions / Azure DevOps workload identity federation) | CI/CD tool details | GitHub Hour 3 · Azure DevOps Hour 3 |
| Deploying myapp with Helm, chart signing | Packaging tool details | Helm Hour 3 |
| Node OS automatic upgrades, security patch channels | Covered under upgrades and operations | AKS Hour 6 |
| Combined troubleshooting of identity and permission failures (including ACR pull failures) | This hour only provides the troubleshooting tree; in-depth troubleshooting comes later | AKS Hour 7 |
How to use this course material
Theory · diagrams · animation · commands · lab · production case · troubleshooting · quiz · voice · video. Read "Theory" and "Animation" first, then do the "Lab". The animation in module 3 is the core of this hour; go through it fully at least once and try all four fault injections.
A quiz score of 70% or higher, or clicking "Mark this module complete", counts toward progress. Progress is saved in this browser (it is cleared on refresh if local storage is disabled).
The Voice tab reads the narration aloud with the browser's built-in Web Speech API (en-US). If no English voice pack is installed, the narration is still readable.
--role-assignment-mode rbac-abac) will become the default in the future; once enabled, AcrPull no longer takes effect. For command parameters, the documents listed under Sources and versions on this page are authoritative; preview features may require the aks-preview extension.aks-lab (this also applies if you used a cluster with your own VNet in hour 2). For Kubernetes RBAC and Pod security basics, see the Kubernetes course first.Module 0 · Warm-up: identity inventory and least privilege (complete before class)
- You have completed hour 1: the resource group
rg-aks-lab(canadacentral) and the clusteraks-labexist in your subscription. Hour 2's network configuration does not affect this hour. - Azure CLI (2.60 or later,
az upgrade), kubectl, and kubelogin (installed once withaz aks install-cli; the official docs note that in Azure CLI scenarios these are managed automatically). - Required Azure roles: on
rg-aks-lab, you need Owner, or Contributor plus Role Based Access Control Administrator (needed to create role assignments; the official docs specifically note that Contributor and Key Vault Contributor cannot create role assignments). Entra permissions: the ability to create security groups (or ask a tenant admin to create the two groups for you). - myapp image: the Docker course image
myapp:1.1(Flask + gunicorn, port 5000,/healthz, depends on Redis).
Step 1: set variables (run this first every time you open a new terminal)
RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab # Naming convention added in this hour (the suffix is generated once and saved; later hours reuse it) touch ~/.aks-lab.env; source ~/.aks-lab.env [ -z "$ACR" ] && echo "ACR=acraks$RANDOM" >> ~/.aks-lab.env [ -z "$KV" ] && echo "KV=kv-aks-lab-$RANDOM" >> ~/.aks-lab.env source ~/.aks-lab.env UAMI=id-myapp; NS=myapp; SA=myapp-sa echo "ACR=$ACR KV=$KV UAMI=$UAMI"
ACR=acraks21877 KV=kv-aks-lab-9312 UAMI=id-myapp
Key Vault names are globally unique and 3–24 characters long; kv-aks-lab- plus up to 5 digits is no more than 16 characters. ACR names may contain only letters and digits (so no hyphens). If you already created an ACR in hour 1, write that name into ~/.aks-lab.env.
Step 2: identity inventory, which identities does this cluster involve?
az aks show -g $RG -n $CLUSTER --query "{identity:identity.type, controlPlaneMI:identity.userAssignedIdentities, kubelet:identityProfile.kubeletidentity.clientId, aad:aadProfile, azureRbac:aadProfile.enableAzureRbac, localDisabled:disableLocalAccounts, oidc:oidcIssuerProfile.enabled, wi:securityProfile.workloadIdentity.enabled}" -o jsonc
az aks show -g $RG -n $CLUSTER --query "addonProfiles" -o jsonc
{
"aad": null,
"azureRbac": null,
"controlPlaneMI": null,
"identity": "SystemAssigned",
"kubelet": "4f2c…-kubelet-client-id",
"localDisabled": false,
"oidc": false,
"wi": null
}
| Identity | Who it is | What it is used for | Covered in this hour |
|---|---|---|---|
| Human users / groups | Entra users, security groups | kubectl access to the API server | M1: Entra integration + RBAC |
| Local admin certificate | clusterAdmin client certificate (--admin) | Bypasses Entra and accesses the cluster directly | M2: disable |
| Control plane identity | The cluster's system or user-assigned managed identity | Creates load balancers, disks, modifies subnets, etc. | Hours 1–2 |
| kubelet identity | The <cluster>-agentpool user-assigned managed identity in the node resource group | Pulls images from ACR | M5: AcrPull |
| Add-on identities | For example azurekeyvaultsecretsprovider-<cluster>, azurepolicy-<cluster> | Add-ons access Azure | M4 / M6 |
| Workload identity | User-assigned managed identity id-myapp + ServiceAccount myapp/myapp-sa | Pod accesses Key Vault, etc. | M3 |
| Pipeline identity | Service principal / managed identity with workload identity federation | CI/CD deployment | GitHub / ADO hours |
Step 3: create two Entra groups (cluster admins / myapp developers)
ADMIN_GROUP_ID=$(az ad group create --display-name aks-lab-admins --mail-nickname aks-lab-admins --query id -o tsv) DEV_GROUP_ID=$(az ad group create --display-name aks-lab-myapp-devs --mail-nickname aks-lab-myapp-devs --query id -o tsv) ME=$(az ad signed-in-user show --query id -o tsv) az ad group member add --group $ADMIN_GROUP_ID --member-id $ME echo "ADMIN_GROUP_ID=$ADMIN_GROUP_ID" >> ~/.aks-lab.env; echo "DEV_GROUP_ID=$DEV_GROUP_ID" >> ~/.aks-lab.env
Step 4: enable all the cluster features this hour needs in one go
# ① Managed Entra integration + Azure RBAC (once enabled, the Entra integration cannot be turned off) az aks update -g $RG -n $CLUSTER --enable-aad --aad-admin-group-object-ids $ADMIN_GROUP_ID --enable-azure-rbac # ② OIDC issuer + Workload Identity az aks update -g $RG -n $CLUSTER --enable-oidc-issuer --enable-workload-identity # ③ Key Vault CSI add-on + Azure Policy add-on az aks enable-addons -g $RG -n $CLUSTER --addons azure-keyvault-secrets-provider,azure-policy # ④ Re-fetch (Entra) credentials az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing kubectl get nodes
To sign in, use a web browser to open the page https://microsoft.com/devicelogin … ← or reuse the az login token directly NAME STATUS ROLES AGE VERSION aks-nodepool1-12345678-vmss000000 Ready <none> 3d v1.3x.x aks-nodepool1-12345678-vmss000001 Ready <none> 3d v1.3x.x
clusterUser local credentials still work until you disable local accounts in module 2. Steps ① and ② both trigger control plane updates (usually a few minutes); on clusters in the Free tier, the API server may be briefly unavailable during this time.Costs and cleanup
| Resource | Billing model (illustrative; see the Azure pricing calculator for actual prices) |
|---|---|
| aks-lab (2 D4s_v5-class nodes + control plane tier) | Nodes are billed per VM hour; Standard / Premium tiers have an additional hourly fee per cluster; the Free tier control plane is not charged. |
| Key Vault (Standard) | Billed per operation; reads in this hour usually cost less than US$1 |
| ACR (Basic) | Registry units billed per day + storage |
| Defender for Containers (module 7, optional) | Billed per vCore hour of protected nodes; enabled at the subscription level, and it covers all clusters in the subscription; turn it off after the lab |
| Log Analytics (module 2) | Billed by ingested data volume; kube-audit volume is very large, so the lab uses kube-audit-admin |
# Pause: keep the configuration, stop compute charges az aks stop -g $RG -n $CLUSTER # Full cleanup (only after hour 8; Key Vault has soft delete, so a same-name vault must wait or be purged) az group delete -n $RG --yes --no-wait az ad group delete --group aks-lab-admins; az ad group delete --group aks-lab-myapp-devs
Warm-up: answer from memory (30 seconds)
Does Kubernetes have its own "user" object?
No. Kubernetes only has ServiceAccount objects; "users" and "groups" are just strings that an authenticator passes to the API server. AKS's Entra integration is an authentication webhook that translates Entra tokens into a username and groups (group = the group's objectId).
What changed with ServiceAccount tokens after 1.24?
Long-lived Secret tokens are no longer generated automatically. Pods use projected tokens that kubelet requests through the TokenRequest API (scoped to an audience, with an expiry, rotated automatically). Workload Identity relies on this kind of token, and sets the audience to api://AzureADTokenExchange.
Identity inventory self-check (8 items)
Check off the items your cluster already has in place (saved in this browser). Come back and check them again after you complete the capstone lab.
Module 1 · Entra ID integration with Kubernetes RBAC / Azure RBAC
- Explain the components involved when
kubectl get podsruns after Entra is enabled: the kubelogin exec plugin in kubeconfig → Entra token → API server authentication webhook (guard) → authorization (Kubernetes RBAC or the Azure RBAC webhook). - Choose an authorization mode: Kubernetes RBAC (in-cluster objects, with the group objectId as the subject) or Azure RBAC (ARM role assignments, which can be scoped to a namespace).
- Use the four built-in roles (RBAC Reader / Writer / Admin / Cluster Admin) and a custom role (
DataActions) for namespace-level least-privilege authorization.
What: what AKS's managed Entra integration is
Kubernetes does not manage users itself. It relies on an external authenticator to tell it "who is making this request and which groups they belong to." AKS's managed Entra integration (--enable-aad) has the AKS resource provider manage the server and client apps for you. Users first get an access token from Entra ID, kubectl sends the token to the API server, and the API server validates it through the AKS-managed authentication webhook (log category alias guard), obtaining a username (UPN or object ID) and groups (a list of group objectIds). Authorization afterward takes one of two forms:
| Kubernetes RBAC (Entra authentication + K8s authorization) | Azure RBAC for Kubernetes Authorization (--enable-azure-rbac) | |
|---|---|---|
| Where permissions are stored | Role / ClusterRole / RoleBinding / ClusterRoleBinding inside the cluster | Azure role assignments (ARM); the scope can be the cluster or <cluster ID>/namespaces/<ns> |
| What to write for the subject | User UPN/objectId, or kind: Group + group objectId | Entra users / groups / service principals / managed identities |
| Management tools | kubectl / GitOps | az CLI / portal / Terraform / Azure Policy |
| Multi-cluster consistency | Distributed per cluster | Assigned once at subscription or resource group scope to cover multiple clusters |
| Propagation delay | Immediate | New role assignments take up to about 5 minutes to propagate to the authorization service |
| Prerequisite | Entra integration | Entra integration, and the Entra tenant must be the same as the tenant of the cluster's subscription |
| Fine-grained control for CRDs | Write apiGroups/resources in the Role | Custom role + customresources/read data action; filtering by CRD group/kind requires ABAC conditions (preview) |
AKS Automatic clusters enable Azure RBAC for Kubernetes by default; in AKS Standard it is optional. After enabling Azure RBAC, existing Kubernetes RBAC bindings in the cluster still work, and the two can coexist. A common platform-team practice is "people use Azure RBAC; in-cluster components and ServiceAccounts use Kubernetes RBAC."
Four built-in AKS roles (data plane)
| Role | What it can do | Notes |
|---|---|---|
| Azure Kubernetes Service RBAC Reader | Read-only access to most objects in the namespace | Cannot read Secrets (reading a Secret means obtaining ServiceAccount credentials, which is privilege escalation), and cannot see Role/RoleBinding either |
| Azure Kubernetes Service RBAC Writer | Read and write most objects in the namespace | Cannot modify Role/RoleBinding, but can read Secrets and run Pods as any ServiceAccount, which is equivalent to gaining the permissions of every SA in the namespace |
| Azure Kubernetes Service RBAC Admin | Namespace admin; can create Role/RoleBinding | Cannot write ResourceQuota or the namespace itself |
| Azure Kubernetes Service RBAC Cluster Admin | Superuser; all resources, all namespaces | Only for a small group of platform admins |
Two more control plane roles decide who can "download the kubeconfig": Azure Kubernetes Service Cluster User Role (listClusterUserCredential) and Cluster Admin Role (listClusterAdminCredential, i.e. --admin). With Entra enabled, the user's kubeconfig contains no keys at all, only kubelogin configuration; the actual permissions are still determined by data-plane authorization.
Why: why do it
- Unified identity lifecycle: when an employee leaves, disabling them in Entra takes effect immediately, with no need to revoke certificates on each cluster.
- Conditional Access / MFA / PIM: Entra policies apply naturally to kubectl sign-in (for example, requiring compliant devices, restricting IP ranges, or activating admin groups on demand).
- Auditable: audit logs record real user UPNs rather than shared certificates (module 2).
How: kubelogin
Starting with Kubernetes 1.24, AKS kubeconfig uses the kubelogin exec plugin format by default: each time kubectl needs a token, it runs kubelogin get-token. For interactive use, reuse az login directly. For non-interactive scenarios (CI, jump boxes), use kubelogin convert-kubeconfig -l <mode> to switch the sign-in method; common modes are azurecli, devicecode, spn, msi, and workloadidentity.
When: how to choose
- New clusters and multi-cluster platforms: Azure RBAC as the default (AKS Automatic uses it by default), with groups + namespace-scoped assignments.
- Existing large sets of Kubernetes RBAC manifests and GitOps-managed permissions: keep Kubernetes RBAC and change the subject to the Entra group objectId.
- In either case:
--aad-admin-group-object-idsshould contain only one "platform admin" group, combined with PIM.
Comparison with other clouds
| AKS | EKS | GKE | |
|---|---|---|---|
| Human identity | Entra ID (managed integration) | IAM (Access Entries / legacy aws-auth ConfigMap) | Google accounts / Google Groups for RBAC |
| Cloud-side authorization | Azure RBAC for Kubernetes | EKS Access Policies | IAM roles (cluster-level) + K8s RBAC |
| Client plugin | kubelogin | aws eks get-token | gke-gcloud-auth-plugin |
--admin certificate is still a back door that bypasses Entra (module 2). ② "Giving someone Azure Kubernetes Service Cluster User Role lets them operate the cluster": it only allows downloading the kubeconfig; there are no data-plane permissions, and kubectl returns Forbidden. ③ "Writer is safe because it can't see Secrets": Writer can read Secrets; Reader cannot. ④ "Group changes take effect immediately": the group claim in an Entra token does not change until the token is refreshed, and Azure RBAC role assignment propagation also takes several minutes.Architecture diagram: authentication and authorization for one kubectl request
Decision diagram: Kubernetes RBAC or Azure RBAC?
Interactive simulator: will this request be allowed?
Choose an identity, an authorization mode, and an operation, then step through it. The simulator follows AKS's real order: kubelogin gets a token → guard authenticates → authorization → result. Role assignments and bindings follow this hour's lab setup: aks-lab-admins is the Entra admin group; aks-lab-myapp-devs has the RBAC Writer role on the myapp namespace in Azure RBAC mode, and an edit RoleBinding in Kubernetes RBAC mode; the on-call SRE (a single user) has only RBAC Reader (cluster scope); the CI service principal has only Cluster User Role.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks create/update --enable-aad | Enable managed Entra integration | --aad-admin-group-object-ids (comma-separated), --aad-tenant-id; cannot be turned off once enabled |
az aks update --enable-azure-rbac | Enable Azure RBAC for Kubernetes | --disable-azure-rbac turns it off; AKS Automatic has it enabled by default |
az role assignment create | Assign AKS data-plane roles | --scope $AKS_ID/namespaces/myapp for namespace scoping |
az role definition create | Custom role | DataActions, for example Microsoft.ContainerService/managedClusters/apps/deployments/read |
az aks get-credentials | Generate kubeconfig | Without --admin, this produces Entra user credentials (kubelogin format) |
kubelogin convert-kubeconfig -l | Switch to a non-interactive sign-in method | azurecli / devicecode / spn / msi / workloadidentity |
kubectl auth can-i | Check permissions | --list -n myapp; whoami: kubectl auth whoami |
AKS_ID=$(az aks show -g $RG -n $CLUSTER --query id -o tsv) # Developer group: read/write only within the myapp namespace az role assignment create --role "Azure Kubernetes Service RBAC Writer" \ --assignee-object-id $DEV_GROUP_ID --assignee-principal-type Group \ --scope $AKS_ID/namespaces/myapp # The same group also needs to download kubeconfig (control plane role) az role assignment create --role "Azure Kubernetes Service Cluster User Role" \ --assignee-object-id $DEV_GROUP_ID --assignee-principal-type Group --scope $AKS_ID az role assignment list --scope $AKS_ID/namespaces/myapp -o table
Principal Role Scope ------------------------------------ ------------------------------------- ----------------------------------------------------------- 6b2f… (aks-lab-myapp-devs) Azure Kubernetes Service RBAC Writer /subscriptions/…/managedClusters/aks-lab/namespaces/myapp
kubectl auth whoami kubectl auth can-i --list -n myapp | head
ATTRIBUTE VALUE Username alice@contoso.com Groups [9d1e… (aks-lab-admins objectId) system:authenticated] Extra: oid [3a7c…]
How to verify: after signing in with the developer account, kubectl get pods -n myapp succeeds and kubectl get pods -n kube-system returns Forbidden. Common mistakes: assigning only Cluster User Role with no data-plane role; testing right after creating a role assignment (it can take up to about 5 minutes to propagate). Production use: put role assignments in Terraform/Bicep, together with namespace creation, in the same "tenant onboarding" module.
Kubernetes RBAC version (same effect)
apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: name: myapp-devs-edit namespace: myapp roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: edit # built-in ClusterRole subjects: - apiGroup: rbac.authorization.k8s.io kind: Group name: "<DEV_GROUP_ID>" # the Entra group's objectId, not its display name
Non-interactive sign-in (CI / jump box)
az aks get-credentials -g $RG -n $CLUSTER kubelogin convert-kubeconfig -l azurecli # reuse the identity from az login (in pipelines, run az login --federated-token … first) # Or: run kubectl in a pod that has Workload Identity kubelogin convert-kubeconfig -l workloadidentity
Lab 1: authorize the myapp namespace by Entra group (about 6 minutes)
az aks show -g $RG -n $CLUSTER --query aadProfile -o jsonc
{
"adminGroupObjectIds": [ "9d1e…" ],
"enableAzureRbac": true,
"managed": true,
"tenantId": "72f9…"
}kubectl create namespace myapp AKS_ID=$(az aks show -g $RG -n $CLUSTER --query id -o tsv) az role assignment create --role "Azure Kubernetes Service RBAC Writer" --assignee-object-id $DEV_GROUP_ID --assignee-principal-type Group --scope $AKS_ID/namespaces/myapp az role assignment create --role "Azure Kubernetes Service Cluster User Role" --assignee-object-id $DEV_GROUP_ID --assignee-principal-type Group --scope $AKS_ID
aks-lab-myapp-devs, then run az login as that user in another terminal):
az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing kubectl auth whoami kubectl -n myapp create deployment web --image=nginx:1.27 && kubectl -n myapp get pods kubectl get pods -n kube-system kubectl -n myapp get secrets
deployment.apps/web created NAME READY STATUS RESTARTS AGE web-7c9f8d6b5c-x2k8p 1/1 Running 0 5s Error from server (Forbidden): pods is forbidden: User "dev@contoso.com" cannot list resource "pods" in API group "" in the namespace "kube-system": User does not have access to the resource in Azure. Update role assignment to allow access. NAME TYPE DATA AGE ← RBAC Writer can read Secrets!
The last line shows that the Writer role can read Secrets. If developers should not see secrets, keep myapp's secrets from existing as Kubernetes Secrets (the CSI mount in module 4 does not create a Secret by default), or use a custom role instead.
SUB=$(az account show --query id -o tsv)
cat > deploy-view.json <<EOF
{ "Name": "AKS Deployment Reader (lab)", "Description": "Read deployments only",
"Actions": [], "NotActions": [],
"DataActions": [ "Microsoft.ContainerService/managedClusters/apps/deployments/read" ],
"NotDataActions": [], "assignableScopes": [ "/subscriptions/$SUB" ] }
EOF
az role definition create --role-definition @deploy-view.jsonkubectl -n myapp delete deployment web az role definition delete --name "AKS Deployment Reader (lab)"
The myapp namespace and role assignments are kept for use in later modules.
Case 1: permission drift across 40 clusters
Problem: the platform team distributed RoleBindings to every cluster using Kubernetes RBAC, and an audit found that 9 clusters still had personal account bindings for former employees. Fix: moved everything to Azure RBAC, with all role assignments pointing to Entra groups, created in Terraform's "team onboarding" module scoped by namespace; in-cluster only the ServiceAccount RoleBindings remain. Configuration: --enable-azure-rbac + group assignments + an Azure Policy audit for "cluster does not have Azure RBAC enabled". Limits: role assignments have a per-subscription count limit, so group granularity must be designed carefully; new assignments have a propagation delay of several minutes.
Case 2: admin group accidentally deleted, nobody can access the cluster
Problem: an Entra admin accidentally deleted the aks-admins group, and all cluster admins lost access. Fix: no local account is needed. Anyone with the Microsoft.ContainerService/managedClusters/write permission can repair it with az aks update --aad-admin-group-object-ids <new group> (the official break-glass docs explicitly cover this case). Prevention: put a deletion-protection process around the admin group, manage membership with PIM, and store the group ID in IaC.
Case 3: developer escalates privilege with the Writer role
Problem: a developer created a Pod in their own namespace that uses a ServiceAccount with the same name as argocd-application-controller (the namespace had been reused by mistake). Cause: RBAC Writer can run Pods as any ServiceAccount in the namespace. Fix: separate system components from business workloads by namespace; keep high-privilege SAs only in platform namespaces; for business namespaces, use custom Kubernetes RBAC roles or a Gatekeeper constraint on serviceAccountName.
Common errors and fixes
Error from server (Forbidden): pods is forbidden: User "dev@contoso.com" cannot list resource "pods" … User does not have access to the resource in Azure. Update role assignment to allow access.
Cause: in Azure RBAC mode there is no matching data-plane role assignment, or the assignment scope is wrong (for example, assigned to namespaces/my-app), or the assignment was just created and is still propagating.
az role assignment list --all --assignee dev@contoso.com --query "[?contains(scope,'managedClusters')].{role:roleDefinitionName,scope:scope}" -o table
kubectl auth whoami
Fix: add the missing role assignment and wait about 5 minutes; if the user was just added to the group, have them sign in again (az logout; az login, and delete the kubelogin cache ~/.kube/cache/kubelogin/) to refresh the group claims.
error: unknown command "get-token" for "kubelogin" or exec: executable kubelogin not found
Cause: kubelogin is not installed on the machine, or PATH contains a different tool with the same name (int128/kubelogin).
az aks install-cli which -a kubelogin; kubelogin --version
Fix: install Azure/kubelogin and place it first in PATH; pin the version explicitly in CI.
AADSTS50076 / AADSTS53003: … Conditional Access policy requires …
Cause: an Entra Conditional Access policy (MFA, compliant device, location) blocked token issuance. This happens in Entra, not in AKS.
Fix: complete MFA for interactive sign-in; for automation, use a service principal, managed identity, or workload identity instead (user MFA does not apply), and confirm policy exclusions with the identity team.
You must be logged in to the server (Unauthorized)
Cause: the token expired, the tenant is wrong, or the kubeconfig is still in the old certificate format; or, in Azure RBAC mode, the cluster tenant does not match the subscription tenant.
az account show --query tenantId -o tsv az aks show -g $RG -n $CLUSTER --query aadProfile.tenantId -o tsv az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing
RoleBinding names group "aks-lab-myapp-devs" but has no effect
Cause: the group claim in an Entra token is the objectId, not the display name.
Fix: change the subject's name to the group objectId (az ad group show -g aks-lab-myapp-devs --query id -o tsv). When a user belongs to more than about 200 groups, the token includes a "groups overage" claim, and guard switches to querying Graph; group membership changes are also delayed in this case.
1. Grant the Entra group $GID read-only permission on the payments namespace (Azure RBAC mode).
az role assignment create --role "Azure Kubernetes Service RBAC Reader" --assignee-object-id $GID --assignee-principal-type Group --scope $(az aks show -g $RG -n $CLUSTER --query id -o tsv)/namespaces/payments
2. Have kubectl on a jump box sign in using a managed identity.
az login --identity az aks get-credentials -g $RG -n $CLUSTER kubelogin convert-kubeconfig -l msi # or -l azurecli to reuse az login
The security team requires that "developers can deploy apps but cannot see any production secrets." Can this be done with built-in roles only?
Not fully: Reader cannot deploy, and Writer can read Secrets. Options: ① keep secrets out of Kubernetes Secrets (the Key Vault CSI driver only mounts files, without secretObjects sync, or the app reads Key Vault directly via Workload Identity); ② or use a custom Azure role (granting read/write DataActions only for deployments/services/configmaps, excluding secrets); ③ have deployments go through a GitOps or pipeline identity, and let people have read-only access.
Verified teaching videos
Official documentation
- Enable Microsoft Entra ID authentication for the AKS control plane
- Use Microsoft Entra ID authorization (Azure RBAC) for the Kubernetes API
- Use kubelogin to authenticate users in AKS
- Control access using Kubernetes RBAC and Entra identities
Video storyboard (about 90 seconds)
Scene: a developer types kubectl get pods in a terminal, and a browser sign-in window pops up beside it.
Narration: once Entra integration is enabled, the kubeconfig no longer contains a certificate; kubectl asks Entra for a token through kubelogin.
Scene: the token flies to the API server, and guard stamps "alice, group 9d1e…".
Narration: the API server's authentication webhook validates the token and obtains the user and group object IDs.
Scene: the flow splits into two paths: on the left, a RoleBinding in the cluster; on the right, a role assignment in the Azure portal with the scope reading namespaces/myapp.
Narration: there are two ways to authorize: Kubernetes RBAC, or Azure RBAC. The latter can assign roles directly at namespace scope.
Scene: four role cards; a key icon flashes on the Writer card.
Narration: note that Writer can read Secrets, and Reader cannot. Least privilege has to be designed together with where secrets are stored.
Module 2 · Disable local accounts and access auditing
- Understand AKS "local accounts": the clusterAdmin certificate downloaded by
az aks get-credentials --adminremains valid after Entra is enabled, which makes it an unauditable back door. - Use
--disable-local-accountsto turn it off, and know that existing clusters must rotate the cluster certificates after disabling, along with the official break-glass procedure. - Enable control plane diagnostic logs (
kube-audit-admin,guard), use KQL to answer "who deleted this Deployment", and distinguish the ARM activity log (who downloaded credentials) from the Kubernetes audit log (who called the API).
What: what local accounts are
AKS enables local accounts by default: the control plane issues a clusterAdmin client certificate for the cluster (and a clusterUser one when Entra is not enabled). az aks get-credentials --admin calls the ARM operation listClusterAdminCredential, which returns a kubeconfig with an embedded certificate and private key. The official docs state plainly that even with RBAC or Entra integration enabled, --admin access "still exists as an unauditable back door."
- The certificate's subject belongs to a superuser group such as
system:masters, and it bypasses all RBAC authorization. - The audit log only shows the shared certificate identity (for example
masterclient), not which person used it. - The certificate is long-lived; once copied to someone else or left in CI logs, it cannot be revoked individually.
How: disabling and recovering
| Action | Command | Effect |
|---|---|---|
| Disable on a new cluster | az aks create … --enable-aad --aad-admin-group-object-ids <gid> --disable-local-accounts | properties.disableLocalAccounts=true |
| Disable on an existing cluster | az aks update -g $RG -n $CLUSTER --disable-local-accounts | Afterward, --admin returns Getting static credential isn't allowed because this cluster is set to disable local accounts. |
| Revoke issued certificates | az aks rotate-certs -g $RG -n $CLUSTER | On existing clusters, anyone who previously downloaded the admin certificate still holds a valid certificate, so you must rotate the cluster certificates (this restarts node components, takes about 30 minutes, and causes an interruption) |
| break-glass | --enable-local-accounts → get-credentials --admin → after recovery, --disable-local-accounts | Only for when Entra sign-in itself is unavailable; requires Azure Kubernetes Service Contributor (including managedClusters/write) |
If a cluster without Entra integration sets disableLocalAccounts=true, no user or admin credential can authenticate, so the order is always "Entra first, then disable local accounts." On a cluster with Entra enabled, members of the groups in aad-admin-group-object-ids can still obtain cluster admin rights using non-admin (Entra) credentials.
Auditing: two log layers
| Layer | What it records | Where | Typical question |
|---|---|---|---|
| ARM activity log | Operations on the AKS resource itself: creating or updating the cluster, listClusterAdminCredential, listClusterUserCredential, role assignment changes | Azure Monitor activity log (kept for 90 days by default; can be exported) | "Who downloaded the admin kubeconfig?" "Who re-enabled local accounts?" |
| Kubernetes audit log | Every API request: user, groups, verb, resource, response code | Diagnostic settings → Log Analytics (resource-specific tables AKSAudit, AKSAuditAdmin, AKSControlPlane) | "Who deleted myapp's Deployment?" |
kube-audit: all audit events (including get/list/watch); very high volume and high cost.kube-audit-admin: audit events excluding get and list; the first choice for "who changed what".guard: decision logs for Entra authentication and Azure RBAC authorization, used to troubleshoot "why was this denied".
Why / When
Any production cluster should use "Entra + local accounts disabled + kube-audit-admin + guard." The Azure Policy built-in definition "Kubernetes clusters should have local authentication methods disabled" can audit or deny non-compliant clusters. Local accounts should be briefly enabled only in extreme cases, such as a company-wide Entra outage.
Two credential paths
Audit data flow
Interactive demo: the same operation, two credentials, two audit results
Select the cluster settings first, then click the action buttons in order. The audit log panel on the right simulates the entries that would appear in AKSAuditAdmin and the ARM activity log.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks update --disable-local-accounts | Local accounts disabled | Entra must be enabled first; --enable-local-accounts restores them |
az aks show --query disableLocalAccounts | Check status | true / false |
az aks rotate-certs | Rotate cluster certificates and revoke old certificates | Causes an interruption (node components restart); requires a maintenance window |
az monitor diagnostic-settings create | Export control plane logs | --logs '[{"category":"kube-audit-admin","enabled":true},{"category":"guard","enabled":true}]', --export-to-resource-specific true |
az monitor activity-log list | Query ARM operations | --resource-id $AKS_ID --offset 7d |
az aks update -g $RG -n $CLUSTER --disable-local-accounts --query disableLocalAccounts az aks get-credentials -g $RG -n $CLUSTER --admin
true (BadRequest) … Getting static credential isn't allowed because this cluster is set to disable local accounts.
Enable audit logs
LAW=law-aks-lab
az monitor log-analytics workspace create -g $RG -n $LAW -l $LOC
LAW_ID=$(az monitor log-analytics workspace show -g $RG -n $LAW --query id -o tsv)
AKS_ID=$(az aks show -g $RG -n $CLUSTER --query id -o tsv)
az monitor diagnostic-settings create -n aks-audit --resource $AKS_ID --workspace $LAW_ID \
--export-to-resource-specific true \
--logs '[{"category":"kube-audit-admin","enabled":true},{"category":"guard","enabled":true}]'
KQL: who changed myapp?
AKSAuditAdmin
| where TimeGenerated > ago(1d)
| where ObjectRef has "myapp" and Verb in ("create","update","patch","delete")
| project TimeGenerated, User = tostring(User.username), Verb, Resource = tostring(ObjectRef.resource),
Name = tostring(ObjectRef.name), Code = ResponseStatus.code, SourceIps
| order by TimeGenerated desc
TimeGenerated User Verb Resource Name Code 2026-11-15 09:41:07 alice@contoso.com delete deployments redis 200 2026-11-15 09:12:33 dev@contoso.com patch deployments myapp 200
Note: column names in resource-specific tables depend on the actual schema in your workspace (check with AKSAuditAdmin | getschema). If the diagnostic setting does not select resource-specific mode, data goes into AzureDiagnostics, and you need to filter with Category == "kube-audit-admin" and parse log_s.
Activity log: who has downloaded admin credentials?
az monitor activity-log list --resource-id $AKS_ID --offset 30d \
--query "[?contains(operationName.value,'listClusterAdminCredential')].{time:eventTimestamp, who:caller, status:status.value}" -o table
Lab 2: disable local accounts and trace a delete operation (about 8 minutes + log delay)
az aks get-credentials -g $RG -n $CLUSTER --admin -f ./admin.kubeconfig kubectl --kubeconfig ./admin.kubeconfig auth whoami
ATTRIBUTE VALUE Username masterclient Groups [system:masters system:authenticated]
az aks update -g $RG -n $CLUSTER --disable-local-accounts az aks get-credentials -g $RG -n $CLUSTER --admin -f ./admin2.kubeconfig # expected to fail kubectl --kubeconfig ./admin.kubeconfig get ns # old certificate: still works!
(BadRequest) Getting static credential isn't allowed because this cluster is set to disable local accounts. NAME STATUS AGE default Active 3d …
This step is the point of the lab: disabling only blocks new certificate downloads; certificates already issued remain valid until they are rotated.
az aks rotate-certs -g $RG -n $CLUSTER --yes kubectl --kubeconfig ./admin.kubeconfig get ns az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing # Entra users also need to re-fetch the kubeconfig (the CA has changed)
Unable to connect to the server: tls: failed to verify certificate: x509: certificate signed by unknown authority
kubectl -n myapp create configmap audit-demo --from-literal=a=1 kubectl -n myapp delete configmap audit-demo # After about 5–15 minutes, run the KQL from the "Commands" tab in Log Analytics (change Resource to configmaps)
rm -f ./admin.kubeconfig ./admin2.kubeconfig # Keep the diagnostic settings until hour 7 (the troubleshooting hour uses them); if not needed: # az monitor diagnostic-settings delete -n aks-audit --resource $AKS_ID
Case 1: a "ghost admin" after an outsourcing contract ends
Problem: the outsourcing team left and their Entra accounts were disabled, but the audit log still shows masterclient requests from an external IP. Cause: an outsourcing staff member had downloaded the admin kubeconfig. Fix: immediately run --disable-local-accounts + rotate-certs; enable API server authorized IP ranges or a private cluster (hour 2); use Azure Policy to deny clusters that enable local accounts. Limits: the cluster is interrupted during certificate rotation, so notify stakeholders in advance.
Case 2: audit log costs exceed the cluster cost
Problem: after enabling kube-audit, Log Analytics ingests tens of GB per day (controllers generate a huge number of watch/list calls). Fix: switch to kube-audit-admin + guard, use resource-specific tables plus the basic/auxiliary log plans for long-term data, and turn kube-audit on only temporarily during investigations, sending it to a storage account.
Case 3: break-glass during a regional Entra outage
Fix: prepare a runbook in advance: an emergency account with Azure Kubernetes Service Contributor → --enable-local-accounts → get credentials with --admin → handle the incident → --disable-local-accounts → rotate-certs (can be done in a maintenance window). The activity log records every step above, for review afterward. Limits: the emergency account itself depends on ARM sign-in (you can use a different authentication method, or Lighthouse delegation from another tenant), and the procedure needs regular drills.
Common errors and fixes
Operation failed with status: 'Bad Request'. Details: Getting static credential isn't allowed because this cluster is set to disable local accounts.
Cause: this is expected behavior: local accounts are disabled on the cluster, but a script or pipeline is still using --admin.
Fix: switch the pipeline to a service principal with workload identity federation + kubelogin convert-kubeconfig -l azurecli (or spn / workloadidentity), and assign that identity an Azure RBAC role.
On a cluster without Entra enabled, after running --disable-local-accounts nobody can sign in (a symptom, not an original error message)
Cause: the official docs state that when Entra integration is not enabled and disableLocalAccounts=true, every user or admin credential fails to authenticate.
Fix: first run az aks update --enable-aad --aad-admin-group-object-ids …, confirm the admin group can sign in, and only then disable local accounts.
Unable to connect to the server: x509: certificate signed by unknown authority (after rotating certificates)
Cause: rotate-certs replaced the cluster CA, so the CA in the old kubeconfig is no longer valid.
az aks get-credentials -g $RG -n $CLUSTER --overwrite-existing
External systems inside the cluster that use the old CA (such as Argo CD cluster registration or monitoring scrapers) must also be updated.
AKSAuditAdmin table does not exist / query returns nothing
Cause: the diagnostic setting does not use resource-specific mode (data goes to AzureDiagnostics), the category is not checked, or the data has not arrived yet.
az monitor diagnostic-settings list --resource $AKS_ID -o jsonc
Confirm in the workspace by running AzureDiagnostics | where Category startswith "kube-audit" | take 5.
1. List everyone who has called listClusterAdminCredential in the past 30 days.
az monitor activity-log list --resource-id $AKS_ID --offset 30d --query "[?contains(operationName.value,'listClusterAdminCredential')].{t:eventTimestamp,who:caller}" -o table2. Export only the guard and kube-audit-admin categories to the resource-specific tables.
az monitor diagnostic-settings create -n aks-audit --resource $AKS_ID --workspace $LAW_ID --export-to-resource-specific true --logs '[{"category":"kube-audit-admin","enabled":true},{"category":"guard","enabled":true}]'The audit shows someone used masterclient to delete the production namespace at 02:13 last night. How do you investigate and remediate?
①Use the ARM activity log to check who called listClusterAdminCredential and when, to narrow the scope; ②check the audit log for other requests from the same source IP; ③immediately run --disable-local-accounts + rotate-certs; ④use Azure Policy to block local accounts; ⑤restore the namespace (GitOps replay or backup restore, hour 6); ⑥review why admin credentials were being distributed in the first place.
Verified teaching videos
Official documentation
- Manage local accounts with Microsoft Entra integration
- Certificate rotation in AKS
- Monitor AKS (control plane resource logs)
- AKS monitoring data reference
Video storyboard (about 75 seconds)
Visual: a door labeled Entra, with a small back door on the wall beside it labeled “--admin”.
Narration: Even after you enable Entra, local admin certificates can still bypass all authorization.
Visual: two audit log lines side by side: masterclient and alice@contoso.com.
Narration: When you act with a certificate, the audit log only shows a shared identity, so you can't trace the action to a person.
Visual: running disable-local-accounts seals the back door shut, but one person is still holding an old key.
Narration: Disabling only blocks new certificates from being downloaded. Certificates already issued stay valid until you rotate the cluster certificates.
Visual: diagnostic settings send kube-audit-admin and guard to Log Analytics.
Narration: Finally, export the audit and guard logs, so every change can be traced.
Module 3 · Workload Identity (Microsoft Entra Workload ID)
- Trace the full token exchange chain: OIDC issuer (cluster) → projected ServiceAccount token (kubelet) → federated credential matches
iss/sub/aud(Entra) → access token → Key Vault authorizes via Azure RBAC. - Know what the mutating webhook injects:
AZURE_CLIENT_ID,AZURE_TENANT_ID,AZURE_FEDERATED_TOKEN_FILE,AZURE_AUTHORITY_HOST, and the projected volume. Know why the Pod must carry theazure.workload.identity/use: "true"label. - Set up
id-myappandmyapp/myapp-safor myapp, and quickly identify which link in the chain failed based on errors such asAADSTS70021,AADSTS700212, andForbiddenByRbac.
What: what Workload Identity solves
Pods that need to reach Entra-protected resources such as Key Vault, Storage, or Service Bus need an Entra identity. The older approaches either stored a service principal client secret in a Kubernetes Secret, which is a long-lived key, or used aad-pod-identity to intercept IMDS, which depended on the node-level NMI component (and that was deprecated on 2022-10-24). Microsoft Entra Workload ID uses the Kubernetes-native ServiceAccount token volume projection and OIDC federation. The AKS cluster acts as the token issuer. Entra ID fetches the cluster's public keys from the OIDC discovery document to verify the ServiceAccount token, then issues an Entra access token. Throughout, no secret is stored in the cluster.
How: five components
| Component | Where | Purpose |
|---|---|---|
OIDC issuer (--enable-oidc-issuer) | Managed by AKS. URL looks like https://{region}.oic.prod-aks.azure.com/{tenant}/{uuid}/ | Serves /.well-known/openid-configuration and /openid/v1/jwks (public keys), and is the iss of SA tokens |
Workload Identity webhook (--enable-workload-identity) | Mutating admission webhook in kube-system | Only modifies Pods labeled azure.workload.identity/use: "true": injects environment variables and the projected token volume |
| User-assigned managed identity (or app registration) | Azure: id-myapp | The Entra identity that is actually authorized to access resources |
| Federated identity credential (FIC) | Attached to id-myapp | Declares "trust this issuer to issue tokens for this subject, with audience api://AzureADTokenExchange" |
| ServiceAccount annotation | myapp/myapp-sa: azure.workload.identity/client-id | Tells the webhook which client ID to inject |
The 8 steps of the token exchange (matches the Animation tab)
- The admin creates
id-myapp, a federated credential (issuer = cluster OIDC URL, subject =system:serviceaccount:myapp:myapp-sa, audience =api://AzureADTokenExchange), and assigns it Key Vault Secrets User. - The Pod creation request passes through the webhook, which injects
AZURE_CLIENT_ID(from the SA annotation),AZURE_TENANT_ID,AZURE_FEDERATED_TOKEN_FILE,AZURE_AUTHORITY_HOST, and aserviceAccountTokenprojected volume (audienceapi://AzureADTokenExchange, defaultexpirationSeconds: 3600). - The kubelet requests a token for the Pod through the TokenRequest API. The API server signs a JWT with the cluster's SA signing private key and writes it to the projected volume. The kubelet refreshes it automatically before it expires.
- The Azure Identity SDK in the app (
WorkloadIdentityCredential/DefaultAzureCredential) reads the token file, then sends a request tologin.microsoftonline.com/{tenant}/oauth2/v2.0/tokenfor a client credentials grant. It uses the SA token as theclient_assertionand sets the scope tohttps://vault.azure.net/.default. - Entra looks up the federated credential for
id-myappbyclient_id, then checks the token'siss,sub, andaudagainst it one by one. - Entra reads the issuer's OIDC discovery document and JWKS, and uses the public key to verify the signature and validity period.
- Validation passes, and Entra issues an access token for
id-myapp(audiencehttps://vault.azure.net, lifetime set by Entra). - The app calls Key Vault with the access token. Key Vault checks via Azure RBAC whether
id-myapphassecrets/getSecret/action, and returns the secret.
Quick reference: annotations and labels
| Key | Location | Notes |
|---|---|---|
azure.workload.identity/use: "true" | Pod label (required) | Without it, the webhook doesn't modify the Pod. The official docs describe this as a "fail close" design: if it's missing, the Pod fails after a restart. |
azure.workload.identity/client-id | SA annotation | Client ID of the managed identity or app to use |
azure.workload.identity/tenant-id | SA annotation (optional) | Defaults to the tenant from the azure-wi-webhook-config ConfigMap |
azure.workload.identity/service-account-token-expiration | SA or Pod annotation (optional) | expirationSeconds for the projected token. Default 3600, range 3600–86400. Pod annotation takes precedence. |
azure.workload.identity/skip-containers | Pod annotation (optional) | Semicolon-separated. Excludes certain containers from receiving the token (for example, sidecars). |
azure.workload.identity/inject-proxy-sidecar | Pod annotation (optional) | Injects a proxy sidecar that intercepts IMDS requests. Used for legacy SDKs migrating from pod identity. |
Why: advantages over other approaches
| Approach | Secret | Granularity | Status |
|---|---|---|---|
| Service principal password in a Secret | Long-lived key, needs rotation | Anyone who can read the Secret can impersonate it | Not recommended |
| kubelet / node managed identity (IMDS) | None | Shared by all Pods on the node | Only suitable for platform components |
| aad-pod-identity | None | Per Pod, but relies on NMI interception | Deprecated 2022-10-24 |
| Workload Identity | None (short-lived tokens) | Per ServiceAccount | GA, recommended. Provisioned by default in AKS Automatic |
When: limits and new changes
- Each managed identity supports up to 20 federated credentials. After you add a federated credential, it takes a few seconds to propagate, so an immediate token request may fail.
- Not supported with the virtual nodes add-on. Creating federated credentials on user-assigned managed identities is not supported in some regions (see the official list).
- After you change an SA annotation, you must restart the Pod for it to take effect, because injection happens when the Pod is created.
- The scope must use the v2 format
<resource>/.default. Using a resource URI directly may fail. - Don't hardcode the token path
/var/run/secrets/azure/tokens/azure-identity-tokenin your code. Always read the environment variableAZURE_FEDERATED_TOKEN_FILE, and reread the file on every exchange (the kubelet refreshes it in place). - Identity bindings: let multiple clusters share one user-assigned managed identity through a single federated credential, which gets around the "20 FIC" limit. Once enabled, the default token audience becomes
api://AKSIdentityBinding. If the same Pod also federates directly, you need an extra projected token with audienceapi://AzureADTokenExchange. Otherwise you getAADSTS700212. - Minimum SDK versions: Python
azure-identity1.13.0, .NET 1.9.0, Java 1.9.0, Go azidentity 1.3.0, Node.js 3.2.0.
system:serviceaccount:<namespace>:<SA name>, so every Pod using the same SA shares the identity. The SA is the security boundary. ③ "Entra needs to reach my API server." No. Entra accesses the public OIDC discovery endpoint managed by AKS, so private clusters work too. ④ "The federated credential still works after I rebuild the cluster." No. A new cluster has a different issuer URL (each cluster has an immutable random GUID), so the federated credential must be updated.Architecture diagram: trust relationships and token flow
Comparing two tokens
{
"aud": ["api://AzureADTokenExchange"],
"exp": 1763201200,
"iat": 1763197600,
"iss": "https://canadacentral.oic.prod-aks.azure.com/72f9…/1b0e…/",
"kubernetes.io": {
"namespace": "myapp",
"pod": { "name": "myapp-6d4b…", "uid": "…" },
"serviceaccount": { "name": "myapp-sa", "uid": "…" }
},
"sub": "system:serviceaccount:myapp:myapp-sa"
}
{
"aud": "https://vault.azure.net",
"iss": "https://sts.windows.net/72f9…/",
"appid": "<clientId of id-myapp>",
"oid": "<principalId of id-myapp>",
"idtyp": "app",
"xms_mirid": "…/userAssignedIdentities/id-myapp",
"exp": 1763284000
}
① Issued by the cluster and consumed by Entra; ② issued by Entra and consumed by Key Vault. The lifetimes of the two are independent of each other.
Core animation: Workload Identity token exchange (with fault injection)
Step through the 8 steps one at a time. At each step, the participating components are highlighted, and real request/response snippets and the key claims of the current token are shown. Pick a "fault," replay, and watch which step fails and what error is returned.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks update --enable-oidc-issuer --enable-workload-identity | Enable the OIDC issuer and webhook | CLI 2.47.0+; --disable-workload-identity turns it off |
az aks show --query oidcIssuerProfile.issuerUrl | Get the issuer URL | Unique to each cluster and immutable |
az identity create | Create a user-assigned managed identity | Record the clientId (for the SA) and the principalId (for role assignments) |
az identity federated-credential create | Create a federated credential | --issuer, --subject system:serviceaccount:ns:sa, --audience api://AzureADTokenExchange |
az identity federated-credential list | Check existing federated credentials | Watch the limit of 20 |
az role assignment create | Authorize the target resource | --assignee-object-id <principalId> --assignee-principal-type ServicePrincipal (avoids Graph lookup and replication delay issues) |
source ~/.aks-lab.env; RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab; UAMI=id-myapp; NS=myapp; SA=myapp-sa AKS_OIDC_ISSUER=$(az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv) az identity create -g $RG -n $UAMI -l $LOC UAMI_CLIENT_ID=$(az identity show -g $RG -n $UAMI --query clientId -o tsv) UAMI_PRINCIPAL_ID=$(az identity show -g $RG -n $UAMI --query principalId -o tsv) az identity federated-credential create -g $RG --identity-name $UAMI --name fic-aks-lab-myapp \ --issuer "$AKS_OIDC_ISSUER" --subject system:serviceaccount:$NS:$SA --audience api://AzureADTokenExchange az identity federated-credential list -g $RG --identity-name $UAMI -o table
Issuer Name Subject Audiences ------------------------------------------------------------------ ------------------ -------------------------------------- --------------------------- https://canadacentral.oic.prod-aks.azure.com/72f9…/1b0e…/ fic-aks-lab-myapp system:serviceaccount:myapp:myapp-sa ['api://AzureADTokenExchange']
apiVersion: v1
kind: ServiceAccount
metadata:
name: myapp-sa
namespace: myapp
annotations:
azure.workload.identity/client-id: "<UAMI_CLIENT_ID>"
# Check what the webhook did to the Pod
kubectl -n myapp get pod POD -o jsonpath='{range .spec.containers[0].env[*]}{.name}={.value}{"\n"}{end}'
kubectl -n myapp get pod POD -o jsonpath='{.spec.volumes[?(@.name=="azure-identity-token")]}' ; echo
AZURE_CLIENT_ID=5c3e…
AZURE_TENANT_ID=72f9…
AZURE_FEDERATED_TOKEN_FILE=/var/run/secrets/azure/tokens/azure-identity-token
AZURE_AUTHORITY_HOST=https://login.microsoftonline.com/
{"name":"azure-identity-token","projected":{"defaultMode":420,"sources":[{"serviceAccountToken":{"audience":"api://AzureADTokenExchange","expirationSeconds":3600,"path":"azure-identity-token"}}]}}
How to verify: If you see these 4 variables and the projected volume, the webhook is working. If not, check the Pod labels. Common error: putting use: "true" in the metadata of the ServiceAccount or Deployment, instead of in the labels of the Pod template. Production use: manage FICs together with the cluster using the Terraform azurerm_federated_identity_credential resource, so the issuer stays consistent after a cluster rebuild.
Lab 3: myapp reads Key Vault using id-myapp (about 10 minutes)
az keyvault create -g $RG -n $KV -l $LOC --enable-rbac-authorization true KV_ID=$(az keyvault show -n $KV --query id -o tsv) ME=$(az ad signed-in-user show --query id -o tsv) az role assignment create --assignee-object-id $ME --assignee-principal-type User --role "Key Vault Secrets Officer" --scope $KV_ID sleep 60 # Role assignment propagation (official docs say it can take up to 10 minutes; retry on 403) az keyvault secret set --vault-name $KV -n redis-password --value "$(openssl rand -base64 24)" --query name -o tsv
az role assignment create --assignee-object-id $UAMI_PRINCIPAL_ID --assignee-principal-type ServicePrincipal \ --role "Key Vault Secrets User" --scope $KV_ID
kubectl create namespace myapp --dry-run=client -o yaml | kubectl apply -f -
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: myapp-sa
namespace: myapp
annotations:
azure.workload.identity/client-id: "$UAMI_CLIENT_ID"
---
apiVersion: v1
kind: Pod
metadata:
name: wi-check
namespace: myapp
labels:
azure.workload.identity/use: "true"
spec:
serviceAccountName: myapp-sa
containers:
- name: cli
image: mcr.microsoft.com/azure-cli:2.67.0
command: ["sleep", "3600"]
env:
- { name: KV, value: "$KV" }
EOF
kubectl -n myapp wait --for=condition=Ready pod/wi-check --timeout=120skubectl -n myapp exec wi-check -- sh -c 'cut -d. -f2 $AZURE_FEDERATED_TOKEN_FILE | tr "_-" "/+" | base64 -d 2>/dev/null; echo'
{"aud":["api://AzureADTokenExchange"],"exp":1763201200,"iss":"https://canadacentral.oic.prod-aks.azure.com/72f9…/1b0e…/","sub":"system:serviceaccount:myapp:myapp-sa", …}kubectl -n myapp exec wi-check -- sh -c '
AT=$(curl -s -X POST "${AZURE_AUTHORITY_HOST}${AZURE_TENANT_ID}/oauth2/v2.0/token" \
-d client_id=$AZURE_CLIENT_ID -d grant_type=client_credentials \
-d scope=https://vault.azure.net/.default \
-d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
--data-urlencode client_assertion@$AZURE_FEDERATED_TOKEN_FILE | sed -n "s/.*\"access_token\":\"\([^\"]*\)\".*/\1/p")
echo "access_token length: ${#AT}"
curl -s -H "Authorization: Bearer $AT" "https://$KV.vault.azure.net/secrets/redis-password?api-version=7.4" | head -c 120; echo'
access_token length: 1689
{"value":"k3Jx…","id":"https://kv-aks-lab-9312.vault.azure.net/secrets/redis-password/0c6f…","attributes":{…kubectl -n myapp exec wi-check -- sh -c 'az login --service-principal -u $AZURE_CLIENT_ID -t $AZURE_TENANT_ID \ --federated-token "$(cat $AZURE_FEDERATED_TOKEN_FILE)" --allow-no-subscriptions -o none && \ az keyvault secret show --vault-name $KV -n redis-password --query "attributes.enabled"'
true
In myapp's Python code, you only need SecretClient(vault_url, DefaultAzureCredential()). azure-identity ≥ 1.13.0 uses these environment variables automatically. In Module 4, we switch to the CSI driver, so the application code doesn't change at all.
myapp-sa2, recreate the Pod, repeat step 5, and observe AADSTS70021. After you restore it, delete the verification Pod:
kubectl -n myapp delete pod wi-check
Case 1: migrating from client secrets to Workload Identity
Problem: 30 microservices each use a service principal password to access Storage. The password is rotated once a year and often breaks when it expires. Approach: one user-assigned managed identity and one SA per service; upgrade the app to a supported Azure Identity version and switch to DefaultAzureCredential; for old SDKs, use the inject-proxy-sidecar annotation as a temporary bridge. Config: a Terraform module outputs the client_id, which is written into the SA annotation in the Helm values. Limits: the proxy sidecar is not a long-term solution, and you must roll-restart after changing annotations.
Case 2: all requests return 403/401 after switching to a blue-green cluster
Problem: after creating the new cluster aks-prod-b, every app reports AADSTS70021. Cause: the federated credential's issuer still points to the old cluster URL. Approach: add a second federated credential for the new cluster on the same identity (both issuers coexist), then delete the old one once the cutover is complete. Limits: 20 FICs per identity; platforms with many clusters should switch to identity bindings, so multiple clusters share one FIC.
Case 3: one SA shared by multiple teams
Problem: for convenience, several apps share the default SA and are bound to the same high-privilege identity. Approach: give each app its own SA and identity. Use a Gatekeeper constraint to block Pods labeled use: "true" from using the default SA. For Key Vault secrets, split them by app into separate vaults, or use secret-level RBAC scopes.
Common errors and fixes
AADSTS70021: No matching federated identity record found for presented assertion.
Cause: the token's iss or sub doesn't exactly match the federated credential: a namespace or SA name typo, a trailing slash on the issuer, an issuer that changed after a cluster rebuild, or a federated credential that was just created and hasn't propagated yet.
az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv
az identity federated-credential list -g $RG --identity-name id-myapp --query "[].{issuer:issuer,subject:subject,aud:audiences}" -o jsonc
kubectl -n myapp get pod POD -o jsonpath='{.spec.serviceAccountName}'
Fix: make the three values match character for character, and wait a few seconds after creation before requesting again.
AADSTS700212: No matching federated identity record found for presented assertion audience 'api://AKSIdentityBinding'.
Cause: the token audience doesn't match the federated credential's audience. Typical scenario: after identity bindings are enabled, the default token audience becomes api://AKSIdentityBinding, but the code still uses it for direct federation.
Fix: project an extra token with audience api://AzureADTokenExchange and have the direct-federation code read it; or switch to access through identity bindings.
DefaultAzureCredential failed to retrieve a token … WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured.
Cause: the webhook didn't inject the environment variables. The Pod template is missing the azure.workload.identity/use: "true" label, the SA is missing the client-id annotation, or the Pod was created before Workload Identity was enabled.
kubectl -n myapp get pod POD --show-labels kubectl -n myapp get sa myapp-sa -o yaml | grep workload.identity kubectl -n kube-system get pods | grep azure-wi-webhook
Fix: add the label or annotation, then restart the Pod.
(Forbidden) Caller is not authorized to perform action on resource. … Action: 'Microsoft.KeyVault/vaults/secrets/getSecret/action' … Code: ForbiddenByRbac
Cause: the token exchange succeeded, but id-myapp doesn't have a Key Vault data-plane role (or the role was assigned at the wrong scope, or Key Vault uses the access policy model).
az role assignment list --assignee $UAMI_PRINCIPAL_ID --all -o table az keyvault show -n $KV --query properties.enableRbacAuthorization
Fix: assign Key Vault Secrets User, then wait for propagation (official docs say it can take up to 10 minutes).
AADSTS700016: Application with identifier '…' was not found in the directory
Cause: the client-id in the SA annotation is wrong (for example, the principalId or objectId was used instead), or the identity is in another tenant.
Fix: verify with az identity show -g $RG -n id-myapp --query clientId -o tsv, correct the annotation, then restart the Pod.
1. Create a federated credential on identity id-payments for the SA api-sa in the namespace payments.
az identity federated-credential create -g $RG --identity-name id-payments --name fic-aks-lab-payments \ --issuer "$(az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv)" \ --subject system:serviceaccount:payments:api-sa --audience api://AzureADTokenExchange
2. Use one command to confirm whether a Pod was injected by the webhook.
kubectl -n myapp get pod POD -o jsonpath='{.spec.containers[0].env[?(@.name=="AZURE_FEDERATED_TOKEN_FILE")].value}'The platform runs 60 AKS clusters. The same app is deployed to all of them and uses the same managed identity. Now the app reports AADSTS70021. What is the cause, and what is the long-term fix?
Each cluster has its own issuer, so each cluster needs its own FIC, and a single identity supports at most 20 FICs. A deployment spanning more than 20 clusters can't match them all. Long-term fix: use identity bindings so multiple clusters share one FIC, or split identities by region or environment. Also include FIC creation in the cluster creation pipeline.
Verified teaching videos
Official documentation
- Use Microsoft Entra Workload ID on AKS
- Deploy and configure an AKS cluster with Workload ID
- Identity bindings concepts
- azure-workload-identity project docs
Video storyboard (about 100 seconds)
Visual: the Pod's pocket is empty, with a crossed-out "client secret" beside it.
Narration: Workload Identity lets a Pod access Azure without carrying any secret.
Visual: the webhook attaches four environment variables to the Pod, and the kubelet places a ticket reading aud=api://AzureADTokenExchange inside it.
Narration: A labeled Pod gets environment variables and a short-lived token issued by the cluster.
Visual: the Pod hands the ticket to an Entra window. Behind it, a clerk checks iss, sub, and aud against the federated credentials register, then fetches the public key from the cluster's public address to verify the signature.
Narration: Entra checks the issuer, the subject, and the audience, and verifies the signature with the cluster's published public key.
Visual: Entra issues a pass reading vault.azure.net, and the Pod uses it to enter Key Vault. The gatekeeper checks the RBAC list and lets it through.
Narration: The access token goes to Key Vault, which then decides, based on Azure RBAC, whether to allow access.
Module 4 · Key Vault secret store CSI driver
- Understand the two components: the Secrets Store CSI Driver (DaemonSet
aks-secrets-store-csi-driver) and the Azure provider (DaemonSetaks-secrets-store-provider-azure), plus theSecretProviderClassCRD. - Know how identity is chosen for a SecretProviderClass: Workload ID (recommended, uses
clientID), the add-on's own user-assigned managed identity (useVMManagedIdentity), or Service Connector. - Understand auto-rotation (
--enable-secret-rotation, defaultrotationPollInterval2m), the lifecycle ofsecretObjectssyncing, and that environment variables andsubPathmounts don't update automatically.
What: what the CSI driver does
The Azure Key Vault provider for Secrets Store CSI Driver uses Key Vault as an external secret store and mounts secrets, keys, and certificates into the Pod as a CSI volume. Features (per the official list): CSI inline volumes, multiple objects in one volume, Pod portability through the SecretProviderClass CRD, Windows containers, syncing to Kubernetes Secrets, and auto-rotation of both mounted content and synced Secrets.
How: mount sequence
- The Pod is scheduled to a node, and the kubelet calls CSI
NodePublishVolume(driversecrets-store.csi.k8s.io). - The driver reads the
SecretProviderClassreferenced by the Pod, requests a token for the Pod's ServiceAccount, and calls the Azure provider over gRPC (Unix socket). - The provider gets an Entra access token based on the SecretProviderClass parameters. In Workload ID mode, it does the exchange with the SA token (the same flow as Module 3, so the app doesn't need an SDK). In managed identity mode, it goes through the node's IMDS.
- The provider reads the objects listed under
objectsfrom Key Vault and returns them to the driver. The driver writes the content to the Pod's tmpfs mount point (for example/mnt/secrets-store/redis-password). - If
secretObjectsis defined, the driver creates or updates the matching Kubernetes Secret. It only appears after at least one Pod has mounted the volume, and it is deleted after all Pods using it are removed. - With rotation enabled, the driver re-fetches every
rotationPollIntervaland updates the mounted content and the synced Secret.
Important: if a Pod can't mount the volume, it can't start (ContainerCreating + FailedMount events). Key Vault is a hard dependency, so consider its network reachability (private endpoints, firewall FQDNs) and throttling.
Three identity options
| Option | SecretProviderClass parameters | Granularity | Recommendation |
|---|---|---|---|
| Workload ID | usePodIdentity: "false", clientID: <UAMI clientId>; the Pod uses an annotated SA (the official example also labels the Pod use: "true") | Per SA | Recommended; identity bindings are also supported |
| User-assigned managed identity (the add-on identity, or a self-created identity assigned to the VMSS) | useVMManagedIdentity: "true", userAssignedIdentityID: <clientId> | Shared by all Pods on the node | Only for platform-level, low-sensitivity secrets |
| Service Connector | Generated by az aks connection create keyvault --enable-csi | Depends on configuration | Quick start |
When the add-on is enabled, AKS creates a user-assigned managed identity named azurekeyvaultsecretsprovider-xxxxx in the node resource group (MC_) and assigns it to the VMSS. You can't prevent it from being created. You can leave it without any Key Vault permissions.
Key Vault role
objectType: secret→ Key Vault Secrets User;key/cert→ Key Vault Certificate User (required by the official docs).- Certificate objects:
certreturns the certificate (PEM, without the chain);keyreturns the public key;secretreturns the private key plus the certificate chain (PEM).
Why / When: CSI mount vs. direct SDK read vs. Kubernetes Secret
| CSI mount (no sync) | CSI + secretObjects sync | App uses WI and reads directly via SDK | Direct Kubernetes Secret | |
|---|---|---|---|---|
| App changes | Reads files | Reads environment variables or files (zero changes) | Needs SDK code | None |
| Secrets stored in etcd? | No | Yes (Secret object) | No | Yes |
| Can RBAC Writer read it? | Requires exec into the Pod | Yes (reads the Secret) | No | Yes |
| Rotation | Files update automatically (app must reread) | Secret updates; env requires Pod restart | App-controlled | Manual |
| When Key Vault is unavailable | New Pods can't start | Same as left | App handles it | Not affected |
Components and data flow
Timeline simulation: after updating a secret in Key Vault
At t=0 the Pod is already running. Click "Write new version in Key Vault," then advance time. Watch when the mounted file, the synced Secret, the environment variable, and the subPath mount each change.
| Location | Current value | Notes |
|---|---|---|
| Key Vault redis-password | v1 | Current version of the secret |
| /mnt/secrets-store/redis-password | v1 | CSI volume file |
| Secret redis-auth (secretObjects) | v1 | Synced Kubernetes Secret |
| Container environment variable REDIS_PASSWORD | v1 | Read at process start |
| subPath-mounted /etc/redis/pass | v1 | Kubernetes limitation: not updated on rotation |
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks enable-addons --addons azure-keyvault-secrets-provider | Enable add-on | For a new cluster, use az aks create --enable-addons … |
az aks addon update --addon azure-keyvault-secrets-provider | Modify configuration | --enable-secret-rotation, --rotation-poll-interval 5m |
az aks show --query addonProfiles.azureKeyvaultSecretsProvider | View configuration and add-on identity | config.enableSecretRotation, rotationPollInterval |
kubectl get secretproviderclass,secretproviderclasspodstatus -n myapp | View SPC and per-Pod mount status | podstatus records the mounted object versions |
az aks disable-addons --addons azure-keyvault-secrets-provider | Disable the add-on | Errors if SecretProviderClasses exist. Running Pods are unaffected, but new Pods will fail to start. |
az aks addon update -g $RG -n $CLUSTER --addon azure-keyvault-secrets-provider --enable-secret-rotation --rotation-poll-interval 2m az aks show -g $RG -n $CLUSTER --query addonProfiles.azureKeyvaultSecretsProvider.config kubectl get pods -n kube-system -l 'app in (secrets-store-csi-driver,secrets-store-provider-azure)' -o wide
{
"enableSecretRotation": "true",
"rotationPollInterval": "2m"
}
NAME READY STATUS RESTARTS AGE NODE
aks-secrets-store-csi-driver-4vpkj 3/3 Running 0 2d aks-nodepool1-…-vmss000000
aks-secrets-store-provider-azure-5p4nb 1/1 Running 0 2d aks-nodepool1-…-vmss000000
…
SecretProviderClass (Workload ID mode)
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
name: myapp-kv
namespace: myapp
spec:
provider: azure
parameters:
usePodIdentity: "false"
clientID: "<UAMI_CLIENT_ID>" # id-myapp
keyvaultName: "<KV>" # kv-aks-lab-<suffix>
tenantId: "<TENANT_ID>"
objects: |
array:
- |
objectName: redis-password
objectType: secret
objectVersion: ""
secretObjects: # optional: sync as a Kubernetes Secret
- secretName: redis-auth
type: Opaque
data:
- objectName: redis-password
key: password
How to verify: kubectl exec into the Pod and check /mnt/secrets-store; kubectl get secret redis-auth. Common errors: secretObjects[].data[].objectName must match the mounted file name (or objectAlias). If the object doesn't exist in Key Vault, the entire mount fails. Metrics: the provider exposes Prometheus metrics on port 8898 and the driver on port 8095 (not exposed externally by default), such as keyvault_request and total_rotation_reconcile_error.
Lab 4: Redis password comes from Key Vault (about 8 minutes)
source ~/.aks-lab.env; RG=rg-aks-lab; CLUSTER=aks-lab UAMI_CLIENT_ID=$(az identity show -g $RG -n id-myapp --query clientId -o tsv) TENANT_ID=$(az account show --query tenantId -o tsv)
cat <<EOF | kubectl apply -f -
apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata: { name: myapp-kv, namespace: myapp }
spec:
provider: azure
parameters:
usePodIdentity: "false"
clientID: "$UAMI_CLIENT_ID"
keyvaultName: "$KV"
tenantId: "$TENANT_ID"
objects: |
array:
- |
objectName: redis-password
objectType: secret
secretObjects:
- secretName: redis-auth
type: Opaque
data:
- { objectName: redis-password, key: password }
EOFredis-auth is kept for myapp in Module 5 to use as an environment variable):
apiVersion: apps/v1
kind: Deployment
metadata: { name: redis, namespace: myapp, labels: { app: redis } }
spec:
replicas: 1
selector: { matchLabels: { app: redis } }
template:
metadata:
labels: { app: redis, azure.workload.identity/use: "true" }
spec:
serviceAccountName: myapp-sa
containers:
- name: redis
image: redis:7.4
args: ["sh", "-c", "exec redis-server --requirepass \"$(cat /mnt/secrets-store/redis-password)\""]
ports: [ { containerPort: 6379 } ]
resources: { requests: { cpu: 100m, memory: 128Mi }, limits: { memory: 256Mi } }
volumeMounts: [ { name: kv, mountPath: /mnt/secrets-store, readOnly: true } ]
readinessProbe: { tcpSocket: { port: 6379 }, periodSeconds: 5 }
livenessProbe: { tcpSocket: { port: 6379 }, periodSeconds: 10 }
volumes:
- name: kv
csi:
driver: secrets-store.csi.k8s.io
readOnly: true
volumeAttributes: { secretProviderClass: myapp-kv }
---
apiVersion: v1
kind: Service
metadata: { name: redis, namespace: myapp }
spec: { selector: { app: redis }, ports: [ { port: 6379 } ] }
kubectl apply -f redis.yaml kubectl -n myapp rollout status deploy/redis kubectl -n myapp exec deploy/redis -- ls /mnt/secrets-store kubectl -n myapp get secret redis-auth kubectl -n myapp exec deploy/redis -- sh -c 'redis-cli -a "$(cat /mnt/secrets-store/redis-password)" --no-auth-warning ping'
deployment "redis" successfully rolled out redis-password NAME TYPE DATA AGE redis-auth Opaque 1 20s PONG
The Redis process reads the file at startup, so Redis's own password does not change automatically on rotation. This is exactly what the next step uses to show that the file changed but the process did not.
az keyvault secret set --vault-name $KV -n redis-password --value "$(openssl rand -base64 24)" -o none
sleep 150
kubectl -n myapp exec deploy/redis -- sh -c 'md5sum /mnt/secrets-store/redis-password'
kubectl -n myapp get secretproviderclasspodstatus -o jsonpath='{.items[0].status.objects}'; echo
The file contents and the object version in podstatus are updated, but Redis still uses the old password because the process wasn't restarted. After running kubectl -n myapp rollout restart deploy/redis, the new password takes effect. In production, have the app watch the file for changes, or use a tool that performs a rolling restart on Secret changes.
Case 1: Key Vault throttling leaves many Pods stuck in ContainerCreating during scale-out
Problem: a promotion scales to 400 Pods, each mounting 12 objects, with a 30s poll interval, and Key Vault returns 429. Approach: consolidate objects (one JSON secret instead of many small ones), change polling to 5–10 minutes, split Key Vault per application, and monitor the keyvault_request metric. Limits: Key Vault has a transaction quota per vault, so estimate poll frequency × Pod count × object count in advance.
Case 2: Ingress still uses the old TLS certificate after rotation
Problem: the certificate was renewed in Key Vault, and CSI updated the file, but the NGINX process only reads the certificate at startup. Approach: use the synced kubernetes.io/tls Secret for the Ingress controller (the controller watches Secrets), and enable rotation; or switch to native Key Vault integration with the application routing add-on (hour 2).
Case 3: developers can read production database passwords
Problem: to avoid any code changes, the team enabled secretObjects sync for all secrets, and the developer group has RBAC Writer. Approach: mount highly sensitive secrets as files only, with no sync; have the app read the file; or have the app use Workload ID and the SDK directly to read the secret.
Common errors and fixes
MountVolume.SetUp failed for volume "kv" : rpc error: code = Unknown desc = failed to mount secrets store objects for pod myapp/redis-…, err: rpc error: code = Unknown desc = failed to mount objects, error: failed to get objectType:secret, objectName:redis-password … StatusCode=403
Cause: the identity used by the SecretProviderClass has no Key Vault data-plane permissions (in WI mode, the identity matching clientID), or the Key Vault network firewall is blocking access.
kubectl -n myapp describe pod -l app=redis | sed -n '/Events/,$p' kubectl -n kube-system logs -l app=secrets-store-provider-azure --tail=50
Fix: assign Key Vault Secrets User (or Certificate User); for a private Key Vault, configure a private endpoint and DNS.
… StatusCode=404 … SecretNotFound: A secret with (name/id) redis-pasword was not found in this key vault
Cause: objectName is misspelled, or the object hasn't been created yet. The entire volume mount fails, and the Pod can't start.
Fix: create the object in Key Vault before deploying, and make sure spelling and casing match.
failed to get keyvault client: … AADSTS70021: No matching federated identity record found …
Cause: in WI mode, the Pod's SA doesn't match the federated credential subject (for example, the Pod uses the default SA).
Fix: change the Pod's serviceAccountName to myapp-sa, or add a federated credential for the new SA.
secret "redis-auth" not found (the Pod's env references the synced Secret)
Cause: a synced Secret is only created after a Pod successfully mounts the CSI volume. If the Pod that references it has no CSI volume mount of its own, or the mount fails, the Secret doesn't exist.
Fix: the Pod that references the Secret must also mount the CSI volume itself; resolve the mount error first.
failed to disable addon … SecretProviderClass is in use
Cause: per the official docs, disabling the add-on while SecretProviderClasses exist produces an error.
Fix: migrate or delete the SecretProviderClasses first, then disable the add-on.
1. Change the rotation poll interval to 5 minutes and confirm it.
az aks addon update -g $RG -n $CLUSTER --addon azure-keyvault-secrets-provider --enable-secret-rotation --rotation-poll-interval 5m az aks show -g $RG -n $CLUSTER --query addonProfiles.azureKeyvaultSecretsProvider.config.rotationPollInterval
2. Look up the clientId of the managed identity that the add-on created automatically.
az aks show -g $RG -n $CLUSTER --query addonProfiles.azureKeyvaultSecretsProvider.identity.clientId -o tsv
A Java service reads its database password through an environment variable, and the DBA rotates the password in Key Vault every 30 days. How do you make this run unattended?
Use CSI + secretObjects sync + rotation enabled, so the Secret updates automatically. Then use a controller (for example, Reloader) to roll-restart the Deployment when the Secret changes. Or change the app to read the mounted file directly and reload on authentication failure. Note that the database side must support two passwords or an overlap window, to avoid authentication failures at the moment of rotation.
Verified teaching videos
Official documentation
- Use the Azure Key Vault provider for Secrets Store CSI Driver
- Access Azure Key Vault with the CSI Driver identity provider
- Configuration options (rotation, sync, metrics)
- Secrets Store CSI Driver known limitations
Video storyboard (about 80 seconds)
Visual: the Pod starts, and the kubelet knocks on the CSI driver's door.
Narration: When mounting the volume, the CSI driver reads the SecretProviderClass and asks the Azure provider to fetch the secret from Key Vault.
Visual: the provider takes the Pod's ServiceAccount token to Entra to exchange it for a token, then enters Key Vault.
Narration: With Workload Identity, the provider handles the token exchange, so the app doesn't need any SDK.
Visual: the secret files land in the Pod's in-memory file system. A dotted arrow copies one into a Kubernetes Secret.
Narration: You can mount only the files, or sync them into a Kubernetes Secret, but the latter is stored in etcd.
Visual: a clock turns every two minutes, the file updates, and the environment variable still holds the old value.
Narration: With rotation enabled, the file updates, but environment variables only change after a restart.
Module 5 · Images and supply chain: ACR, image integrity, and scanning
- Explain which identity AKS uses to pull images from ACR: the kubelet identity (not the Pod's workload identity).
--attach-acractually assigns itAcrPull. - Understand ACR's role assignment permission modes: under RBAC Registry + ABAC Repository Permissions (
rbac-abac),AcrPullandAcrPushno longer apply, and you need roles such asContainer Registry Repository Readerinstead. - Build four checkpoints for the supply chain: source (allowed registries), signing (Notation, AKS Image Integrity in preview), vulnerabilities (Defender agentless scanning), and admission (Defender gated deployment or Azure Policy).
What: how AKS pulls images from ACR
Images are pulled by containerd on the node, and credentials come from the kubelet's credential provider. It uses the cluster's kubelet identity (the user-assigned managed identity in the node resource group, identityProfile.kubeletidentity). az aks update --attach-acr $ACR creates an AcrPull role assignment for that identity on the registry (the operator needs permission to create role assignments, such as Owner or User Access Administrator). So:
- You don't need
imagePullSecrets, and you shouldn't enable the ACR admin user (--admin-enabled false). - All nodes and all namespaces share this pull permission. Anyone who can create Pods in the cluster can pull any image from that registry. To isolate by namespace, use ACR ABAC repository conditions, multiple registries, or Azure Policy to restrict image sources.
az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.ioruns a diagnostic Pod inside the cluster to check DNS, networking, and authorization.
ACR's ABAC mode (important change)
| RBAC Registry Permissions (traditional) | RBAC Registry + ABAC Repository Permissions (rbac-abac) | |
|---|---|---|
| Pull role | AcrPull | Container Registry Repository Reader (+ Container Registry Repository Catalog Lister to list repositories) |
| Push role | AcrPush | Container Registry Repository Writer |
| Repository-level permissions | None (token/scope maps only) | Role assignment with an ABAC condition, for example repositories:name StringStartsWithIgnoreCase 'myapp/' |
| Owner/Contributor | Includes data plane | Control plane only, cannot pull or push images |
The official docs say ABAC mode "will become the default mode for ACR" and warn that switching without first assigning equivalent ABAC roles will cut off existing identities' access. Switching also invalidates cached registry credentials (401), and for AKS you must restart the kubelet or replace nodes for an immediate refresh. For an ABAC-mode registry, assign Repository Reader directly to the kubelet identity (optionally with repository conditions) rather than relying on AcrPull.
Image integrity: signing and verification
- Signing: use the
notationCLI from the Notary Project with the Azure Key Vault plugin to sign the image digest in CI. The signature is stored as an OCI referrer in the same ACR repository. - Verification (AKS Image Integrity, preview): built on Ratify + Azure Policy + Gatekeeper. After you enable it through the built-in policy initiative "[Preview]: Use Image Integrity to ensure only trusted images are deployed," the cluster deploys Ratify Pods, syncs certificates from Key Vault, and verifies signatures at admission. Limits (official): requires cluster 1.26+, the OIDC issuer, and the Azure Policy add-on; only the Notation verifier is supported; only the Audit effect is supported (it doesn't block deployments); up to 200 unique signatures per cluster; not for use with production registries or workloads.
- For production scenarios that truly need to "reject unsigned images," the common approach today is to deploy the open-source Ratify + Gatekeeper yourself, or to enforce verification in the pipeline. Check the current official status.
Vulnerability scanning and gated deployment (Defender for Containers)
- Agentless vulnerability assessment (Microsoft Defender Vulnerability Management): scans images in ACR (quick scan after push, daily rescans), running containers, and supported nodes, covering OS and language packages. Vulnerability findings are attached to the image in the registry as Microsoft-signed artifacts.
- Gated deployment: Defender's admission controller (
defender-admission-controller) evaluates images at deploy time using these vulnerability results. Rule actions are Audit (allow and log) or Deny (block). Once prerequisites are met, a default rule "High/critical vulnerabilities → Audit" is created automatically. You can scope it by cluster or namespace and set exemptions. For supported environments and registries, see the Defender support matrix.
Old images on nodes: Image Cleaner
The AKS Image Cleaner (based on Eraser) periodically removes unused, vulnerable images from nodes: az aks update --enable-image-cleaner --image-cleaner-interval-hours 48. It doesn't block deployments. It only reduces the risky images left on nodes.
:latest is fine, it's our own registry." Tags are mutable, so you can't audit what is actually running. Deployment Safeguards rejects the latest tag (Module 6).Control points in an image supply chain
Interactive simulator: can this image run on aks-lab?
Set the image properties and cluster controls, then click "Deploy." It goes through the admission webhooks in real order (Gatekeeper/Azure Policy, Ratify, Defender admission controller) and then the kubelet pull.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az acr create | Create a registry | --sku Basic|Standard|Premium, --role-assignment-mode rbac-abac (optional) |
az aks update --attach-acr | Assign AcrPull to the kubelet identity | Remove with --detach-acr; requires permission to create role assignments |
az aks check-acr | Diagnose ACR connectivity and authorization from inside the cluster | --acr <name>.azurecr.io, optionally with --node-name |
az acr build / az acr import | Cloud build, or import from another registry | import --source docker.io/library/redis:7.4 avoids Docker Hub rate limits |
az acr repository show-manifests / az acr manifest list-metadata | View digest | Pin with @sha256: when deploying |
notation sign / notation verify | Sign / verify | Key Vault plugin azure-kv, --id <key id> |
az aks update --enable-image-cleaner | Clean up unused vulnerable images on nodes | --image-cleaner-interval-hours |
source ~/.aks-lab.env; RG=rg-aks-lab; CLUSTER=aks-lab az acr create -g $RG -n $ACR --sku Basic --admin-enabled false az aks update -g $RG -n $CLUSTER --attach-acr $ACR az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io
[2026-11-15T10:02:11Z] Checking host name resolution (acraks21877.azurecr.io): SUCCEEDED [2026-11-15T10:02:11Z] Canonical name for ACR (acraks21877.azurecr.io): r0123cac.eastus.cloudapp.azure.com. [2026-11-15T10:02:12Z] Checking managed identity... [2026-11-15T10:02:12Z] Kubelet managed identity client ID: 4f2c… [2026-11-15T10:02:13Z] Validating managed identity existance: SUCCEEDED [2026-11-15T10:02:14Z] Validating image pull permission: SUCCEEDED [2026-11-15T10:02:14Z] Your cluster can pull images from acraks21877.azurecr.io!
# Build and push myapp:1.1 (in the myapp directory from the Docker hour)
az acr build -r $ACR -t myapp:1.1 .
az acr import -n $ACR --source docker.io/library/redis:7.4 --image redis:7.4
az acr manifest list-metadata -r $ACR -n myapp --query "[].{digest:digest,tags:tags}" -o table
Signing (run in the pipeline, conceptual example)
# Prerequisites: notation and the notation-azure-kv plugin installed; signing certificate myapp-signer in Key Vault KEY_ID=$(az keyvault certificate show -n myapp-signer --vault-name $KV --query kid -o tsv) DIGEST=$(az acr manifest list-metadata -r $ACR -n myapp --query "[?tags[0]=='1.1'].digest" -o tsv) notation sign --signature-format cose --id $KEY_ID --plugin azure-kv $ACR.azurecr.io/myapp@$DIGEST notation ls $ACR.azurecr.io/myapp@$DIGEST
For the full steps on signing, certificates, and trust policies, see the official tutorial "Sign container images with Notation and Azure Key Vault". Note: sign the digest, not the tag, and use the digest in deployment manifests too.
Pull authorization for ABAC-mode registries
KUBELET_OID=$(az aks show -g $RG -n $CLUSTER --query identityProfile.kubeletidentity.objectId -o tsv) ACR_ID=$(az acr show -n $ACR --query id -o tsv) az acr show -n $ACR --query roleAssignmentMode -o tsv az role assignment create --assignee-object-id $KUBELET_OID --assignee-principal-type ServicePrincipal \ --role "Container Registry Repository Reader" --scope $ACR_ID
Lab 5: deploy myapp:1.1 from ACR, using the Redis password from Key Vault (about 8 minutes)
az acr build -r $ACR -t myapp:1.1 ., and import redis at the same time.myapp:1.1 needs to read the password from the REDIS_PASSWORD environment variable. If the Docker hour version doesn't have this, add password=os.getenv("REDIS_PASSWORD") to redis.Redis(...) and rebuild.
DIGEST=$(az acr manifest list-metadata -r $ACR -n myapp --query "[?tags[0]=='1.1'].digest" -o tsv)
cat <<EOF | kubectl apply -f -
apiVersion: apps/v1
kind: Deployment
metadata: { name: myapp, namespace: myapp, labels: { app: myapp } }
spec:
replicas: 2
selector: { matchLabels: { app: myapp } }
template:
metadata:
labels: { app: myapp, azure.workload.identity/use: "true" }
spec:
serviceAccountName: myapp-sa
containers:
- name: myapp
image: $ACR.azurecr.io/myapp@$DIGEST
ports: [ { containerPort: 5000 } ]
env:
- { name: REDIS_HOST, value: redis }
- name: REDIS_PASSWORD
valueFrom: { secretKeyRef: { name: redis-auth, key: password } }
resources: { requests: { cpu: 100m, memory: 128Mi }, limits: { memory: 256Mi } }
readinessProbe: { httpGet: { path: /healthz, port: 5000 }, periodSeconds: 5 }
livenessProbe: { httpGet: { path: /healthz, port: 5000 }, periodSeconds: 10 }
volumeMounts: [ { name: kv, mountPath: /mnt/secrets-store, readOnly: true } ]
volumes:
- name: kv
csi: { driver: secrets-store.csi.k8s.io, readOnly: true, volumeAttributes: { secretProviderClass: myapp-kv } }
EOF
kubectl -n myapp rollout status deploy/myapp
kubectl -n myapp port-forward deploy/myapp 5000:5000 & sleep 2; curl -s localhost:5000/; curl -s localhost:5000/healthz
deployment "myapp" successfully rolled out Hello! This page has been viewed 1 times. ok
az aks update -g $RG -n $CLUSTER --detach-acr $ACR kubectl -n myapp rollout restart deploy/myapp; sleep 60 kubectl -n myapp get pods; kubectl -n myapp describe pod -l app=myapp | grep -A3 Failed az aks update -g $RG -n $CLUSTER --attach-acr $ACR
If the image is already cached on the node (imagePullPolicy: IfNotPresent), the pull may not fail. This is itself a troubleshooting point worth remembering. To reproduce it, schedule the Pod onto a new node, or use a digest that hasn't been pulled yet.
Case 1: after switching ACR to ABAC mode, ImagePullBackOff across the whole cluster
Problem: the security team switched the registry to rbac-abac to get repository-level permissions, and the rolling release then failed everywhere. Cause: the kubelet identity only had AcrPull, which doesn't apply in ABAC mode, and the switch invalidated cached credentials. Approach: follow the official migration steps. First, under RBAC mode, assign Repository Reader (+ Catalog Lister) to the kubelet identity, then switch, then immediately restart the kubelet or replace nodes to refresh credentials, and after verifying, remove AcrPull. Lesson: run a full dry run in pre-production.
Case 2: scale-out fails due to Docker Hub rate limiting
Problem: when nodes auto-scale, many pulls of docker.io/library/redis trigger the anonymous pull rate limit. Approach: use az acr import to import the base image into your own ACR (or use an ACR cache rule), and use Azure Policy to allow only *.azurecr.io and mcr.microsoft.com.
Case 3: critical vulnerability in a base image found before go-live
Approach: run Defender gated deployment in Audit mode for two weeks first to measure the impact and fix the base image. Then switch the production namespaces to Deny, and set time-limited exemptions for CVEs that truly can't be fixed. Limits: behavior when an image has no scan results depends on the rule configuration, so make it explicit.
Common errors and fixes
Failed to pull image "acraks21877.azurecr.io/myapp:1.1": … failed to authorize: failed to fetch anonymous token: unexpected status … 401 Unauthorized
Cause: the kubelet identity has no pull permission (not attached, detached, the registry switched to ABAC mode leaving only AcrPull, or the role assignment was just created).
az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io az role assignment list --assignee $(az aks show -g $RG -n $CLUSTER --query identityProfile.kubeletidentity.objectId -o tsv) --all -o table az acr show -n $ACR --query roleAssignmentMode -o tsv
Failed to pull image …: dial tcp: lookup acraks21877.azurecr.io … no such host / i/o timeout
Cause: networking. The private endpoint DNS zone isn't linked to the cluster VNet, or the outbound firewall doesn't allow *.azurecr.io and the data endpoint *.<region>.data.azurecr.io.
Fix: see the outbound rules in hour 2. check-acr checks DNS first.
admission webhook "validation.gatekeeper.sh" denied the request: [azurepolicy-…allowedimages…] Container image docker.io/library/myapp:1.1 for container myapp has not been allowed. (sample format)
Cause: the Azure Policy "allowed images only" policy (regex) doesn't match.
Fix: push the image to ACR, or adjust the regex in the policy parameters (for example ^[a-z0-9]+\.azurecr\.io/.+$).
ErrImagePull: manifest unknown / not found
Cause: the tag or digest doesn't exist, or it was pushed to a different registry. Or the ABAC condition only granted the myapp/ prefix while the repository name is myapp (watch the trailing slash semantics of the prefix).
az acr repository show-tags -n $ACR --repository myapp -o table
1. Find the objectId of the cluster's kubelet identity, and list its roles on the ACR.
OID=$(az aks show -g $RG -n $CLUSTER --query identityProfile.kubeletidentity.objectId -o tsv) az role assignment list --assignee $OID --scope $(az acr show -n $ACR --query id -o tsv) -o table
2. Import nginx:1.27 from Docker Hub into ACR.
az acr import -n $ACR --source docker.io/library/nginx:1.27 --image nginx:1.27
Two teams share one ACR and one AKS cluster. Team A should not be able to run Team B's images. The kubelet identity is shared. What do you do?
Pull authorization can't be separated by namespace, since the kubelet identity is shared. Options: ① at the admission layer, use Azure Policy or Gatekeeper to enforce "namespace team-a may only use acr/team-a/*"; ② split registries or node pools (different kubelet identities require different clusters); ③ ACR ABAC conditions can only grant per repository for the kubelet identity too, so they still can't distinguish namespaces. Conclusion: use admission policies for namespace isolation, and ACR ABAC for people and pipeline isolation.
Verified teaching videos
Official documentation
- Authenticate with ACR from AKS
- ACR ABAC repository permissions
- Image Integrity (preview)
- Sign container images with Notation and Azure Key Vault
- Gated deployment for Kubernetes container images
Video storyboard (about 80 seconds)
Visual: the kubelet on the node walks into ACR holding an "AcrPull" badge.
Narration: The kubelet identity pulls the image, not the Pod's workload identity.
Visual: ACR switches to ABAC mode, the AcrPull badge turns gray, and is replaced with "Repository Reader".
Narration: In ABAC mode, the traditional roles no longer apply, so assign the new roles before migrating.
Visual: the image carries two tags, a signature and a vulnerability report, and passes three gates in turn.
Narration: At admission, you can check the source, the signature, and vulnerabilities. Image Integrity currently only audits.
Visual: gated deployment switches from Audit to Deny, and an image with critical vulnerabilities is blocked at the gate.
Narration: Audit first, then deny, and set time-limited exemptions for vulnerabilities that truly can't be fixed.
Module 6 · Azure Policy and Pod security (Deployment Safeguards)
- Understand the structure of the Azure Policy add-on: Azure Policy assignment → add-on (
kube-system/azure-policy) syncs into Gatekeeper constraint templates and constraints → Gatekeeper admission webhook denies or audits → compliance results report back to Azure Policy. - You will enable Deployment Safeguards (
az aks safeguards create/update), distinguish Warn from Enforce, and know that Enforce changes resources (default resource requests, anti-affinity and topology spread) and rejects non-compliant resources. - You will set the Pod Security Standards level (Baseline / Restricted) and fix the myapp and Redis manifests so they pass Restricted.
What: Azure Policy for AKS
The Azure Policy add-on (az aks enable-addons --addons azure-policy) deploys Gatekeeper (the OPA admission controller, in the gatekeeper-system namespace) and the Azure Policy sync components (azure-policy / azure-policy-webhook in kube-system) into the cluster. You assign “Kubernetes” category policies or initiatives in Azure. The add-on periodically pulls these assignments and converts them into ConstraintTemplates and Constraints. Gatekeeper evaluates them at admission time and periodically audits existing resources. Compliance results return to the Azure Policy compliance dashboard. Common effects are Audit, Deny, and Disabled. Some policies also support Mutate.
Gatekeeper runs fail-open: if the webhook times out or is unavailable, requests are allowed through. The official FAQ explains this is so deployments are not blocked. Policy is therefore a guardrail, not the only security boundary, and it must be paired with auditing and Defender. System namespaces such as kube-system and gatekeeper-system are not evaluated by default.
Deployment Safeguards
Deployment Safeguards is a set of built-in Azure Policies provided by AKS. You enable them in one step, at two levels:
- Warn: if a resource is non-compliant, kubectl prints a warning, but creation is still allowed.
- Enforce: first mutates the items that can be fixed automatically, then rejects resources that are still non-compliant.
| AKS Automatic | AKS Standard | |
|---|---|---|
| Default state | Enabled, Enforce | Optional |
| Can be changed to Warn | No (you can only exclude namespaces) | Yes |
| PSS default | Baseline (cannot be turned off) | Privileged (unrestricted) |
| Prerequisite | Azure Policy add-on (and register Microsoft.PolicyInsights); enabling Safeguards itself does not require Azure Policy permissions | |
Policies included in Safeguards (official list)
| Policy | Mutation under Enforce |
|---|---|
| Cannot Edit Individual Nodes (you cannot taint or label a single node directly) | — |
| Containers must define CPU and memory requests | If missing, set to CPU 500m / memory 2048Mi (requests=limits); if below 100m / 100Mi, raise to the minimum |
| Must have anti-affinity or topologySpreadConstraints | Adds a preferred anti-affinity with weight 100 on the app → app.kubernetes.io/name labels, plus maxSkew 1 / ScheduleAnyway / kubernetes.io/hostname topology spread |
Must not use AKS-specific labels (kubernetes.azure.com) | — |
| Only allowed images | — |
Reserved system pool taint (CriticalAddonsOnly) | Remove this taint from user node pools |
| Must configure a readiness or liveness probe | — |
| Must use a StorageClass backed by a CSI driver | — |
| Service selectors must be unique | — |
Images must not use the latest tag | — |
Safeguards is all or nothing: you cannot pick individual policies or define custom mutators. Versions ship with the AKS add-on version.
Pod Security Standards level
| Level | Main restrictions |
|---|---|
| Privileged | Unrestricted (AKS Standard default) |
| Baseline | Forbids privileged, hostNetwork/hostPID/hostIPC, hostPort, dangerous capabilities, non-default AppArmor/SELinux/procMount, Unconfined seccomp, and unsafe sysctls; hostPath is also restricted |
| Restricted | On top of Baseline: only configMap/csi/downwardAPI/emptyDir/ephemeral/PVC/projected/secret volumes are allowed; allowPrivilegeEscalation: false; runAsNonRoot: true; no runAsUser: 0; seccomp must be RuntimeDefault or Localhost; you must drop ALL and may only add NET_BIND_SERVICE |
When: choosing between Azure Policy, Safeguards, and native PSA
- Safeguards: for AKS Standard, when you want sensible defaults quickly. Start with Warn to observe, then move to Enforce.
- Custom Azure Policy assignments: organization-wide consistency (assigned at the management group or subscription, covering all clusters), for example “only allow our company's ACR” or “block public IPs on LoadBalancers”.
- Native Pod Security Admission (namespace label
pod-security.kubernetes.io/enforce=restricted): built into Kubernetes, no extra components, good for fine-tuning per namespace. When it is enabled alongside the PSS from Safeguards, avoid rule conflicts and duplicate errors.
--pss-level), and AKS Standard defaults to Privileged.Admission pipeline
Interactive simulator: submit a Pod template and see the admission result
Check the manifest features, choose a Safeguards level and a PSS level, then click “Submit”. The warning and rejection messages in the output use the original format from the official docs.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks enable-addons --addons azure-policy | Install the Azure Policy add-on | Run az provider register -n Microsoft.PolicyInsights first |
az aks safeguards create | Enable Deployment Safeguards | -g/-n or --cluster <id>; --level Warn|Enforce |
az aks safeguards update | Change the level, exclude namespaces, PSS | --excluded-ns ns1 ns2 (space-separated), --pss-level Baseline|Restricted|Privileged |
az aks safeguards delete | Disable Safeguards | — |
az policy assignment create | Assign a policy or initiative | --policy-set-definition, --scope, --params |
kubectl get constrainttemplates,constraints | View the constraints pushed to the cluster | kubectl get k8sazurev… -o yaml to view audit violations |
The az aks safeguards command group is recent. If your CLI says the command does not exist, run az upgrade first, and install the aks-preview extension if needed. Follow the official docs.
az provider register -n Microsoft.PolicyInsights az aks safeguards create -g $RG -n $CLUSTER --level Warn az aks safeguards update -g $RG -n $CLUSTER --level Warn --pss-level Baseline --excluded-ns monitoring kubectl get pods -n gatekeeper-system; kubectl get constrainttemplates | head
NAME READY STATUS RESTARTS AGE gatekeeper-audit-6c8f9b7d5c-k2l9x 1/1 Running 0 1d gatekeeper-controller-7d9c6b8f4d-2xqzv 1/1 Running 0 1d gatekeeper-controller-7d9c6b8f4d-8h4tw 1/1 Running 0 1d NAME AGE k8sazurev1antiaffinityrules 10m k8sazurev1containerenforceprobes 10m …
Warn and Enforce output (official example format)
$ kubectl apply -f deployment.yaml Warning: [azurepolicy-k8sazurev1antiaffinityrules-ceffa082711831ebffd1] Deployment with 2 replicas should have either podAntiAffinity or topologySpreadConstraints set to avoid disruptions due to nodes crashing deployment.apps/simple-web created
$ kubectl apply -f deployment.yaml Error from server (Forbidden): error when creating "deployment.yaml": admission webhook "validation.gatekeeper.sh" denied the request: [azurepolicy-k8sazurev1antiaffinityrules-ceffa082711831ebffd1] Deployment with 2 replicas should have either podAntiAffinity or topologySpreadConstraints set to avoid disruptions due to nodes crashing
Restricted-compliant container securityContext
spec:
securityContext:
runAsNonRoot: true
seccompProfile: { type: RuntimeDefault }
containers:
- name: myapp
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true # Not required by PSS, but recommended (mount an emptyDir if gunicorn needs a writable /tmp)
capabilities: { drop: ["ALL"] }
Lab 6: from Warn to Enforce, fixing myapp and Redis (about 10 minutes plus policy sync wait)
kubectl -n myapp create deployment bad --image=nginx --replicas=2 --dry-run=server -o name
Warning: [azurepolicy-…-enforceprobes-…] Container nginx in your Pod bad-… has no livenessProbe. Required probes: readinessProbe, livenessProbe Warning: [azurepolicy-…-latestimage-…] Please specify an explicit, versioned image tag such as '1.0' for container nginx. … Warning: [azurepolicy-…-resourcerequests-…] container nginx has no resource requests Warning: [azurepolicy-k8sazurev1antiaffinityrules-…] Deployment with 2 replicas should have either podAntiAffinity or topologySpreadConstraints set … deployment.apps/bad
--dry-run=server goes through the admission webhook without persisting anything, so it is ideal for checking early in CI.
kubectl -n myapp get deploy myapp -o yaml | kubectl apply --dry-run=server -f - 2>&1 | grep -i warning kubectl -n myapp get deploy redis -o yaml | kubectl apply --dry-run=server -f - 2>&1 | grep -i warning
Expected: myapp and redis only show anti-affinity-related warnings (myapp has 2 replicas). Adding topologySpreadConstraints to myapp fixes it.
az aks safeguards update -g $RG -n $CLUSTER --level Warn --pss-level Restricted
# Add the fields Restricted requires to myapp (the myapp image runs as the non-root user appuser in the Docker course)
kubectl -n myapp patch deploy myapp --type merge -p '{"spec":{"template":{"spec":{
"securityContext":{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}},
"topologySpreadConstraints":[{"maxSkew":1,"topologyKey":"kubernetes.io/hostname","whenUnsatisfiable":"ScheduleAnyway","labelSelector":{"matchLabels":{"app":"myapp"}}}],
"containers":[{"name":"myapp","securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]}}}}'
# The official redis image starts as root and drops privileges, so under Restricted you must set the redis user explicitly (UID 999)
kubectl -n myapp patch deploy redis --type merge -p '{"spec":{"template":{"spec":{
"securityContext":{"runAsNonRoot":true,"runAsUser":999,"seccompProfile":{"type":"RuntimeDefault"}},
"containers":[{"name":"redis","securityContext":{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]}}}]}}}}'
kubectl -n myapp rollout status deploy/myapp; kubectl -n myapp rollout status deploy/redisaz aks safeguards update -g $RG -n $CLUSTER --level Enforce --pss-level Restricted
# After sync, try the “bad” manifest again: it should be rejected
kubectl -n myapp create deployment bad --image=nginx --replicas=2 --dry-run=server -o name
# Observe the mutator: Pods missing resources get default values added
kubectl -n myapp run probe-demo --image=nginx:1.27 --dry-run=server -o jsonpath='{.spec.containers[0].resources}'; echo
Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: …
{"limits":{"cpu":"500m","memory":"2Gi"},"requests":{"cpu":"500m","memory":"2Gi"}}az aks safeguards update -g $RG -n $CLUSTER --level Warn --pss-level Baseline
Case 1: after enabling Enforce, the node pool suddenly doubled in size
Problem: many Jobs had no resources set, so the Enforce mutator added 500m CPU / 2Gi memory to every container, and the Cluster Autoscaler scaled up sharply. Approach: run Warn for two weeks first to collect the non-compliant manifests, fix them, then switch to Enforce; temporarily use --excluded-ns for batch namespaces. Limitation: the mutator's default values cannot be customized.
Case 2: organization-wide “only allow our company's ACR”
Approach: assign the built-in policy “Kubernetes cluster containers should only use allowed images” at the management group. Set the parameter regex to allow only ^acr(prod|shared)\.azurecr\.io/.+$ and ^mcr\.microsoft\.com/.+$. Use Audit first, then Deny, and keep kube-system and other system namespaces in the exclusion list. Result: new clusters are governed automatically as soon as they join the subscription.
Case 3: a third-party Helm chart cannot pass Restricted
Problem: the monitoring agent needs hostPath and hostNetwork. Approach: put it in a dedicated namespace and exclude that namespace, or use Baseline/Privileged for that namespace only. Record the exception and review it regularly. Principle: relax rules per namespace, not per cluster.
Common errors and fixes
Container <container_name> in your Pod <pod_name> has no livenessProbe. Required probes: readinessProbe, livenessProbe
Fix: add liveness and readiness probes to every container (myapp uses /healthz; Redis uses a tcpSocket on 6379).
Please specify an explicit, versioned image tag such as '1.0' for container %v. …
Fix: use an explicit version tag or a digest. nginx (no tag) is blocked as well.
Containers must not run as root user in spec.containers[*].securityContext.runAsNonRoot
Cause: Restricted requires runAsNonRoot: true. After you set it, if the image's default user is root, the kubelet also reports container has runAsNonRoot and image will run as root (CreateContainerConfigError).
Fix: use a non-root user in the image (Dockerfile USER), or set a numeric runAsUser in securityContext.
All containers must drop ALL capabilities under restricted policy
Fix: capabilities: { drop: ["ALL"] }; you may only add NET_BIND_SERVICE. An app that listens on port 80 either adds it or moves to a high port (myapp uses 5000, so it does not need it).
The policy has been assigned for an hour, but the cluster still has no matching constraint
kubectl -n kube-system get pods -l app=azure-policy kubectl -n kube-system logs -l app=azure-policy --tail=50 az aks show -g $RG -n $CLUSTER --query addonProfiles.azurepolicy
Cause: the add-on is not enabled or is unhealthy, Microsoft.PolicyInsights is not registered, the assignment scope does not include this cluster, or outbound traffic is blocked by a firewall (the add-on needs access to Azure Policy endpoints).
1. Enable the Enforce level of Safeguards, excluding the monitoring and batch namespaces.
az aks safeguards update -g $RG -n $CLUSTER --level Enforce --excluded-ns monitoring batch
2. Without creating any resources, check whether a manifest would pass admission.
kubectl apply -f deploy.yaml --dry-run=server
Gatekeeper's webhook was temporarily unavailable because of a node failure, and during that time a privileged Pod was deployed. What does this show, and how would you remediate it?
Gatekeeper is fail-open, so admission policy cannot be the only line of defense. Remediation: Gatekeeper audit will later flag the Pod as non-compliant, visible on the Azure Policy compliance dashboard; Defender runtime detection (privileged containers, sensitive mounts) raises alerts; run Gatekeeper with multiple replicas and a PodDisruptionBudget; for high-risk constraints, add native Pod Security Admission (built into the API server, so it does not depend on an external webhook).
Verified teaching videos
Official documentation
- Use Deployment Safeguards
- Azure Policy for Kubernetes
- Azure Policy built-in definitions for AKS
- Pod Security Standards
Video storyboard (about 80 seconds)
Visual: an Azure Policy assignment, like an official document, is carried into the cluster by the add-on and becomes Gatekeeper constraints.
Narration: The Azure Policy add-on syncs policy assignments into Gatekeeper constraints.
Visual: a manifest with no resources or probes enters the admission pipeline; in Warn mode a yellow sticky note is attached and it is let through.
Narration: Warn mode only gives a notice; the resources are still created.
Visual: in Enforce mode the manifest is first “patched” with resource requests and topology spread, then rejected for missing probes.
Narration: Enforce mutates first, then validates, and rejects anything still non-compliant.
Visual: the PSS dial turns from Privileged to Restricted, and the myapp manifest gains runAsNonRoot and drop ALL.
Narration: Raise the Pod security level to Restricted so that containers run as non-root.
Module 7 · Microsoft Defender for Containers
- Name the five areas of Defender for Containers: security posture management, vulnerability assessment, runtime threat protection, software supply chain protection, and deployment and monitoring. Distinguish agentless capabilities (based on the Azure and Kubernetes APIs and audit logs) from sensor capabilities (the Defender sensor on the node).
- You will enable the plan on the subscription, confirm the sensor on aks-lab, and use the official test method to trigger a test alert.
- Understand how alerts map to MITRE ATT&CK for Containers, and how to investigate and respond in Defender XDR.
What: the five areas
| Area | Capability | How it works |
|---|---|---|
| Security posture management | Discovers clusters, workloads, and configuration; detects misconfigurations (control plane hardening recommendations); Security Explorer for risk hunting | Agentless: reads cloud APIs and Kubernetes APIs; data plane hardening depends on the Azure Policy add-on |
| Vulnerability assessment | ACR images, running containers, supported nodes; OS and language packages; exploitability information; daily rescans | Agentless, provided by Microsoft Defender Vulnerability Management |
| Runtime threat protection | 60+ Kubernetes-aware analytics and anomaly detections; mapped to MITRE ATT&CK; can be investigated and responded to in Defender XDR | Sensor (node process and network events) + agentless (Kubernetes audit log analysis) |
| Software supply chain protection | Image scan results are linked to images in the registry, supporting gated deployments (Audit / Deny) | Vulnerability assessment + defender-admission-controller |
| Deployment and monitoring | Finds clusters without the sensor installed and deploys the components at scale | Auto-provisioning / policy |
Sensor capabilities (require the Defender sensor)
- Anti-malware: detects malicious activity inside containers.
- DNS detection: suspicious DNS activity from container workloads.
- Binary drift detection / prevention: an executable that is not in the original image runs in a container (for example, a tool an attacker downloaded); you can alert on it or block it according to a drift policy.
- The sensor images are maintained by Microsoft (MCR
mcr.microsoft.com/azuredefender/stable/…, such aslow-level-collector,pod-collector,security-publisher). When deployed as an AKS add-on, they are updated on the AKS release cycle. Customers should not modify them.
Typical runtime detection examples (as listed officially)
An exposed Kubernetes dashboard, a workload publicly exposed through a LoadBalancer Service, creation of a high-privilege role, creation of a sensitive mount (a hostPath mount of /etc, /var/run/docker.sock, and so on). Alerts only fire for activity that happens after the plan is enabled.
How: enabling it
- Enable the Defender for Containers plan on the subscription (Environment settings in the portal, or
az security pricing create -n Containers --tier standard). Once enabled, the sensor is deployed automatically to AKS clusters in the subscription by default (this is configurable). - For a single cluster:
az aks update -g $RG -n $CLUSTER --enable-defender(you can use--defender-configto specify a Log Analytics workspace). Use--disable-defenderto remove it. - Data plane hardening recommendations require the Azure Policy add-on (enabled in module 6).
Why / When
Preventive controls (Policy, PSS, signing) always have exceptions and fail-open scenarios, so runtime detection is the last line of defense, and it gives the SOC Kubernetes context (cluster, namespace, Pod, image). Compared with open-source options (Falco + custom rules + SIEM), Defender's advantages are that it is managed, correlated with Azure Resource Graph and vulnerability data, and integrated with Defender XDR. The trade-off is per-vCore billing, and customization is limited to its supported matrix.
Components and data flow
Attack chain simulation: at each step, who detects it?
Run the attacker's actions in order (based on common tactics in MITRE ATT&CK for Containers). The panel on the right shows which data source can observe each step and what kind of alert it might produce. Uncheck “Sensor” to see what gets missed.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az security pricing create -n Containers --tier standard | Enable the plan on the current subscription | --tier free turns it off; affects the entire subscription |
az security pricing show -n Containers | View plan status and extensions | — |
az aks update --enable-defender | Deploy the sensor on a cluster | --defender-config <json> to specify the workspace; --disable-defender |
az aks show --query securityProfile.defender | View a cluster's Defender configuration | securityMonitoring.enabled |
az security alert list | List alerts | Filter by --resource-group |
az security pricing create -n Containers --tier standard az aks update -g $RG -n $CLUSTER --enable-defender az aks show -g $RG -n $CLUSTER --query securityProfile.defender -o jsonc kubectl get pods -n kube-system | grep -i defender
{
"logAnalyticsWorkspaceResourceId": "/subscriptions/…/resourceGroups/DefaultResourceGroup-CCAN/providers/Microsoft.OperationalInsights/workspaces/DefaultWorkspace-…-CCAN",
"securityMonitoring": { "enabled": true }
}
microsoft-defender-collector-ds-7x2kq 2/2 Running 0 5m
microsoft-defender-collector-misc-… 1/1 Running 0 5m
microsoft-defender-publisher-ds-… 1/1 Running 0 5m
Pod names change between versions, so rely on the actual output of grep -i defender.
Trigger test alerts (official alert verification method)
# Method 1: Kubernetes audit log test alert kubectl get pods --namespace=asc-alerttest-662jfi039n # Method 2: sensor test alert (run inside a test Pod) kubectl -n myapp run alerttest --image=mcr.microsoft.com/azure-cli:2.67.0 --restart=Never -- sleep 600 kubectl -n myapp exec alerttest -- sh -c 'cp /bin/echo ./asc_alerttest_662jfi039n && ./asc_alerttest_662jfi039n testing eicar pipe'
The alert name is in the style of “Microsoft Defender for Cloud test alert for K8S (not a threat)”. The official guidance is to wait at least about 10 minutes; community experience may be longer. For a fuller attack-scenario simulation, you can use the open-source Kubernetes attack simulation tool described in the official docs, but run it only on a dedicated test cluster.
Lab 7: enable Defender and verify the alert pipeline (about 10 minutes plus waiting, optional)
az security pricing create -n Containers --tier free (if the subscription already had it enabled, do not turn it off).az security pricing show -n Containers --query "{tier:pricingTier, ext:extensions[].{name:name,on:isEnabled}}" -o jsonc# Test alert kubectl get pods --namespace=asc-alerttest-662jfi039n # A “dangerous” configuration: expose Redis publicly through a LoadBalancer (lab only! delete it immediately when done) kubectl -n myapp expose deploy redis --name redis-public --type LoadBalancer --port 6379 sleep 120; kubectl -n myapp delete svc redis-public
The second command succeeds if Safeguards or Policy does not block public LoadBalancers. Defender may raise an alert such as “Exposed Kubernetes service detected”. It also reminds you that your baseline should include a policy that blocks public LoadBalancers or allows only internal LBs.
aks-lab; or:
az security alert list --resource-group $RG --query "[].{time:timeGeneratedUtc,name:alertDisplayName,sev:severity}" -o table
Time Name Sev 2026-11-15T11:24:03.000000Z Microsoft Defender for Cloud test alert for K8S (not a threat) Low
kubectl -n myapp delete pod alerttest --ignore-not-found # When no longer needed: az aks update -g $RG -n $CLUSTER --disable-defender az security pricing create -n Containers --tier free # only if the subscription was not already enabled
Case 1: a crypto-mining container appears at midnight
What happened: an exposed debug endpoint was exploited, and the attacker downloaded and ran a binary inside a container. The Defender sensor detected binary drift and a suspicious network connection and raised alerts. The SOC saw the cluster, namespace, Pod, and image context in Defender XDR. Response: isolate it (a NetworkPolicy denies egress), preserve evidence before deleting the Pod, fix the image, and turn on the drift block policy. Prevention: a read-only root filesystem plus Restricted PSS greatly reduces the attack surface for this kind of attack.
Case 2: cost review
Problem: Finance found that security costs had doubled. Cause: the plan was enabled on a large subscription, covering all development and test clusters. Approach: separate production and non-production by subscription; for non-production clusters, use --disable-defender or turn off the sensor by policy, and keep only the agentless capabilities; review the coverage report regularly. Limitation: check the pricing page for the exact billing rules.
Case 3: audit log alert “high-privilege role created”
What happened: an operator's installation script created a ClusterRoleBinding that binds cluster-admin, and Defender raised an alert based on the audit log. Handling: after confirming the change was legitimate, create a suppression rule (scoped to a specific SA and namespace), and require the operator to use a least-privilege ClusterRole.
Common errors and fixes
Defender recommendation “Azure Kubernetes Service clusters should have Defender profile enabled” stays non-compliant
Cause: the sensor is not deployed (auto-provisioning is off, the cluster was created before the plan was enabled and no update was triggered, or the deployment failed).
az aks show -g $RG -n $CLUSTER --query securityProfile.defender kubectl get pods -n kube-system | grep -i defender
Fix: az aks update --enable-defender; check whether outbound rules allow the endpoints Defender needs (see the outbound rules table in hour 2).
microsoft-defender-collector-ds-… CrashLoopBackOff / Pending
Cause: insufficient node resources, a node pool has a custom taint that the DaemonSet does not tolerate, or an unsupported node OS is in use.
kubectl -n kube-system describe pod -l app=microsoft-defender-collector-ds | sed -n '/Events/,$p'
The test command ran, but no test alert appears
Cause: not enough time has passed; related extensions of the plan (such as Kubernetes audit log analysis or the sensor) are not enabled; or the alert is in another subscription's or workspace's view.
Fix: confirm the extension status in az security pricing show -n Containers, then wait and retry.
1. Remove the sensor only on aks-lab, but keep the subscription plan.
az aks update -g $RG -n $CLUSTER --disable-defender
2. Trigger one Kubernetes test alert.
kubectl get pods --namespace=asc-alerttest-662jfi039n
The security team wants to “block any executable inside a container that is not in the image,” but is worried about affecting some apps that download plugins at startup. How do you move forward?
Start by running binary drift detection in alert mode to collect alerts over a period and identify legitimate drift. For legitimate apps, refactor them (bake the plugins into the image at build time), or set exceptions in the drift policy by cluster, namespace, or image. Then enable “block” for production namespaces, and use a read-only root filesystem to reduce writable locations.
Verified teaching videos
Official documentation
- Introduction to Defender for Containers
- Alerts for containers – Kubernetes clusters
- Alert validation
- Binary drift protection
- Defender for Containers support matrix
Video storyboard (about 80 seconds)
Visual: outside the cluster there are two eyes: one watches the API and audit logs, and one (the sensor) looks at processes inside the node.
Narration: Defender for Containers has two data sources: agentless and sensor-based.
Visual: an attacker execs into a container and downloads a binary; the sensor lights up “drift”.
Narration: When an executable that is not in the image runs, binary drift detection fires.
Visual: the alert card shows the MITRE tactic along with the cluster, namespace, Pod, and image.
Narration: Alerts map to MITRE ATT&CK and include full Kubernetes context.
Visual: the subscription switch turns on, and billing icons light up on every cluster at once.
Narration: Remember that the plan is subscription-level, so plan the scope and costs carefully.
Module 8 · Security baseline review
- Review an AKS cluster across six areas: identity and access, network exposure, node and cluster configuration, workloads, image supply chain, and detection and auditing.
- For each item, know how to check it (one az or kubectl command, or one Azure Policy) and the risk of not meeting it, and be able to turn the checklist into a script that runs in a pipeline.
- Use a troubleshooting tree to quickly locate identity- and security-related failures (Forbidden, AADSTS, Key Vault 403, ACR 401, admission rejection).
What: what a baseline is
A security baseline is a set of minimum requirements that every cluster must meet, along with an exception process. Its value is not the checklist itself, but that it is verifiable (every item has a check method) and enforceable (it can be enforced with Azure Policy or pipeline gates). Microsoft provides the MCSB AKS baseline and Defender for Cloud recommendations, which you can use directly as a starting point.
Review checklist (aks-lab version)
| # | Area | Control | Check method | Module in this hour |
|---|---|---|---|---|
| 1 | Identity | Managed Entra integration, with the admin group managed through PIM | az aks show --query aadProfile | M1 |
| 2 | Identity | Azure RBAC (or K8s RBAC bound only to groups); no personal accounts bound directly to cluster-admin | aadProfile.enableAzureRbac; kubectl get clusterrolebindings -o wide | M1 |
| 3 | Identity | Local accounts disabled | disableLocalAccounts == true; Policy “local authentication methods disabled” | M2 |
| 4 | Identity | Workloads use Workload ID, with no service principal password Secrets | securityProfile.workloadIdentity.enabled; search for AZURE_CLIENT_SECRET | M3 |
| 5 | Identity | Secrets come from Key Vault; sensitive secrets are not synced as Kubernetes Secrets; rotation is enabled | addonProfiles.azureKeyvaultSecretsProvider.config | M4 |
| 6 | Network | API server private, or authorized IP restrictions | apiServerAccessProfile | Hour 2 |
| 7 | Network | NetworkPolicy is enabled and each namespace has a default deny | networkProfile.networkPolicy; kubectl get netpol -A | Hour 2 |
| 8 | Network | Egress is controlled (NAT Gateway / firewall); public LoadBalancers are governed by policy | networkProfile.outboundType; Policy | Hour 2 |
| 9 | Nodes | Supported Kubernetes versions, an automatic upgrade channel, and a node OS security patch channel | autoUpgradeProfile | Hour 6 |
| 10 | Nodes | No SSH access to nodes (or SSH is disabled); use kubectl debug | Node pool securityProfile.sshAccess (follow the CLI output) | Hour 7 |
| 11 | Workloads | Deployment Safeguards ≥ Warn; PSS Baseline/Restricted for production namespaces | az aks safeguards show (follow the CLI) | M6 |
| 12 | Workloads | System namespaces do not run business workloads; business service accounts do not use default | kubectl get pods -A -o jsonpath | M3, M6 |
| 13 | Supply chain | Only private registries allowed; ACR admin user and anonymous pull disabled | Policy “allowed images”; az acr show --query adminUserEnabled | M5 |
| 14 | Supply chain | Vulnerability assessment enabled; gating for high-risk images (Audit first, then Deny) | Defender recommendations | M5, M7 |
| 15 | Detection | Control plane logs: kube-audit-admin + guard exported | az monitor diagnostic-settings list | M2 |
| 16 | Detection | Defender for Containers (production subscription), with alerts routed to the SOC | securityProfile.defender | M7 |
How: from checklist to automation
- Prevention: assign Azure Policy at the management group (cluster level: disable local accounts, enable Azure RBAC, authorized IPs; workload level: Safeguards / PSS / allowed images).
- Detection: Defender for Cloud recommendations and the security score; the review script in this module runs regularly in the pipeline and outputs a JSON report.
- Exceptions: each exception has an owner, an expiry date, and compensating controls, recorded in the repository (for example,
exceptions.yaml).
Why / When
Reviews happen at three points: before a new cluster goes live (gate), every quarter (drift check), and after major changes (for example, switching ACR to ABAC mode or enabling Enforce). The platform team turns the baseline into IaC defaults (AVM module parameters), so the secure configuration is the default configuration. This is also the design idea behind AKS Automatic: Azure RBAC by default, Workload ID, and Safeguards Enforce with Baseline PSS.
Defense in depth: six areas and this hour's modules
Review process
Interactive scorer: how secure is aks-lab right now?
Check the controls the cluster already meets (the default is the state after completing all the labs in this hour). The scorer calculates a weighted score and lists the highest-risk gaps with their fix commands.
Collect the cluster security configuration in one step
az aks show -g $RG -n $CLUSTER --query "{
aadManaged: aadProfile.managed, azureRbac: aadProfile.enableAzureRbac,
localAccountsDisabled: disableLocalAccounts,
oidc: oidcIssuerProfile.enabled, workloadIdentity: securityProfile.workloadIdentity.enabled,
defender: securityProfile.defender.securityMonitoring.enabled,
imageCleaner: securityProfile.imageCleaner.enabled,
kvCsi: addonProfiles.azureKeyvaultSecretsProvider.enabled,
kvRotation: addonProfiles.azureKeyvaultSecretsProvider.config.enableSecretRotation,
azurePolicy: addonProfiles.azurepolicy.enabled,
privateCluster: apiServerAccessProfile.enablePrivateCluster,
authorizedIps: apiServerAccessProfile.authorizedIpRanges,
networkPolicy: networkProfile.networkPolicy, outboundType: networkProfile.outboundType,
upgradeChannel: autoUpgradeProfile.upgradeChannel, nodeOsChannel: autoUpgradeProfile.nodeOsUpgradeChannel,
k8sVersion: currentKubernetesVersion, tier: sku.tier }" -o jsonc
{
"aadManaged": true,
"authorizedIps": null,
"azurePolicy": true,
"azureRbac": true,
"defender": true,
"imageCleaner": null,
"k8sVersion": "1.3x.x",
"kvCsi": true,
"kvRotation": "true",
"localAccountsDisabled": true,
"networkPolicy": "cilium",
"nodeOsChannel": "NodeImage",
"oidc": true,
"outboundType": "loadBalancer",
"privateCluster": null,
"tier": "Standard",
"upgradeChannel": "patch",
"workloadIdentity": true
}
In-cluster checks
# cluster-admin bound directly to an individual user
kubectl get clusterrolebindings -o json | jq -r '.items[] | select(.roleRef.name=="cluster-admin") | "\(.metadata.name)\t\([.subjects[]? | "\(.kind):\(.name)"] | join(","))"'
# Business Pods using the default ServiceAccount
kubectl get pods -A -o json | jq -r '.items[] | select(.metadata.namespace|test("^(kube-|gatekeeper-|calico-)")|not) | select((.spec.serviceAccountName // "default")=="default") | "\(.metadata.namespace)/\(.metadata.name)"'
# Privileged containers / hostNetwork
kubectl get pods -A -o json | jq -r '.items[] | select(.spec.hostNetwork==true or ([.spec.containers[].securityContext.privileged]|any)) | "\(.metadata.namespace)/\(.metadata.name)"'
# Service principal passwords in environment variables (should not exist)
kubectl get deploy -A -o json | jq -r '.items[] | select([.spec.template.spec.containers[].env[]?.name] | index("AZURE_CLIENT_SECRET")) | "\(.metadata.namespace)/\(.metadata.name)"'
Azure-side checks
az acr show -n $ACR --query "{admin:adminUserEnabled, anonymousPull:anonymousPullEnabled, mode:roleAssignmentMode, publicNetwork:publicNetworkAccess}" -o jsonc
az monitor diagnostic-settings list --resource $(az aks show -g $RG -n $CLUSTER --query id -o tsv) --query "[].logs[?enabled].category" -o tsv
az policy state summarize --resource $(az aks show -g $RG -n $CLUSTER --query id -o tsv) --query "results.nonCompliantPolicies"
Lab 8: generate a review report for aks-lab (about 8 minutes)
#!/usr/bin/env bash
# Usage: RG=rg-aks-lab CLUSTER=aks-lab ./aks-review.sh > report.txt
set -euo pipefail
J=$(az aks show -g "$RG" -n "$CLUSTER" -o json)
q(){ echo "$J" | jq -r "$1"; }
check(){ # name result(true/false) fix suggestion
if [ "$2" = "true" ]; then printf "PASS %-42s\n" "$1"; else printf "FAIL %-42s -> %s\n" "$1" "$3"; fi; }
check "Managed Entra integration" "$(q '.aadProfile.managed // false')" "az aks update --enable-aad --aad-admin-group-object-ids <gid>"
check "Azure RBAC for K8s" "$(q '.aadProfile.enableAzureRbac // false')" "az aks update --enable-azure-rbac"
check "Disable local accounts" "$(q '.disableLocalAccounts // false')" "az aks update --disable-local-accounts && az aks rotate-certs"
check "Workload Identity" "$(q '.securityProfile.workloadIdentity.enabled // false')" "az aks update --enable-oidc-issuer --enable-workload-identity"
check "Key Vault CSI + rotation" "$(q '(.addonProfiles.azureKeyvaultSecretsProvider.config.enableSecretRotation // "false") == "true"')" "az aks addon update --addon azure-keyvault-secrets-provider --enable-secret-rotation"
check "Azure Policy add-on" "$(q '.addonProfiles.azurepolicy.enabled // false')" "az aks enable-addons --addons azure-policy"
check "API server access restricted" "$(q '(.apiServerAccessProfile.enablePrivateCluster // false) or ((.apiServerAccessProfile.authorizedIpRanges // []) | length > 0)')" "Authorized IP or private cluster (hour 2)"
check "NetworkPolicy" "$(q '(.networkProfile.networkPolicy // "none") != "none"')" "Enable Cilium/Azure NPM (hour 2)"
check "Node OS patch channel" "$(q '(.autoUpgradeProfile.nodeOsUpgradeChannel // "None") != "None"')" "az aks update --node-os-upgrade-channel NodeImage"
check "Defender sensor" "$(q '.securityProfile.defender.securityMonitoring.enabled // false')" "az aks update --enable-defender"
AKS_ID=$(q '.id')
CATS=$(az monitor diagnostic-settings list --resource "$AKS_ID" --query "[].logs[?enabled].category" -o tsv | tr '\n' ' ')
check "Audit log kube-audit-admin" "$([[ "$CATS" == *kube-audit-admin* ]] && echo true || echo false)" "az monitor diagnostic-settings create …"
check "guard logs" "$([[ "$CATS" == *guard* ]] && echo true || echo false)" "az monitor diagnostic-settings create …"chmod +x aks-review.sh; RG=rg-aks-lab CLUSTER=aks-lab ./aks-review.sh | tee report.txt
PASS Managed Entra integration PASS Azure RBAC for K8s PASS Disable local accounts PASS Workload Identity PASS Key Vault CSI + rotation PASS Azure Policy add-on FAIL API server access restricted -> Authorized IP or private cluster (hour 2) PASS NetworkPolicy PASS Node OS patch channel FAIL Defender sensor -> az aks update --enable-defender PASS Audit log kube-audit-admin PASS guard logs
MYIP=$(curl -s https://api.ipify.org) az aks update -g $RG -n $CLUSTER --api-server-authorized-ip-ranges $MYIP/32 RG=rg-aks-lab CLUSTER=aks-lab ./aks-review.sh | grep "API Server"
Risk: after this, only these IPs can reach the API server. Add the IPs of your CI agents and colleagues too, since the Cloud Shell egress IP changes. After the lab, you can clear the setting with --api-server-authorized-ip-ranges "".
Case 1: a release review gate
Approach: the platform team splits the 16 baseline items into “required (blocks release)” and “recommended (exceptions must be recorded)”. Required items: Entra, local accounts disabled, Azure RBAC, Workload ID, Safeguards ≥ Warn, allowed images, audit logs, and supported versions. Defaults come from the Terraform AVM module. The pipeline runs the review script, and any FAIL blocks the merge.
Case 2: a quarterly drift check finds a “temporary” relaxation
Problem: half a year earlier, --enable-local-accounts was turned on temporarily for troubleshooting and never reverted. Approach: Azure Policy with Deny enforces “local authentication disabled,” so any attempt to re-enable it is rejected by ARM. Break-glass now requires a temporary policy exemption that has an expiry time.
Case 3: a compliance audit needs evidence
Approach: export the Azure Policy compliance state, Defender recommendations, the review script report, and the audit log query results, and archive them by control. Attach the check command and a timestamp to each item. Auditors care about being continuously compliant, not compliant on a single day.
Interactive troubleshooting tree: identity and security failures
Start from the symptom, choose step by step, and end with a diagnostic command and the direction for the fix.
1. With one command, check whether local accounts are disabled on the cluster, and whether Azure RBAC and Workload ID are enabled.
az aks show -g $RG -n $CLUSTER --query "{local:disableLocalAccounts, azrbac:aadProfile.enableAzureRbac, wi:securityProfile.workloadIdentity.enabled}" -o jsonc2. List all principals bound to cluster-admin.
kubectl get clusterrolebindings -o json | jq -r '.items[] | select(.roleRef.name=="cluster-admin") | .metadata.name + " " + ([.subjects[]?.name]|join(","))'You take over an environment with 12 AKS clusters, and in the first week you can only do five things to reduce risk the most. Which five?
Suggested answer: ① Entra, disable local accounts, and rotate certificates (eliminate unauditable back doors); ② authorized IPs or private access for the API server (shrink the attack surface); ③ export kube-audit-admin and guard (make investigation possible); ④ enable Defender for Containers on production subscriptions (get vulnerability and runtime visibility); ⑤ Azure Policy: allowed images and Safeguards Warn (see the current state first). Then continue with the Workload ID migration, PSS Restricted, and gated deployment Deny. Reasoning: close the back doors and gain visibility first, then tighten step by step.
Verified teaching videos
Official documentation
- Azure security baseline for AKS (MCSB)
- Best practices for cluster security and upgrades
- Best practices for pod security
- Security concepts for AKS
Video storyboard (about 75 seconds)
Visual: onion-like concentric circles, labeled from the outside in: detection, identity, admission, workloads.
Narration: A security baseline is defense in depth. Every layer can fail, so the layers are stacked.
Visual: the review script prints PASS or FAIL line by line.
Narration: Every control needs an executable check command that can run in a pipeline.
Visual: the Azure Policy shield covers several clusters, and the exception list shows an owner and an expiry date.
Narration: Enforce with policy, handle special cases through the exception process, and keep checking for drift.
Command cheat sheet
RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab; ACR and KV come from ~/.aks-lab.envEntra ID and RBAC (M1)
| Purpose | Command |
|---|---|
| Enable managed Entra + Azure RBAC | az aks update -g $RG -n $CLUSTER --enable-aad --aad-admin-group-object-ids $GID --enable-azure-rbac |
| Namespace-scoped role assignment | az role assignment create --role "Azure Kubernetes Service RBAC Writer" --assignee-object-id $GID --assignee-principal-type Group --scope $AKS_ID/namespaces/myapp |
| Download kubeconfig | az role assignment create --role "Azure Kubernetes Service Cluster User Role" … --scope $AKS_ID |
| Non-interactive login | kubelogin convert-kubeconfig -l azurecli|spn|msi|workloadidentity|devicecode |
| Who am I / what can I do | kubectl auth whoami · kubectl auth can-i --list -n myapp |
Local accounts and auditing (M2)
| Purpose | Command |
|---|---|
| Disable / restore local accounts | az aks update -g $RG -n $CLUSTER --disable-local-accounts · --enable-local-accounts |
| Revoke issued certificates | az aks rotate-certs -g $RG -n $CLUSTER (causes disruption) |
| Export audit logs | az monitor diagnostic-settings create -n aks-audit --resource $AKS_ID --workspace $LAW_ID --export-to-resource-specific true --logs '[{"category":"kube-audit-admin","enabled":true},{"category":"guard","enabled":true}]' |
| Who downloaded the admin credentials | az monitor activity-log list --resource-id $AKS_ID --offset 30d --query "[?contains(operationName.value,'listClusterAdminCredential')]" |
Workload Identity (M3)
| Purpose | Command |
|---|---|
| Enable | az aks update -g $RG -n $CLUSTER --enable-oidc-issuer --enable-workload-identity |
| issuer URL | az aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv |
| Create identity | az identity create -g $RG -n id-myapp |
| Federated credential | az identity federated-credential create -g $RG --identity-name id-myapp --name fic-aks-lab-myapp --issuer $ISSUER --subject system:serviceaccount:myapp:myapp-sa --audience api://AzureADTokenExchange |
| SA annotation / Pod label | azure.workload.identity/client-id: <clientId> · azure.workload.identity/use: "true" |
| Key Vault read permission | az role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" --scope $KV_ID |
Key Vault CSI (M4)
| Purpose | Command |
|---|---|
| Enable add-on | az aks enable-addons -g $RG -n $CLUSTER --addons azure-keyvault-secrets-provider |
| Rotation | az aks addon update -g $RG -n $CLUSTER --addon azure-keyvault-secrets-provider --enable-secret-rotation --rotation-poll-interval 2m |
| Mount status | kubectl get secretproviderclass,secretproviderclasspodstatus -n myapp |
| Component logs | kubectl -n kube-system logs -l app=secrets-store-provider-azure --tail=50 |
ACR and supply chain (M5)
| Purpose | Command |
|---|---|
| Attach ACR / diagnostics | az aks update -g $RG -n $CLUSTER --attach-acr $ACR · az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io |
| Build / import | az acr build -r $ACR -t myapp:1.1 . · az acr import -n $ACR --source docker.io/library/redis:7.4 --image redis:7.4 |
| ABAC mode | az acr show -n $ACR --query roleAssignmentMode · role Container Registry Repository Reader |
| Signing | notation sign --signature-format cose --id $KEY_ID --plugin azure-kv $ACR.azurecr.io/myapp@$DIGEST |
| Node image cleanup | az aks update -g $RG -n $CLUSTER --enable-image-cleaner --image-cleaner-interval-hours 48 |
Policy and Pod security (M6)
| Purpose | Command |
|---|---|
| Azure Policy add-on | az aks enable-addons -g $RG -n $CLUSTER --addons azure-policy |
| Safeguards | az aks safeguards create -g $RG -n $CLUSTER --level Warn · update --level Enforce --pss-level Restricted --excluded-ns ns1 ns2 · delete |
| Pre-flight checklist | kubectl apply -f x.yaml --dry-run=server |
| View constraints | kubectl get constrainttemplates · kubectl get pods -n gatekeeper-system |
Defender and review (M7–M8)
| Purpose | Command |
|---|---|
| Enable plan / sensor | az security pricing create -n Containers --tier standard · az aks update -g $RG -n $CLUSTER --enable-defender |
| Test alert | kubectl get pods --namespace=asc-alerttest-662jfi039n |
| Alert list | az security alert list --resource-group $RG -o table |
| Security configuration overview | az aks show -g $RG -n $CLUSTER --query "{local:disableLocalAccounts, azrbac:aadProfile.enableAzureRbac, wi:securityProfile.workloadIdentity.enabled, defender:securityProfile.defender.securityMonitoring.enabled}" |
Error code quick reference
| Error | Meaning | Check first |
|---|---|---|
AADSTS70021 | Federated credential issuer/subject mismatch | Issuer URL, namespace, SA name |
AADSTS700212 | Audience mismatch | Projected token audience, identity binding |
AADSTS700016 | Client ID does not exist | Whether the SA annotation was written as principalId |
ForbiddenByRbac (Key Vault) | Token is valid but lacks data plane permission | Key Vault Secrets User assignment |
401 Unauthorized (ACR pull) | kubelet identity has no pull permission | az aks check-acr, ABAC mode |
User does not have access to the resource in Azure | No Azure RBAC assignment | Role assignment scope, propagation delay |
Getting static credential isn't allowed … | Local accounts are disabled | Use Entra credentials instead |
denied the request: [azurepolicy-…] | Gatekeeper policy denial | The policy name and remediation suggestion in the message |
Capstone lab + final quiz
myapp namespace; ② the cluster has no usable local accounts; ③ myapp and Redis hold no static credentials, and the Redis password is in Key Vault and can be rotated; ④ images come only from ACR and are deployed by digest; ⑤ workloads pass Restricted PSS and Safeguards; ⑥ all changes are auditable, and every review script check PASSes (API server access restriction and Defender may be exempted per environment).source ~/.aks-lab.env; RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab
az aks show -g $RG -n $CLUSTER --query "{aad:aadProfile.managed, azrbac:aadProfile.enableAzureRbac, oidc:oidcIssuerProfile.enabled, wi:securityProfile.workloadIdentity.enabled}" -o jsonc
kubectl get ns myapp; kubectl -n myapp get sa myapp-sa; kubectl -n myapp get secretproviderclass myapp-kv
For anything missing, go back to the “Lab” tab of the relevant module and fill it in.
myapp namespace; disable local accounts and rotate certificates (in a maintenance window); turn on kube-audit-admin + guard.
az role assignment list --scope $AKS_ID/namespaces/myapp -o table az aks show -g $RG -n $CLUSTER --query disableLocalAccounts
myapp-sa, that Pods carry use: "true", and that secrets come from myapp-kv. Rotate the Redis password in Key Vault and complete one rolling restart:
az keyvault secret set --vault-name $KV -n redis-password --value "$(openssl rand -base64 24)" -o none sleep 150 kubectl -n myapp rollout restart deploy/redis deploy/myapp kubectl -n myapp rollout status deploy/redis; kubectl -n myapp rollout status deploy/myapp kubectl -n myapp port-forward deploy/myapp 5000:5000 & sleep 2; curl -s localhost:5000/healthz
Think about it: could the order in which the two Deployments restart cause a brief authentication failure? How would you design a dual-password window?
$ACR.azurecr.io/myapp@sha256:…, and change the redis image to $ACR.azurecr.io/redis:7.4, imported into ACR:
kubectl -n myapp set image deploy/redis redis=$ACR.azurecr.io/redis:7.4 kubectl -n myapp get deploy -o custom-columns=NAME:.metadata.name,IMAGE:.spec.template.spec.containers[0].image
--dry-run=server to check that the two Deployments produce no warnings:
az aks safeguards update -g $RG -n $CLUSTER --level Warn --pss-level Restricted for d in myapp redis; do echo "== $d"; kubectl -n myapp get deploy $d -o yaml | kubectl apply --dry-run=server -f - 2>&1 | grep -i warning || echo "no warnings"; done
aks-review.sh and save the report and exception notes as security-review-2026-11.md.--level Warn --pss-level Baseline; if you are not continuing now, run az aks stop -g $RG -n $CLUSTER.Open-ended self-check (6 questions)
1. Why is a ServiceAccount described as the security boundary for Workload Identity? What does that mean for namespace and RBAC design?
Federated credentials match on system:serviceaccount:ns:sa, so all Pods using the same SA get the same Azure identity. Anyone who can create a Pod in that namespace under that SA (such as an RBAC Writer) can borrow that identity. Therefore: give each application its own SA and identity; limit who can create Pods in the namespace; bind high-privilege identities only to platform namespaces.
2. List all the trust relationships and signers between “a Pod sends a request” and “reads a Key Vault secret.”
The cluster's SA signing private key issues the SA token (iss=OIDC issuer) → Entra trusts that issuer through the federated credential (signature verified via the public JWKS) → Entra issues an access token (aud=vault) → Key Vault trusts Entra's signature and authorizes id-myapp through Azure RBAC.
3. After local accounts are disabled, what do you do if Entra has a global outage? What are the risks of the process itself?
The official break-glass procedure: an account with the AKS Contributor role temporarily runs --enable-local-accounts → --admin; after recovery, disable local accounts again and rotate certificates. Risks: ARM sign-in also depends on Entra, so you need an emergency account that uses a different authentication path; during this window the certificate is unauditable super-privilege access, so it needs strict logging and rotation afterwards.
4. What are the best-fit scenarios for syncing CSI into a Kubernetes Secret versus mounting files only?
Syncing: needed for environment variables, Ingress TLS Secrets, or third-party charts that only support Secrets; the cost is that the values go into etcd and RBAC Writers can read them. Mount only: for highly sensitive secrets where the app can read files and supports hot reload.
5. Why does Deployment Safeguards Enforce need a Warn period first?
Enforce mutates resources (default 500m/2Gi requests, anti-affinity) and rejects non-compliant manifests. This can trigger scale-ups, scheduling failures, or deployment interruptions. The Warn period is used to collect non-compliant manifests, fix charts, and decide which namespaces to exclude.
6. Before switching ACR to ABAC mode, what is your checklist?
Inventory all pull and push identities (each cluster's kubelet identity, pipelines, ACR Tasks); pre-assign an equivalent ABAC role to each identity (Reader + Catalog Lister / Writer / Contributor); configure --source-acr-auth-id for ACR Tasks; rehearse in pre-production; right after the switch, refresh AKS node credentials (restart kubelet or replace nodes); remove the old roles after verification.
Sources and versions
| Topic | Verified conclusion | Source (accessed 2026-11-15) |
|---|---|---|
| Entra integration | The AKS resource provider manages the server-side and client-side apps; once enabled, it cannot be turned off; for 1.24+ clusters, the kubeconfig automatically uses the kubelogin exec format; break-glass requires Azure Kubernetes Service Contributor (managedClusters/write); if the admin group is misconfigured, fix it directly with --aad-admin-group-object-ids | Enable Entra ID authentication (page updated 2026-06) |
| Azure RBAC for K8s | Four built-in roles and their limits (Reader cannot read Secrets; Writer can read Secrets and run Pods as any SA); namespace scope $AKS_ID/namespaces/<ns>; new assignments take up to about 5 minutes to propagate; the tenant must match the subscription; AKS Automatic enables it by default; ABAC conditions for CRDs are in preview | Entra ID authorization for the Kubernetes API (2026-08) |
| Local accounts | --disable-local-accounts / --enable-local-accounts; properties.disableLocalAccounts; original error text 'Getting static credential isn't allowed because this cluster is set to disable local accounts.'; on existing clusters, certificates must be rotated after disabling; 'non-auditable backdoor' | Manage local accounts |
| Workload ID | AKS 1.22+, CLI 2.47.0+; up to 20 federated identity credentials (FICs) per identity; virtual nodes not supported; default audience api://AzureADTokenExchange; annotations/labels and their defaults (token expiration 3600, range 3600–86400); do not hardcode the token path; identity bindings set the default audience to api://AKSIdentityBinding, and using direct federation by mistake returns AADSTS700212; minimum SDK version table; pod-managed identity deprecated 2022-10-24 | Workload ID overview (2026-10) · Deploy and configure (2026-10) |
| Key Vault CSI | Add-on azure-keyvault-secrets-provider, CLI 2.30.0+; automatically creates the azurekeyvaultsecretsprovider-xxxxx identity, which cannot be blocked; default rotationPollInterval is 2m; az aks addon update … --enable-secret-rotation --rotation-poll-interval; subPath is not rotated; synced Secrets are removed along with the Pods that mount them; metrics ports 8898 / 8095; roles Secrets User / Certificate User; disabling the add-on returns an error when an SPC exists | CSI driver (2026-09) · Identity access (2026-09) · Configuration options |
| Image Integrity | Preview; based on Ratify + Azure Policy + Gatekeeper; 1.26+; requires OIDC and the Policy add-on; Notation verifier only; Audit only; up to 200 unique signatures; not for production; built-in initiative '[Preview]: Use Image Integrity to ensure only trusted images are deployed' | Image Integrity |
| ACR ABAC | The mode 'RBAC Registry + ABAC Repository Permissions' (--role-assignment-mode rbac-abac) will become the default in the future; AcrPull/AcrPush/AcrDelete have no effect in this mode; equivalent role table; switching mode makes old credentials return 401, and AKS needs a kubelet restart or node replacement to refresh them | ACR ABAC repository permissions (updated 2026-06) |
| Deployment Safeguards | Warn / Enforce; Automatic defaults to Enforce with Baseline PSS, and Warn cannot be selected; Standard is optional, and PSS defaults to Privileged; az aks safeguards create/update/delete, --level, --excluded-ns, --pss-level; 10 policies and mutators (defaults 500m/2048Mi, minimum 100m/100Mi; anti-affinity weight 100 + topology spread); original error message text; Gatekeeper fail-open; 'all or nothing' | Deployment Safeguards (updated 2026-10) |
| Defender for Containers | Five domains; agentless discovery and vulnerability assessment (MDVM, daily rescans); sensor capabilities: anti-malware, DNS detection, binary drift detection and prevention; 60+ detections; MITRE mapping and Defender XDR; MCR image list includes defender-admission-controller; gated deployment with Audit/Deny and default audit rules | Introduction (2026-08) · Gated deployment (2026-10) · Alert validation |
| Control plane logs | Categories kube-apiserver, kube-audit, kube-audit-admin, guard, and others; resource-specific tables AKSAudit, AKSAuditAdmin, AKSControlPlane | AKS monitoring data reference |
Video verification notes
The following videos were verified for title and channel through the YouTube oEmbed endpoint (2026-11-15): Programming with Wolfgang, 'Authentication in Azure Kubernetes Service (AKS) explained' (tuXJMHfNqyU); 'Secure Azure DevOps Access to AKS via Entra ID' (0PFpkZhJUgw); 'Secure your Kubernetes Secrets with Azure Key Vault Secrets Provider' (FXEuo-6X3zA); 'AKS Governance Made Easy with Azure Policy' (rLjk_F2ZYLQ); MadeForCloud, 'Azure RBAC for AKS Authorization' (s2Uq_bJbb8w); Pixel Robots, 'Azure Kubernetes Service (AKS). Disable local admin account.' (wtvStwKaLqE); Azure Kubernetes Service (AKS), 'AKS Workload Identity - Quick Tutorial' (i2GobU0Wg48) and 'Exploring AKS Automatic Security' (qFgeZNp5NOk); Microsoft Azure, 'Azure AD Workload Identity on AKS | KubeCon 2022' (5WUP8KAzwCo); Cloud Explainers, 'AKS Workload Identity: Migrating from Pod Managed Identities Safely' (zx7QftuSud8); TechVantage, 'Azure Key Vault Secrets in AKS, Step by Step: CSI Driver + Workload Identity' (AQP6qN9sF8Q); CNCF Notary Project, 'What is Notation? | Container Image Signing' (ZMNUazoGwdk); BiteSizedCerts, 'Container Security: Defender for Containers, AKS, ACR, ACI, Container Apps (SC-500)' (oyqPif4QUwg); John Savill's Technical Training, 'Anatomy of Azure Policy' (4wGns611G4w); Microsoft Security Community, 'Defender for Containers - Demo in a Multi-Cloud Environment Lab' (62_Cj6yseno); Microsoft Security, 'AWS ECR Coverage in Defender for Containers | Defender for Cloud in the Field #25' (cxaFjMn-Zro); Microsoft Developer, 'Learn Live - AKS Security Best Practices' (WLgt3kobCxY); Cloud Security Podcast, 'Azure Kubernetes Service (AKS) Security Explained' (JD3mj5bTOuk); TechWorld with Nana, 'Kubernetes Security Best Practices you need to know | THE Guide for securing your K8s cluster!' (oBf5lrmquYI). Recording dates vary across these videos. For product names (Azure AD → Entra ID) and commands that have changed, follow the body text of this lesson.
Voice narration notes
The 'Voice' tab uses the browser's Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, and English terms are pronounced in en-US. Results depend on the voices installed on the operating system. The course-generation environment cannot call a TTS service, so no MP3 is embedded; if you need offline audio, give the narration script to any TTS tool.
Known limitations
- The commands in this lesson were not actually run in the generation environment. All IDs, GUIDs, IPs, name suffixes, times, and token lengths in the 'expected output' are sample values, and outputs labeled 'example' only illustrate the format. Azure Policy constraint names and Defender sensor Pod names change between versions.
- The
az aks safeguardscommand group is new, and some CLI versions may require theaks-previewextension. For the plan nameContainersused withaz security pricingand the extension name, follow the actual output ofaz security pricing show. - This page does not give specific prices for Defender for Containers, Log Analytics, Standard-tier control planes, or similar services. Use the Azure pricing calculator. Defender plans are enabled per subscription, so the impact is broad.
- Image Integrity is in preview and supports Audit only. For supported environments for gated deployment and the details of default rules, follow the Defender support matrix. In ACR ABAC mode, the behavior of
--attach-acris not explicitly documented, so this lesson conservatively recommends assigning Repository Reader manually. - The Workload ID lab uses
mcr.microsoft.com/azure-cli:2.67.0as the validation image; any recent version works. The manual token exchange example assumes thatcurlandsedare available in the image. - myapp:1.1 must support the
REDIS_PASSWORDenvironment variable. If the Docker lesson version does not have it, add one line as described in Module 5. Under Restricted, Redis runs as UID 999, following the user convention of the official redis image. - 'Disable local accounts → rotate certificates' causes a brief outage, so in the lab you may only read this step. Incorrect API Server authorized IP settings can lock you out.
- The times, sequence, and alert names in the animation are illustrative. They explain the mechanism and do not represent the platform's exact implementation.