AKS Hour 3: Identity and Security

Who can access the cluster (Entra ID + RBAC), which identity the applications in the cluster use to access Azure (Workload Identity), where secrets are kept (Key Vault CSI), which images run (ACR + integrity + scanning), which configurations are allowed (Azure Policy / Deployment Safeguards), and who finds out when something goes wrong (Defender for Containers)
AKS · Azure CLI 2.6x+Workload Identity GADeployment SafeguardsImage Integrity still in previewVerified against learn.microsoft.com · 2026-11
Overall learning goals
  • 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 Vault kv-aks-lab-<suffix>. Be able to explain each JWT field (iss/sub/aud) and the AADSTS error 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 subPath pitfall.
  • Set up image supply chain controls: ACR pull authorization (the difference between --attach-acr and 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

#TimeModuleCore contentAnimation / interactionLab (aks-lab)
0Before classWarm-up: identity inventory and least privilegeReuse the cluster from hours 1–2; list every identity involved in the cluster; turn on the features this hour needsIdentity inventory self-checkOIDC / WI / KV CSI / Policy add-ons ready
100–06Entra ID integration with Kubernetes RBAC / Azure RBACManaged Entra integration, kubelogin, two authorization modes, four built-in roles, namespace-scoped assignments, custom rolesRequest simulator for the authentication and authorization path of a single kubectl requestAuthorize the myapp namespace by Entra group
206–13Disable local accounts and access auditing--admin back door, --disable-local-accounts, certificate rotation, break-glass, control plane logs (kube-audit-admin, guard), activity logHow local certificates and Entra tokens look in audit logsDisable local accounts + query the audit log with KQL
313–21Workload IdentityOIDC issuer, federated credentials, mutating webhook, projected token, token exchange, identity bindingsCore animation: full token exchange + fault injectionmyapp reads Key Vault with id-myapp
421–28Key Vault secrets store CSI driverAdd-on, SecretProviderClass, three identity methods, rotation, sync to Secret, metricsMount and rotation timelinemyapp's Redis password comes from Key Vault
528–35Images and supply chain: ACR, image integrity and scanningkubelet identity and AcrPull, ACR ABAC mode, Notation signing, Image Integrity (preview), vulnerability assessment, gated deploymentThe four checkpoints an image must passPush myapp:1.1 to ACR and pull it from AKS
635–42Azure Policy and Pod securityAzure Policy add-on (Gatekeeper), built-in initiatives, Deployment Safeguards (Warn/Enforce, mutator), Pod Security StandardsAdmission pipeline: mutate → validate → rejectWarn → Enforce, fix the myapp manifests
742–50Microsoft Defender for ContainersAgentless discovery and vulnerability assessment, Defender sensor (eBPF), audit log analysis, binary drift, anti-malware, XDRAttack chain and detection point simulatorEnable the sensor and trigger a test alert
850–60Security baseline reviewReview item by item across six areas (identity / network / nodes / workloads / supply chain / detection), with automated checksBaseline scorer + troubleshooting treeGenerate a review report for aks-lab
—After classCheat sheet · Capstone labTurn myapp into a secure deployment with zero static credentialsFinal quiz (12 questions)Capstone lab

Knowledge coverage matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Access the cluster with an Entra identity and authorize by group✓✓·····✓az aks update --enable-aad --enable-azure-rbacM1 lab
Eliminate unauditable admin back doors·✓·····✓--disable-local-accountsM2 lab
Answer "who did what"·✓····✓✓az monitor diagnostic-settings create, KQLAKSAuditAdmin
Pods access Azure without keys··✓✓···✓az identity federated-credential createmyapp + id-myapp
Move secrets out to Key Vault and rotate them··✓✓···✓az aks addon update --enable-secret-rotationRedis password
Controlled image sources and integrity····✓✓✓✓az aks check-acr, notation signmyapp:1.1
Admission control: policy, PSS, Safeguards····✓✓·✓az aks safeguards create/updateWarn → Enforce
Runtime detection and response····✓·✓✓az aks update --enable-defenderTest alert
Identity and security troubleshooting✓✓✓✓✓✓·✓kubectl auth can-i, describe podTroubleshooting tree

Out of scope for this hour (and where to learn it)

TopicWhy it is not in this hourWhere to learn it
Kubernetes RBAC objects (Role/ClusterRole/Binding), ServiceAccount, Pod Security Admission, and general NetworkPolicy principlesGeneral Kubernetes knowledge; this hour covers only the AKS-specific differencesKubernetes Hour 5 (for AKS basics, see Hour 6)
Private clusters, authorized API server IP ranges, API server VNet integration, outbound firewallNetworking topic; this hour only references it in the baseline reviewAKS Hour 2
Pipelines deploy to AKS with OIDC (GitHub Actions / Azure DevOps workload identity federation)CI/CD tool detailsGitHub Hour 3 · Azure DevOps Hour 3
Deploying myapp with Helm, chart signingPackaging tool detailsHelm Hour 3
Node OS automatic upgrades, security patch channelsCovered under upgrades and operationsAKS Hour 6
Combined troubleshooting of identity and permission failures (including ACR pull failures)This hour only provides the troubleshooting tree; in-depth troubleshooting comes laterAKS Hour 7

How to use this course material

10 pages per module
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.
Learning progress
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).
English voice
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.
Version and status notes (verified 2026-11)Microsoft Entra Workload ID is GA on AKS (cluster 1.22+, Azure CLI 2.47.0+). Pod-managed identity (the open-source aad-pod-identity) was deprecated on 2022-10-24; do not use it. Once managed Entra integration is enabled, it cannot be turned off. Deployment Safeguards are optional in AKS Standard (Warn / Enforce), and default to Enforce + Baseline PSS in AKS Automatic. Image Integrity is still in preview. It supports only the Notation verifier and the Audit effect, and the official docs state that it should not be used for production registries or workloads. ACR's ABAC mode (--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.
Prerequisite coursesThis hour continues on the cluster created in hour 1, named 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)

First count how many "identities" an AKS cluster involves, then turn on everything this hour needs in one go
Before class ≈ 15 minChanges the cluster authentication mode (irreversible)
Prerequisites
  • You have completed hour 1: the resource group rg-aks-lab (canadacentral) and the cluster aks-lab exist 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 with az 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
}
IdentityWho it isWhat it is used forCovered in this hour
Human users / groupsEntra users, security groupskubectl access to the API serverM1: Entra integration + RBAC
Local admin certificateclusterAdmin client certificate (--admin)Bypasses Entra and accesses the cluster directlyM2: disable
Control plane identityThe cluster's system or user-assigned managed identityCreates load balancers, disks, modifies subnets, etc.Hours 1–2
kubelet identityThe <cluster>-agentpool user-assigned managed identity in the node resource groupPulls images from ACRM5: AcrPull
Add-on identitiesFor example azurekeyvaultsecretsprovider-<cluster>, azurepolicy-<cluster>Add-ons access AzureM4 / M6
Workload identityUser-assigned managed identity id-myapp + ServiceAccount myapp/myapp-saPod accesses Key Vault, etc.M3
Pipeline identityService principal / managed identity with workload identity federationCI/CD deploymentGitHub / ADO hours
Three least-privilege questions① Is this identity limited to what it must do? ② Is the scope as narrow as possible (namespace < cluster < resource group < subscription)? ③ Are the credentials short-lived (tokens), or long-lived (certificates, keys, client secrets)? The goal of this hour: all human and workload identities use short-lived Entra tokens, and no long-lived credentials remain in the cluster.

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
Security risks and notesStep ① changes how kubeconfig authenticates, so save your current work before running it. After enabling, existing 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

ResourceBilling 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.

Environment check list

Module 1 · Entra ID integration with Kubernetes RBAC / Azure RBAC

00:00 – 06:00 · Authentication is handled by Entra. Authorization is one of two options (or both): write a RoleBinding in the cluster, or create a role assignment in Azure.
6 minManaged Entra integrationAzure RBAC for K8sABAC conditions for CRDs: preview★★★★★
Learning objectives
  • Explain the components involved when kubectl get pods runs 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.
Prerequisite knowledge: Kubernetes RBAC (K8s hour 5), Azure role assignments. Importance: ★★★★★

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 storedRole / ClusterRole / RoleBinding / ClusterRoleBinding inside the clusterAzure role assignments (ARM); the scope can be the cluster or <cluster ID>/namespaces/<ns>
What to write for the subjectUser UPN/objectId, or kind: Group + group objectIdEntra users / groups / service principals / managed identities
Management toolskubectl / GitOpsaz CLI / portal / Terraform / Azure Policy
Multi-cluster consistencyDistributed per clusterAssigned once at subscription or resource group scope to cover multiple clusters
Propagation delayImmediateNew role assignments take up to about 5 minutes to propagate to the authorization service
PrerequisiteEntra integrationEntra integration, and the Entra tenant must be the same as the tenant of the cluster's subscription
Fine-grained control for CRDsWrite apiGroups/resources in the RoleCustom 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)

RoleWhat it can doNotes
Azure Kubernetes Service RBAC ReaderRead-only access to most objects in the namespaceCannot read Secrets (reading a Secret means obtaining ServiceAccount credentials, which is privilege escalation), and cannot see Role/RoleBinding either
Azure Kubernetes Service RBAC WriterRead and write most objects in the namespaceCannot 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 AdminNamespace admin; can create Role/RoleBindingCannot write ResourceQuota or the namespace itself
Azure Kubernetes Service RBAC Cluster AdminSuperuser; all resources, all namespacesOnly 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-ids should contain only one "platform admin" group, combined with PIM.

Comparison with other clouds

AKSEKSGKE
Human identityEntra ID (managed integration)IAM (Access Entries / legacy aws-auth ConfigMap)Google accounts / Google Groups for RBAC
Cloud-side authorizationAzure RBAC for KubernetesEKS Access PoliciesIAM roles (cluster-level) + K8s RBAC
Client pluginkubeloginaws eks get-tokengke-gcloud-auth-plugin
Common misconceptions ① "Enabling Entra makes the cluster secure": if local accounts are not disabled, the --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

kubectl exec: kubelogin get-token--login azurecliAuthorization: Bearer … Microsoft Entra ID Conditional Access / MFA / PIMToken contains oid, upn, groups ① Get token ② HTTPS AKS API server (managed control plane) ③ Authentication webhook (guard)Token → user + groups ④ AuthorizationAzure RBAC webhook (if enabled)Kubernetes RBAC (Role/Binding) ⑤ Admission (Gatekeeper, PSA…) ⑥ etcd / response Azure RBAC (ARM) Role assignments: AKS RBAC Reader/Writer/Admin/Cluster Admin Scope: …/managedClusters/aks-lab/namespaces/myapp DataActions: Microsoft.ContainerService/managedClusters/* SubjectAccessReview Control plane roles (only decide whether the kubeconfig can be downloaded)Cluster User Role / Cluster Admin Role kubeconfig (Entra mode)No certificates/keys, only exec plugin configurationGenerated by az aks get-credentials
Figure 1-1: authentication (who am I) is handled by Entra + guard; authorization (what can I do) is decided by the Azure RBAC webhook or Kubernetes RBAC

Decision diagram: Kubernetes RBAC or Azure RBAC?

Who needs permissions?People / pipelines / in-cluster components People, pipelines, multi-cluster unified→ Azure RBAC (namespace scope + groups) In-cluster ServiceAccounts, operators→ Kubernetes RBAC (delivered via GitOps) Both coexist, with unified auditingkube-audit-admin + guard logs (module 2)
Figure 1-2: the typical division of labor: people use Azure RBAC, workloads in the cluster use Kubernetes 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.

kubectlRead kubeconfig kubeloginEntra token guard authenticationuser + groups AuthorizationAzure RBAC webhook Result—
Choose a combination, then click "Next step".
$ kubectl …

Core commands and parameters

CommandPurposeKey parameters / notes
az aks create/update --enable-aadEnable managed Entra integration--aad-admin-group-object-ids (comma-separated), --aad-tenant-id; cannot be turned off once enabled
az aks update --enable-azure-rbacEnable Azure RBAC for Kubernetes--disable-azure-rbac turns it off; AKS Automatic has it enabled by default
az role assignment createAssign AKS data-plane roles--scope $AKS_ID/namespaces/myapp for namespace scoping
az role definition createCustom roleDataActions, for example Microsoft.ContainerService/managedClusters/apps/deployments/read
az aks get-credentialsGenerate kubeconfigWithout --admin, this produces Entra user credentials (kubelogin format)
kubelogin convert-kubeconfig -lSwitch to a non-interactive sign-in methodazurecli / devicecode / spn / msi / workloadidentity
kubectl auth can-iCheck 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)

Confirm the cluster's Entra configuration
az aks show -g $RG -n $CLUSTER --query aadProfile -o jsonc
{
  "adminGroupObjectIds": [ "9d1e…" ],
  "enableAzureRbac": true,
  "managed": true,
  "tenantId": "72f9…"
}
Create the namespace and assign roles (as admin):
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
Verify with a test user (add a test user to 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.

Custom read-only Deployment role:
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.json
Cleanup:
kubectl -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.

Command-line exercises
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
Scenario analysis
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

▶
Authentication in Azure Kubernetes Service (AKS) explained — Programming with Wolfgang
English · explains how local accounts, Entra authentication, and Kubernetes RBAC relate
▶
Azure RBAC for AKS Authorization — MadeForCloud
English · demonstrates how Azure RBAC role assignments control kubectl permissions

Official documentation

Video storyboard (about 90 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–70s
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.
Shot 4 · 70–90s
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.
Or score ≥ 70% on the quiz

Module 2 · Disable local accounts and access auditing

06:00 – 13:00 · Close the shared-certificate back door, then make every kubectl call traceable to a real person
7 min--disable-local-accountskube-audit-admin · guard★★★★★
Learning objectives
  • Understand AKS "local accounts": the clusterAdmin certificate downloaded by az aks get-credentials --admin remains valid after Entra is enabled, which makes it an unauditable back door.
  • Use --disable-local-accounts to 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).
Importance: ★★★★★ (a hard requirement of the security baseline; Azure Policy has a matching built-in definition)

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

ActionCommandEffect
Disable on a new clusteraz aks create … --enable-aad --aad-admin-group-object-ids <gid> --disable-local-accountsproperties.disableLocalAccounts=true
Disable on an existing clusteraz aks update -g $RG -n $CLUSTER --disable-local-accountsAfterward, --admin returns Getting static credential isn't allowed because this cluster is set to disable local accounts.
Revoke issued certificatesaz aks rotate-certs -g $RG -n $CLUSTEROn 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-accountsOnly 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

LayerWhat it recordsWhereTypical question
ARM activity logOperations on the AKS resource itself: creating or updating the cluster, listClusterAdminCredential, listClusterUserCredential, role assignment changesAzure Monitor activity log (kept for 90 days by default; can be exported)"Who downloaded the admin kubeconfig?" "Who re-enabled local accounts?"
Kubernetes audit logEvery API request: user, groups, verb, resource, response codeDiagnostic 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.

Common misconceptions ① "After local accounts are disabled, the old admin kubeconfig stops working automatically": on existing clusters it does not; you must rotate the certificates. ② "Enabling kube-audit is enough": the cost can far exceed the cost of the cluster itself, and without guard logs it is hard to explain a Forbidden. ③ "The activity log shows who deleted a Pod": it does not. The activity log only records ARM-level operations; Kubernetes API operations require the audit log. ④ "Break-glass means keeping an admin certificate in a vault": the official procedure is to temporarily re-enable local accounts, then disable them again immediately after recovery. The certificate should not be stored long-term.

Two credential paths

Local account (--admin)listClusterAdminCredentialkubeconfig with embedded certificate + private keyLong-lived; can be copied Entra credentialslistClusterUserCredentialkubeconfig contains only kubelogin configurationToken lasts about 1 hour; subject to Conditional Access API ServerCertificate → system:masters (bypasses RBAC)Token → guard → RBAC→ audit backend AKSAuditAdmin (example)user: masterclientgroups: system:masters→ cannot identify the person AKSAuditAdmin (example)user: alice@contoso.comgroups: [9d1e…, system:authenticated]→ traceable; can be correlated with Conditional Access logs
Figure 2-1: the same kubectl delete. In the audit log, one entry shows a "shared certificate" and the other shows a specific person.

Audit data flow

API ServerAudit policy (managed) Diagnostic settingsCategories: kube-audit-admin, guard Log AnalyticsResource-specific table AKSAuditAdmin… Alerts / SentinelKQL rules Can also be sent to a storage account (long-term retention) or an event hub (third-party SIEM) at the same time
Figure 2-2: control plane logs are exported through diagnostic settings. AKS's audit policy is managed by the platform and cannot be customized by users.

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.

Terminal
$
Audit log
(empty)
Tip: first, with "Disable local accounts" unchecked, click the four buttons in order; then check it and repeat; finally, check "Rotate certificates".

Core commands and parameters

CommandPurposeKey parameters / notes
az aks update --disable-local-accountsLocal accounts disabledEntra must be enabled first; --enable-local-accounts restores them
az aks show --query disableLocalAccountsCheck statustrue / false
az aks rotate-certsRotate cluster certificates and revoke old certificatesCauses an interruption (node components restart); requires a maintenance window
az monitor diagnostic-settings createExport control plane logs--logs '[{"category":"kube-audit-admin","enabled":true},{"category":"guard","enabled":true}]', --export-to-resource-specific true
az monitor activity-log listQuery 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)

First, make the mistake: download admin credentials (simulating legacy setup):
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]
Enable audit logs (run the diagnostic settings command on the "Commands" tab). The data usually appears in the workspace several minutes to about fifteen minutes later.
Disable local accounts:
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.

Revoke old certificates (causes an interruption, about 30 minutes; if time is short, just read through this step):
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
Create and trace a delete:
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)
Cleanup:
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.

Command-line exercises
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 table
2. 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}]'
Scenario analysis
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

▶
Azure Kubernetes Service (AKS). Disable local admin account. #AKS #Azure #Kubernetes #Shorts — Pixel Robots
English · Short video demonstrating how to disable local admin accounts
▶
Secure Azure DevOps Access to AKS via Entra ID — Programming with Wolfgang
English · Pipeline that avoids admin credentials and uses Entra identities to access AKS

Official documentation

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
Shot 4 · 60–75s
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.
Or score ≥ 70% on the quiz

Module 3 · Workload Identity (Microsoft Entra Workload ID)

13:00 – 21:00 · Pods carry no secrets. They exchange a token issued by Kubernetes for an Entra access token.
8 minGA · AKS 1.22+Up to 20 federated credentials per identitypod-managed identity deprecated★★★★★
Learning objectives
  • 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 the azure.workload.identity/use: "true" label.
  • Set up id-myapp and myapp/myapp-sa for myapp, and quickly identify which link in the chain failed based on errors such as AADSTS70021, AADSTS700212, and ForbiddenByRbac.
Prerequisites: ServiceAccounts and projected tokens (K8s hour 5), the OAuth 2.0 client credentials flow. Importance: ★★★★★ (core of this hour)

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

ComponentWherePurpose
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-systemOnly 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-myappThe Entra identity that is actually authorized to access resources
Federated identity credential (FIC)Attached to id-myappDeclares "trust this issuer to issue tokens for this subject, with audience api://AzureADTokenExchange"
ServiceAccount annotationmyapp/myapp-sa: azure.workload.identity/client-idTells the webhook which client ID to inject

The 8 steps of the token exchange (matches the Animation tab)

  1. 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.
  2. 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 a serviceAccountToken projected volume (audience api://AzureADTokenExchange, default expirationSeconds: 3600).
  3. 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.
  4. The Azure Identity SDK in the app (WorkloadIdentityCredential / DefaultAzureCredential) reads the token file, then sends a request to login.microsoftonline.com/{tenant}/oauth2/v2.0/token for a client credentials grant. It uses the SA token as the client_assertion and sets the scope to https://vault.azure.net/.default.
  5. Entra looks up the federated credential for id-myapp by client_id, then checks the token's iss, sub, and aud against it one by one.
  6. Entra reads the issuer's OIDC discovery document and JWKS, and uses the public key to verify the signature and validity period.
  7. Validation passes, and Entra issues an access token for id-myapp (audience https://vault.azure.net, lifetime set by Entra).
  8. The app calls Key Vault with the access token. Key Vault checks via Azure RBAC whether id-myapp has secrets/getSecret/action, and returns the secret.

Quick reference: annotations and labels

KeyLocationNotes
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-idSA annotationClient ID of the managed identity or app to use
azure.workload.identity/tenant-idSA annotation (optional)Defaults to the tenant from the azure-wi-webhook-config ConfigMap
azure.workload.identity/service-account-token-expirationSA or Pod annotation (optional)expirationSeconds for the projected token. Default 3600, range 3600–86400. Pod annotation takes precedence.
azure.workload.identity/skip-containersPod annotation (optional)Semicolon-separated. Excludes certain containers from receiving the token (for example, sidecars).
azure.workload.identity/inject-proxy-sidecarPod annotation (optional)Injects a proxy sidecar that intercepts IMDS requests. Used for legacy SDKs migrating from pod identity.

Why: advantages over other approaches

ApproachSecretGranularityStatus
Service principal password in a SecretLong-lived key, needs rotationAnyone who can read the Secret can impersonate itNot recommended
kubelet / node managed identity (IMDS)NoneShared by all Pods on the nodeOnly suitable for platform components
aad-pod-identityNonePer Pod, but relies on NMI interceptionDeprecated 2022-10-24
Workload IdentityNone (short-lived tokens)Per ServiceAccountGA, 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-token in your code. Always read the environment variable AZURE_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 audience api://AzureADTokenExchange. Otherwise you get AADSTS700212.
  • Minimum SDK versions: Python azure-identity 1.13.0, .NET 1.9.0, Java 1.9.0, Go azidentity 1.3.0, Node.js 3.2.0.
Common misconceptions ① "The Pod gets the id-myapp secret." No. The Pod only holds a short-lived JWT issued by Kubernetes, and the Entra access token is also short-lived. ② "The federated credential subject is the Pod name." No. It is 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

AKS cluster aks-lab API ServerTokenRequest · SA signing private keyiss = OIDC Issuer URL azure-wi-webhookmutating admissionInjects env + projected volume Pod (ns myapp, SA myapp-sa, label use=true) Projected token fileaud api://AzureADTokenExchangekubelet refreshes periodically App + Azure IdentityWorkloadIdentityCredentialReads AZURE_FEDERATED_TOKEN_FILE AZURE_CLIENT_ID · AZURE_TENANT_IDAZURE_FEDERATED_TOKEN_FILE · AZURE_AUTHORITY_HOST ③ AKS-managed OIDC discovery endpoint (public){issuer}/.well-known/openid-configuration{issuer}/openid/v1/jwks (public keys) Microsoft Entra IDid-myapp → federated credential:iss = cluster OIDC URL; sub = system:serviceaccount:myapp:myapp-saaud = api://AzureADTokenExchange Key Vault kv-aks-lab-<suffix>Azure RBAC: id-myapp = Key Vault Secrets UserGET /secrets/redis-password ④ client_assertion ⑥ Fetch public key to verify signature ⑦ access token ⑧ Bearer
Figure 3-1 Trust direction: Entra trusts "tokens issued by the cluster issuer for some SA"; Key Vault trusts "tokens issued by Entra for id-myapp".

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.

Admin / IaCUAMI + FIC + RBAC API ServerTokenRequest / signing WI webhookInjects env + volume kubeletWrites/refreshes token file Pod: myappAzure Identity SDK Entra ID/oauth2/v2.0/token OIDC discovery endpoint (AKS-managed, public)openid-configuration · jwks Key Vault kv-aks-lab-<suffix>Azure RBAC authorization
Step 0 / 8
Select a fault type (or keep it normal), then click "Next step".
Request / response
$
Key claims of the current token
(no token yet)

Core commands and parameters

CommandPurposeKey parameters / notes
az aks update --enable-oidc-issuer --enable-workload-identityEnable the OIDC issuer and webhookCLI 2.47.0+; --disable-workload-identity turns it off
az aks show --query oidcIssuerProfile.issuerUrlGet the issuer URLUnique to each cluster and immutable
az identity createCreate a user-assigned managed identityRecord the clientId (for the SA) and the principalId (for role assignments)
az identity federated-credential createCreate a federated credential--issuer, --subject system:serviceaccount:ns:sa, --audience api://AzureADTokenExchange
az identity federated-credential listCheck existing federated credentialsWatch the limit of 20
az role assignment createAuthorize 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)

Create the Key Vault (Azure RBAC mode) and secret:
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
Create id-myapp, the federated credential, and the role assignment (run the commands from the "Commands" tab), then:
az role assignment create --assignee-object-id $UAMI_PRINCIPAL_ID --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" --scope $KV_ID
Create the ServiceAccount and verify the Pod:
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=120s
Look at the SA token claims (to understand iss/sub/aud):
kubectl -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", …}
Option A: complete the token exchange manually (to show the protocol itself):
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":{…
Option B: use the SDK/CLI the way an app does:
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.

Failure drill: rename the SA to 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.

Command-line exercises
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}'
Scenario analysis
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

▶
AKS Workload Identity - Quick Tutorial — Azure Kubernetes Service (AKS)
English · Quickstart from the AKS official channel
▶
Azure AD Workload Identity on AKS | KubeCon 2022 — Microsoft Azure
English · 2022 demo; still uses the name Azure AD (now Microsoft Entra), but the principles are the same
▶
AKS Workload Identity: Migrating from Pod Managed Identities Safely — Cloud Explainers
English · Migrating from aad-pod-identity

Official documentation

Video storyboard (about 100 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–70s
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.
Shot 4 · 70–100s
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.
Or score ≥ 70% on the quiz

Module 4 · Key Vault secret store CSI driver

21:00 – 28:00 · Mount secrets from Key Vault into the Pod as files without changing application code, and sync them into Kubernetes Secrets when needed
7 minAdd-on azure-keyvault-secrets-providerDefault poll interval 2m★★★★☆
Learning objectives
  • Understand the two components: the Secrets Store CSI Driver (DaemonSet aks-secrets-store-csi-driver) and the Azure provider (DaemonSet aks-secrets-store-provider-azure), plus the SecretProviderClass CRD.
  • 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, default rotationPollInterval 2m), the lifecycle of secretObjects syncing, and that environment variables and subPath mounts don't update automatically.
Prerequisites: Module 3; Kubernetes Secrets and volumes (K8s hour 2). Importance: ★★★★☆

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

  1. The Pod is scheduled to a node, and the kubelet calls CSI NodePublishVolume (driver secrets-store.csi.k8s.io).
  2. The driver reads the SecretProviderClass referenced by the Pod, requests a token for the Pod's ServiceAccount, and calls the Azure provider over gRPC (Unix socket).
  3. 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.
  4. The provider reads the objects listed under objects from 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).
  5. If secretObjects is 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.
  6. With rotation enabled, the driver re-fetches every rotationPollInterval and 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

OptionSecretProviderClass parametersGranularityRecommendation
Workload IDusePodIdentity: "false", clientID: <UAMI clientId>; the Pod uses an annotated SA (the official example also labels the Pod use: "true")Per SARecommended; 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 nodeOnly for platform-level, low-sensitivity secrets
Service ConnectorGenerated by az aks connection create keyvault --enable-csiDepends on configurationQuick 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: cert returns the certificate (PEM, without the chain); key returns the public key; secret returns 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 syncApp uses WI and reads directly via SDKDirect Kubernetes Secret
App changesReads filesReads environment variables or files (zero changes)Needs SDK codeNone
Secrets stored in etcd?NoYes (Secret object)NoYes
Can RBAC Writer read it?Requires exec into the PodYes (reads the Secret)NoYes
RotationFiles update automatically (app must reread)Secret updates; env requires Pod restartApp-controlledManual
When Key Vault is unavailableNew Pods can't startSame as leftApp handles itNot affected
Common misconceptions ① "With rotation on, environment variables also change." No. Environment variables are set when the process starts, so a restart is needed (tools like Reloader can help). ② "Mounting with subPath also rotates." No. This is a known Kubernetes limitation. ③ "A Secret created by secretObjects sync will always exist." No. Once all Pods mounting it are deleted, the synced Secret is deleted too. ④ "The add-on's managed identity is best practice." No. It is node-level, so anyone who can run a Pod on that node and reference a SecretProviderClass may be able to borrow it.

Components and data flow

Node (VMSS instance) kubeletNodePublishVolume aks-secrets-store-csi-driver (DS) aks-secrets-store-provider-azure (DS) gRPC (unix socket) Pod: redis (ns myapp, SA myapp-sa) tmpfs volume/mnt/secrets-store/redis-passwordUpdated in place on rotation env REDIS_PASSWORDFrom the synced Secretredis-authNeeds restart after rotation Secret redis-authsecretObjects sync(stored in etcd) Entra IDSA token → access token (WI mode) Key Vaultsecret: redis-passwordKey Vault Secrets User → id-myapp Re-fetched every rotationPollInterval (default 2m)
Figure 4-1 The driver handles mounting and syncing; the Azure provider handles identity and Key Vault access

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.

t = 0 min
LocationCurrent valueNotes
Key Vault redis-passwordv1Current version of the secret
/mnt/secrets-store/redis-passwordv1CSI volume file
Secret redis-auth (secretObjects)v1Synced Kubernetes Secret
Container environment variable REDIS_PASSWORDv1Read at process start
subPath-mounted /etc/redis/passv1Kubernetes limitation: not updated on rotation
Ready.
$ kubectl get secretproviderclasspodstatus -n myapp

Core commands and parameters

CommandPurposeKey parameters / notes
az aks enable-addons --addons azure-keyvault-secrets-providerEnable add-onFor a new cluster, use az aks create --enable-addons …
az aks addon update --addon azure-keyvault-secrets-providerModify configuration--enable-secret-rotation, --rotation-poll-interval 5m
az aks show --query addonProfiles.azureKeyvaultSecretsProviderView configuration and add-on identityconfig.enableSecretRotation, rotationPollInterval
kubectl get secretproviderclass,secretproviderclasspodstatus -n myappView SPC and per-Pod mount statuspodstatus records the mounted object versions
az aks disable-addons --addons azure-keyvault-secrets-providerDisable the add-onErrors 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)

Prepare variables (reuse the Key Vault, identity, and SA from Module 3):
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)
Create the SecretProviderClass:
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 }
EOF
Deploy Redis (mounts the CSI volume and reads the password from the file at startup; the synced Secret redis-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.

Observe rotation:
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.

Keep resources: Redis and the SecretProviderClass continue to be used by the myapp deployment in Module 5.

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.

Command-line exercises
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
Scenario analysis
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

▶
Secure your Kubernetes Secrets with Azure Key Vault Secrets Provider — Programming with Wolfgang
English · Add-on installation and SecretProviderClass demo
▶
Azure Key Vault Secrets in AKS, Step by Step: CSI Driver + Workload Identity — TechVantage
English · The same "CSI + Workload ID" combination covered in this hour

Official documentation

Video storyboard (about 80 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–65s
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.
Shot 4 · 65–80s
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.
Or score ≥ 70% on the quiz

Module 5 · Images and supply chain: ACR, image integrity, and scanning

28:00 – 35:00 · Where images are pulled from (ACR + kubelet identity), whether they are the ones we signed (Notation + Image Integrity), and whether they contain high-severity vulnerabilities (Defender scanning + gated deployment)
7 min--attach-acr / AcrPullACR ABAC mode: AcrPull doesn't applyImage Integrity: preview, Audit only★★★★☆
Learning objectives
  • Explain which identity AKS uses to pull images from ACR: the kubelet identity (not the Pod's workload identity). --attach-acr actually assigns it AcrPull.
  • Understand ACR's role assignment permission modes: under RBAC Registry + ABAC Repository Permissions (rbac-abac), AcrPull and AcrPush no longer apply, and you need roles such as Container Registry Repository Reader instead.
  • 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).
Prerequisites: image building and pushing from the Docker hour. Importance: ★★★★☆

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.io runs 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 roleAcrPullContainer Registry Repository Reader (+ Container Registry Repository Catalog Lister to list repositories)
Push roleAcrPushContainer Registry Repository Writer
Repository-level permissionsNone (token/scope maps only)Role assignment with an ABAC condition, for example repositories:name StringStartsWithIgnoreCase 'myapp/'
Owner/ContributorIncludes data planeControl 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 notation CLI 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.

Common misconceptions ① "The Pod uses Workload Identity, so pulling images uses that identity too." No. Image pulls happen in the kubelet, which uses the kubelet identity. ② "Enabling Image Integrity blocks unsigned images." Not currently. The preview only supports Audit. ③ "No scanner alerts means no problem." Scanning is based on known CVEs. You also need pinned digests, minimal base images, SBOMs, and provenance control. ④ "Using :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

CI pipelinedocker build / az acr buildSBOM · notation sign ACR acraks<suffix>myapp@sha256:… + signature referrerAdmin user disabled · private endpoint Defender vulnerability assessmentScan after push · daily rescanResults attached to the image as signed artifacts AKS admission and runtime ① Azure Policy / SafeguardsAllowed image sources, latest tag forbidden ② Image Integrity (preview)Ratify verifies Notation signatures · Audit ③ Defender gated deploymentAudit / Deny per vulnerability rule ④ kubelet pullkubelet identity · AcrPull / Repo Reader Runtime: Defender sensor (drift, malware) · Image Cleaner removes old images from nodesModule 7
Figure 5-1 The admission stage (①②③) determines whether a Pod can be created; the pull stage (④) determines whether the image can be retrieved.

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.

Image properties
Cluster controls
Click "kubectl apply".
$

Core commands and parameters

CommandPurposeKey parameters / notes
az acr createCreate a registry--sku Basic|Standard|Premium, --role-assignment-mode rbac-abac (optional)
az aks update --attach-acrAssign AcrPull to the kubelet identityRemove with --detach-acr; requires permission to create role assignments
az aks check-acrDiagnose ACR connectivity and authorization from inside the cluster--acr <name>.azurecr.io, optionally with --node-name
az acr build / az acr importCloud build, or import from another registryimport --source docker.io/library/redis:7.4 avoids Docker Hub rate limits
az acr repository show-manifests / az acr manifest list-metadataView digestPin with @sha256: when deploying
notation sign / notation verifySign / verifyKey Vault plugin azure-kv, --id <key id>
az aks update --enable-image-cleanerClean 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)

Create the ACR and attach it to the cluster (the first 3 commands on the "Commands" tab).
Push the image: in the myapp directory from the Docker hour, run 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.

Deploy myapp (pinned digest, Workload Identity SA, password from the synced Secret):
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
Trigger a pull failure and diagnose it:
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.

(Optional) View vulnerability assessment: after enabling Defender for Containers (Module 7), go to Defender for Cloud → Recommendations and look for "Azure registry container images should have vulnerabilities resolved".

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
Command-line exercises
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
Scenario analysis
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

▶
What is Notation? | Container Image Signing — CNCF Notary Project
English · Basic concepts of Notation signing
▶
Container Security: Defender for Containers, AKS, ACR, ACI, Container Apps (SC-500) — BiteSizedCerts
English · Overall view of ACR and Defender scanning

Official documentation

Video storyboard (about 80 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
Shot 4 · 60–80s
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.
Or score ≥ 70% on the quiz

Module 6 · Azure Policy and Pod security (Deployment Safeguards)

35:00 – 42:00 · Stop non-compliant manifests before they are written to etcd. Gatekeeper is managed centrally by Azure Policy, and Safeguards provides a ready-to-use set of best practices.
7 minAzure Policy add-onSafeguards: Warn / EnforcePSS: Privileged / Baseline / Restricted★★★★★
Learning objectives
  • 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.
Prerequisites: Pod Security Standards and admission control (K8s hour 5). Importance: ★★★★★

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 AutomaticAKS Standard
Default stateEnabled, EnforceOptional
Can be changed to WarnNo (you can only exclude namespaces)Yes
PSS defaultBaseline (cannot be turned off)Privileged (unrestricted)
PrerequisiteAzure Policy add-on (and register Microsoft.PolicyInsights); enabling Safeguards itself does not require Azure Policy permissions

Policies included in Safeguards (official list)

PolicyMutation under Enforce
Cannot Edit Individual Nodes (you cannot taint or label a single node directly)—
Containers must define CPU and memory requestsIf missing, set to CPU 500m / memory 2048Mi (requests=limits); if below 100m / 100Mi, raise to the minimum
Must have anti-affinity or topologySpreadConstraintsAdds 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

LevelMain restrictions
PrivilegedUnrestricted (AKS Standard default)
BaselineForbids privileged, hostNetwork/hostPID/hostIPC, hostPort, dangerous capabilities, non-default AppArmor/SELinux/procMount, Unconfined seccomp, and unsafe sysctls; hostPath is also restricted
RestrictedOn 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.
Common misconceptions ① “Enforce only rejects.” It also modifies your Pods (for example, it adds a 2Gi memory request), which can suddenly leave nodes short of resources and increase Pending Pods. ② “A policy takes effect as soon as it is assigned.” The add-on syncs assignments periodically (the official docs say about every 15 minutes), so new policies take time to arrive. ③ “If Gatekeeper goes down, it blocks all deployments.” It is fail-open. ④ “Safeguards equals Restricted PSS.” PSS is a separate setting (--pss-level), and AKS Standard defaults to Privileged.

Admission pipeline

kubectl applyDeployment Authentication + authorizationModule 1 Mutating admissionWI webhook · SafeguardsMutators (Enforce) Validating admissionGatekeeper (Azure Policy)PSA · Defender gate Written to etcd (including warnings) Forbidden: denied the request Azure Policy add-on (periodically syncs assignments → constraints)Gatekeeper audits existing resources → compliance results report back to Azure Policy Azure Policy (subscription / management group / resource group)Safeguards plan · PSS plan · custom assignment
Figure 6-1: mutate first, then validate; Gatekeeper is rolled out centrally by Azure Policy and reports compliance back

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.

Manifest features
Safeguards level
PSS level (--pss-level)
Select, then submit.
$ kubectl apply -f deployment.yaml

Core commands and parameters

CommandPurposeKey parameters / notes
az aks enable-addons --addons azure-policyInstall the Azure Policy add-onRun az provider register -n Microsoft.PolicyInsights first
az aks safeguards createEnable Deployment Safeguards-g/-n or --cluster <id>; --level Warn|Enforce
az aks safeguards updateChange the level, exclude namespaces, PSS--excluded-ns ns1 ns2 (space-separated), --pss-level Baseline|Restricted|Privileged
az aks safeguards deleteDisable Safeguards—
az policy assignment createAssign a policy or initiative--policy-set-definition, --scope, --params
kubectl get constrainttemplates,constraintsView the constraints pushed to the clusterkubectl 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)

Enable Safeguards (Warn + Baseline): run the first two commands on the “Commands” tab, then wait about 15 minutes for policies to sync (you can keep reading in the meantime).
Submit a “bad” manifest:
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.

Check whether myapp and Redis are compliant (the manifests from modules 4–5 already include requests, probes, and pinned versions):
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.

Switch to Restricted and fix:
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/redis
Switch to Enforce and verify:
az 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"}}
Revert to settings suitable for the later hours (the scaling lab in hour 4 creates many test Pods):
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).

Command-line exercises
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
Scenario analysis
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

▶
AKS Governance Made Easy with Azure Policy — Programming with Wolfgang
English · Azure Policy add-on and built-in policy demo
▶
Exploring AKS Automatic Security — Azure Kubernetes Service (AKS)
English · AKS official channel, covering Safeguards and PSS as enabled by default in Automatic
▶
Anatomy of Azure Policy — John Savill's Technical Training
English · The structure of Azure Policy itself (definitions, initiatives, assignments, effects)

Official documentation

Video storyboard (about 80 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–65s
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.
Shot 4 · 65–80s
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.
Or score ≥ 70% on the quiz

Module 7 · Microsoft Defender for Containers

42:00 – 50:00 · The first six modules cover prevention; this module covers detection: posture, vulnerabilities, runtime threats, and response
8 minutesAgentless discovery + vulnerability assessmentDefender sensor (eBPF)Subscription-level plan, billed per vCore★★★★☆
Learning objectives
  • 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.
Importance: ★★★★☆ (costs are significant; the lab is optional)

What: the five areas

AreaCapabilityHow it works
Security posture managementDiscovers clusters, workloads, and configuration; detects misconfigurations (control plane hardening recommendations); Security Explorer for risk huntingAgentless: reads cloud APIs and Kubernetes APIs; data plane hardening depends on the Azure Policy add-on
Vulnerability assessmentACR images, running containers, supported nodes; OS and language packages; exploitability information; daily rescansAgentless, provided by Microsoft Defender Vulnerability Management
Runtime threat protection60+ Kubernetes-aware analytics and anomaly detections; mapped to MITRE ATT&CK; can be investigated and responded to in Defender XDRSensor (node process and network events) + agentless (Kubernetes audit log analysis)
Software supply chain protectionImage scan results are linked to images in the registry, supporting gated deployments (Audit / Deny)Vulnerability assessment + defender-admission-controller
Deployment and monitoringFinds clusters without the sensor installed and deploys the components at scaleAuto-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 as low-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-config to specify a Log Analytics workspace). Use --disable-defender to 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.

Common misconceptions ① “Enabling the plan only affects this one cluster.” The plan is subscription-level: every cluster and registry in the subscription is covered and billed. ② “Without the sensor there is no detection at all.” Audit log analysis and vulnerability assessment are agentless, but process-level detections (drift, malware, DNS) need the sensor. ③ “Alerts automatically block attacks.” Most capabilities detect and alert; blocking capabilities (drift prevention, gated deployment Deny) must be configured explicitly. ④ “Test alerts appear immediately.” They usually take several minutes or longer.

Components and data flow

aks-lab API ServerAudit logs → agentless analysisKubernetes API → discovery Defender sensor (DS)eBPF: process, file, network, DNSDrift · anti-malware Azure Policy add-onData plane hardening recommendations defender-admission-controller (gated deployment) Workloads: myapp, redisVulnerabilities in running containers (daily scan) Microsoft Defender for CloudRecommendations · alerts · attack paths · Security ExplorerCloud security graph (vulnerabilities + exposure + identity) Microsoft Defender XDR / SentinelEvent correlation, investigation, response ACR: image vulnerability assessment (MDVM)Scanned after push · results linked to the image as a signed artifact
Figure 7-1: two data sources: agentless (APIs, audit logs, registry scanning) and sensor-based (node runtime)

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.

Attacker terminal
attacker$
Defender alert (illustrative)
(no alerts)
Click to start.

Core commands and parameters

CommandPurposeKey parameters / notes
az security pricing create -n Containers --tier standardEnable the plan on the current subscription--tier free turns it off; affects the entire subscription
az security pricing show -n ContainersView plan status and extensions—
az aks update --enable-defenderDeploy the sensor on a cluster--defender-config <json> to specify the workspace; --disable-defender
az aks show --query securityProfile.defenderView a cluster's Defender configurationsecurityMonitoring.enabled
az security alert listList alertsFilter 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)

Cost warning: the plan is enabled at the subscription level and billed per vCore-hour of protected nodes. In a shared subscription, check with your administrator first. After the lab, turn it off with az security pricing create -n Containers --tier free (if the subscription already had it enabled, do not turn it off).
Check the current status:
az security pricing show -n Containers --query "{tier:pricingTier, ext:extensions[].{name:name,on:isEnabled}}" -o jsonc
Enable the plan and sensor (the first two commands on the “Commands” tab) and confirm the Pods are running.
Generate two kinds of detectable events:
# 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.

View alerts: in the portal, go to Defender for Cloud → Security alerts and filter by resource 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
View the vulnerability assessment: search the recommendations list for “container images should have vulnerabilities resolved” and review the findings for myapp:1.1 and redis:7.4.
Cleanup:
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.

Command-line exercises
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
Scenario analysis
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

▶
Defender for Containers - Demo in a Multi-Cloud Environment Lab — Microsoft Security Community
English · End-to-end demo
▶
AWS ECR Coverage in Defender for Containers | Defender for Cloud in the Field #25 — Microsoft Security
English · Official show explaining registry vulnerability assessment (using ECR as the example; the principle is the same as for ACR)

Official documentation

Video storyboard (about 80 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–65s
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.
Shot 4 · 65–80s
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.
Or score ≥ 70% on the quiz

Module 8 · Security baseline review

50:00 – 60:00 · Combine the first seven modules into an executable, automatable review checklist, and get a troubleshooting path for identity and security failures
10 minutesMCSB · AKS security best practices · CIS AKS BenchmarkScriptable★★★★★
Learning objectives
  • 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).
Reference frameworks: the AKS security baseline in the Microsoft cloud security benchmark (MCSB), the security best practices in the AKS docs, and the CIS AKS Benchmark. Importance: ★★★★★

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)

#AreaControlCheck methodModule in this hour
1IdentityManaged Entra integration, with the admin group managed through PIMaz aks show --query aadProfileM1
2IdentityAzure RBAC (or K8s RBAC bound only to groups); no personal accounts bound directly to cluster-adminaadProfile.enableAzureRbac; kubectl get clusterrolebindings -o wideM1
3IdentityLocal accounts disableddisableLocalAccounts == true; Policy “local authentication methods disabled”M2
4IdentityWorkloads use Workload ID, with no service principal password SecretssecurityProfile.workloadIdentity.enabled; search for AZURE_CLIENT_SECRETM3
5IdentitySecrets come from Key Vault; sensitive secrets are not synced as Kubernetes Secrets; rotation is enabledaddonProfiles.azureKeyvaultSecretsProvider.configM4
6NetworkAPI server private, or authorized IP restrictionsapiServerAccessProfileHour 2
7NetworkNetworkPolicy is enabled and each namespace has a default denynetworkProfile.networkPolicy; kubectl get netpol -AHour 2
8NetworkEgress is controlled (NAT Gateway / firewall); public LoadBalancers are governed by policynetworkProfile.outboundType; PolicyHour 2
9NodesSupported Kubernetes versions, an automatic upgrade channel, and a node OS security patch channelautoUpgradeProfileHour 6
10NodesNo SSH access to nodes (or SSH is disabled); use kubectl debugNode pool securityProfile.sshAccess (follow the CLI output)Hour 7
11WorkloadsDeployment Safeguards ≥ Warn; PSS Baseline/Restricted for production namespacesaz aks safeguards show (follow the CLI)M6
12WorkloadsSystem namespaces do not run business workloads; business service accounts do not use defaultkubectl get pods -A -o jsonpathM3, M6
13Supply chainOnly private registries allowed; ACR admin user and anonymous pull disabledPolicy “allowed images”; az acr show --query adminUserEnabledM5
14Supply chainVulnerability assessment enabled; gating for high-risk images (Audit first, then Deny)Defender recommendationsM5, M7
15DetectionControl plane logs: kube-audit-admin + guard exportedaz monitor diagnostic-settings listM2
16DetectionDefender for Containers (production subscription), with alerts routed to the SOCsecurityProfile.defenderM7

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.

Common misconceptions ① “A 100% security score means you are secure.” The score only covers the recommendations it knows about; exceptions and business-logic risks are not included. ② “One review is enough.” Configurations drift (someone re-enables local accounts, or a temporary policy relaxation is never reverted), so you need continuous checks and Policy enforcement. ③ “The stricter the baseline, the better.” A baseline without an exception process gets bypassed; use Audit first, then Deny, and tier by namespace.

Defense in depth: six areas and this hour's modules

Detection and auditing (M2 audit logs · M7 Defender) Identity and access (M1 Entra + RBAC · M2 disable local accounts) · Network exposure (hour 2) Admission control (M6 Policy / Safeguards / PSS · M5 allowed images / signing / gating) Workloads: myapp (M3 Workload ID · M4 Key Vault CSI · non-root · read-only root filesystem) Nodes: supported versions · OS security patch channel · no SSH (hours 6–7) Images: from ACR, pinned digest, scanned (M5)
Figure 8-1: any layer can fail (for example, Gatekeeper fails open), so layers are stacked and the outermost layer, detection, acts as the safety net

Review process

Collectaz aks show / kubectl Compare against baseline16 items · weighted Handle exceptionsOwner · expiry date Remediate / enforceIaC · Azure Policy Continuous checksPipeline · Defender
Figure 8-2: the review is a closed loop, not a one-time check

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)

Save the review script:
#!/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 …"
Run and interpret:
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
Fix one item: for example, add an authorized IP to the API server (replace it with your egress IP; for a private cluster, see hour 2):
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 "".

Put the script into a pipeline: in GitHub Actions or Azure DevOps, sign in with workload identity federation and run it daily; when a check FAILs, open a ticket (see GitHub hour 3).

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.

Command-line exercises
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 jsonc
2. 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(","))'
Scenario analysis
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

▶
Learn Live - AKS Security Best Practices — Microsoft Developer
English · Official Learn Live broadcast covering AKS security best practices
▶
Azure Kubernetes Service (AKS) Security Explained — Cloud Security Podcast
English · AKS security from an attacker and defender perspective
▶
Kubernetes Security Best Practices you need to know | THE Guide for securing your K8s cluster! — TechWorld with Nana
English · General Kubernetes security checklist

Official documentation

Video storyboard (about 75 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–75s
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.
Or score ≥ 70% on the quiz

Command cheat sheet

All key commands in this hour, grouped by topic. Variable conventions: RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab; ACR and KV come from ~/.aks-lab.env

Entra ID and RBAC (M1)

PurposeCommand
Enable managed Entra + Azure RBACaz aks update -g $RG -n $CLUSTER --enable-aad --aad-admin-group-object-ids $GID --enable-azure-rbac
Namespace-scoped role assignmentaz role assignment create --role "Azure Kubernetes Service RBAC Writer" --assignee-object-id $GID --assignee-principal-type Group --scope $AKS_ID/namespaces/myapp
Download kubeconfigaz role assignment create --role "Azure Kubernetes Service Cluster User Role" … --scope $AKS_ID
Non-interactive loginkubelogin convert-kubeconfig -l azurecli|spn|msi|workloadidentity|devicecode
Who am I / what can I dokubectl auth whoami · kubectl auth can-i --list -n myapp

Local accounts and auditing (M2)

PurposeCommand
Disable / restore local accountsaz aks update -g $RG -n $CLUSTER --disable-local-accounts · --enable-local-accounts
Revoke issued certificatesaz aks rotate-certs -g $RG -n $CLUSTER (causes disruption)
Export audit logsaz 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 credentialsaz monitor activity-log list --resource-id $AKS_ID --offset 30d --query "[?contains(operationName.value,'listClusterAdminCredential')]"

Workload Identity (M3)

PurposeCommand
Enableaz aks update -g $RG -n $CLUSTER --enable-oidc-issuer --enable-workload-identity
issuer URLaz aks show -g $RG -n $CLUSTER --query oidcIssuerProfile.issuerUrl -o tsv
Create identityaz identity create -g $RG -n id-myapp
Federated credentialaz 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 labelazure.workload.identity/client-id: <clientId> · azure.workload.identity/use: "true"
Key Vault read permissionaz role assignment create --assignee-object-id $PRINCIPAL_ID --assignee-principal-type ServicePrincipal --role "Key Vault Secrets User" --scope $KV_ID

Key Vault CSI (M4)

PurposeCommand
Enable add-onaz aks enable-addons -g $RG -n $CLUSTER --addons azure-keyvault-secrets-provider
Rotationaz aks addon update -g $RG -n $CLUSTER --addon azure-keyvault-secrets-provider --enable-secret-rotation --rotation-poll-interval 2m
Mount statuskubectl get secretproviderclass,secretproviderclasspodstatus -n myapp
Component logskubectl -n kube-system logs -l app=secrets-store-provider-azure --tail=50

ACR and supply chain (M5)

PurposeCommand
Attach ACR / diagnosticsaz aks update -g $RG -n $CLUSTER --attach-acr $ACR · az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io
Build / importaz 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 modeaz acr show -n $ACR --query roleAssignmentMode · role Container Registry Repository Reader
Signingnotation sign --signature-format cose --id $KEY_ID --plugin azure-kv $ACR.azurecr.io/myapp@$DIGEST
Node image cleanupaz aks update -g $RG -n $CLUSTER --enable-image-cleaner --image-cleaner-interval-hours 48

Policy and Pod security (M6)

PurposeCommand
Azure Policy add-onaz aks enable-addons -g $RG -n $CLUSTER --addons azure-policy
Safeguardsaz aks safeguards create -g $RG -n $CLUSTER --level Warn · update --level Enforce --pss-level Restricted --excluded-ns ns1 ns2 · delete
Pre-flight checklistkubectl apply -f x.yaml --dry-run=server
View constraintskubectl get constrainttemplates · kubectl get pods -n gatekeeper-system

Defender and review (M7–M8)

PurposeCommand
Enable plan / sensoraz security pricing create -n Containers --tier standard · az aks update -g $RG -n $CLUSTER --enable-defender
Test alertkubectl get pods --namespace=asc-alerttest-662jfi039n
Alert listaz security alert list --resource-group $RG -o table
Security configuration overviewaz 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

ErrorMeaningCheck first
AADSTS70021Federated credential issuer/subject mismatchIssuer URL, namespace, SA name
AADSTS700212Audience mismatchProjected token audience, identity binding
AADSTS700016Client ID does not existWhether the SA annotation was written as principalId
ForbiddenByRbac (Key Vault)Token is valid but lacks data plane permissionKey Vault Secrets User assignment
401 Unauthorized (ACR pull)kubelet identity has no pull permissionaz aks check-acr, ABAC mode
User does not have access to the resource in AzureNo Azure RBAC assignmentRole assignment scope, propagation delay
Getting static credential isn't allowed …Local accounts are disabledUse Entra credentials instead
denied the request: [azurepolicy-…]Gatekeeper policy denialThe policy name and remediation suggestion in the message

Capstone lab + final quiz

Turn myapp into a secure deployment with zero static credentials: Entra access, no local accounts, Workload ID, Key Vault secrets, ACR pinned digests, Restricted PSS, auditing, and detection
Post-class ≈ 40 minutesCovers all modules
Scenario: myapp is about to go live on aks-lab, and the security review sets these requirements: ① only members of Entra groups can access the cluster, and developers can only operate in the 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).
Pre-checks (module 0)
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.

Access control (modules 1–2): confirm that the developer group has only the RBAC Writer role on the 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
Identity and secrets (modules 3–4): confirm that myapp and redis both use 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?

Supply chain (module 5): confirm that the myapp image is $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
Admission (module 6): under Safeguards Warn + Restricted, use --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
Detection (module 7, optional): after enabling Defender, trigger a test alert and confirm it is visible; or record an exception in the report (do not enable it on the development subscription).
Review (module 8): run aks-review.sh and save the report and exception notes as security-review-2026-11.md.
Wrap-up: for the hours that follow, set Safeguards back to --level Warn --pss-level Baseline; if you are not continuing now, run az aks stop -g $RG -n $CLUSTER.
Acceptance checklist

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

Verification basis for all technical facts in this hour (verified 2026-11-15; learn.microsoft.com is authoritative)
TopicVerified conclusionSource (accessed 2026-11-15)
Entra integrationThe 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-idsEnable Entra ID authentication (page updated 2026-06)
Azure RBAC for K8sFour 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 previewEntra 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 IDAKS 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-24Workload ID overview (2026-10) · Deploy and configure (2026-10)
Key Vault CSIAdd-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 existsCSI driver (2026-09) · Identity access (2026-09) · Configuration options
Image IntegrityPreview; 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 ABACThe 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 themACR ABAC repository permissions (updated 2026-06)
Deployment SafeguardsWarn / 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 ContainersFive 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 rulesIntroduction (2026-08) · Gated deployment (2026-10) · Alert validation
Control plane logsCategories kube-apiserver, kube-audit, kube-audit-admin, guard, and others; resource-specific tables AKSAudit, AKSAuditAdmin, AKSControlPlaneAKS 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 safeguards command group is new, and some CLI versions may require the aks-preview extension. For the plan name Containers used with az security pricing and the extension name, follow the actual output of az 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-acr is not explicitly documented, so this lesson conservatively recommends assigning Repository Reader manually.
  • The Workload ID lab uses mcr.microsoft.com/azure-cli:2.67.0 as the validation image; any recent version works. The manual token exchange example assumes that curl and sed are available in the image.
  • myapp:1.1 must support the REDIS_PASSWORD environment 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.