Infrastructure

AKS Workload Identity: prove token rotation before restarting pods

A production runbook for separating pod injection, projected token rotation, federated credential matching, SDK behavior and Azure authorization before restarting pods or restoring a client secret.

07 Nov 2026 azureaksworkload-identitymicrosoft-entraoidcfederated-credentialskubernetesmanaged-identitysecurityobservabilityautomationrunbookrollbackproduction

An AKS workload that accessed Azure without a secret starts returning 401 after running normally for several hours. New pods may work while older replicas fail, or every replica may break after a deployment. The managed identity still exists and its Azure roles look unchanged. Under pressure, restarting all pods or adding a client secret appears to be the fastest recovery.

Both actions can hide the real fault. Microsoft Entra Workload ID for AKS crosses several contracts: the admission webhook mutates the pod, the kubelet rotates a projected Kubernetes service account token, the application or Azure SDK reads that file, Microsoft Entra matches its issuer, subject and audience to a federated credential, and the target service authorizes the resulting access token. A 401 only says that one authentication path failed; it does not identify the layer.

The running case is an API on AKS using a Kubernetes service account mapped to a user-assigned managed identity. The runbook ends with one decision: repair pod injection, correct the federation tuple, update token reload behavior, keep the current configuration and investigate the target, or roll back the deployment. Restoring a long-lived secret is an emergency exception, not the default recovery.

Freeze one failing replica and one healthy control

Do not restart the deployment before preserving evidence. Select one failing pod and, when available, one healthy pod from the same ReplicaSet. Record the image digest, pod UID, node, start time, service account, application version, first failure time and one redacted authentication error with its UTC timestamp.

yaml 01-workload-identity-incident.yml
incident: INC-AKS-742
namespace: payments
deployment: settlement-api
failing_pod: settlement-api-7c6b9f8d4f-k2m8q
healthy_control: settlement-api-7c6b9f8d4f-r7w5p
image_digest: sha256:<digest>
service_account: settlement-api
managed_identity_client_id: <client-guid>
target_resource: /subscriptions/<sub>/resourceGroups/rg-prod/providers/Microsoft.KeyVault/vaults/kv-prod
failure:
first_seen_utc: 2026-11-07T06:18:40Z
http_status: 401
entra_error: <redacted-code-and-correlation-id>
stop_conditions:
- pod identity cannot be attributed
- projected token path would be printed to shared logs
- proposed fix changes identity and RBAC together
- no healthy control or bounded canary is available

A rolling restart destroys the most useful comparison: whether the same manifest behaves differently before and after token renewal. Keep the failing replica out of service if needed, but retain it long enough to inspect metadata and file behavior. Never print the token itself into the terminal transcript, CI output or incident channel.

Locate the failing stage before changing permissions

Treat the path as five gates:

  1. Mutation: the pod template carries azure.workload.identity/use: "true", uses the intended service account, and the created pod contains the injected Azure environment variables and projected volume.
  2. Projection and rotation: the token file exists, remains readable and is refreshed by the kubelet.
  3. Application reload: the credential implementation rereads the projected assertion instead of retaining the first file content indefinitely.
  4. Federation: the AKS OIDC issuer, service account subject and api://AzureADTokenExchange audience exactly match a federated credential on the intended identity.
  5. Authorization: Microsoft Entra issued an Azure access token, then the target accepted that principal, audience and role.

An Entra error such as AADSTS70021 points toward a federation tuple that does not match. A target 403 normally occurs later and should move the investigation toward RBAC or data-plane permissions. A 401 returned by the application can represent either token acquisition or target rejection; preserve the inner SDK or service error before assigning a cause.

Verify mutation on the created pod

Inspect the Deployment, ServiceAccount and live pod separately. Labels added only to ServiceAccount metadata do not replace the required label on the pod template. Changing the template or service account does not retrofit an already running pod; the webhook acts when a pod is created.

bash 02-inspect-pod-injection.sh
NS="payments"
DEPLOY="settlement-api"
POD="settlement-api-7c6b9f8d4f-k2m8q"
SA="settlement-api"

kubectl -n "$NS" get deploy "$DEPLOY" \
-o jsonpath='{.spec.template.metadata.labels.azure\.workload\.identity/use}{"\n"}{.spec.template.spec.serviceAccountName}{"\n"}'

kubectl -n "$NS" get serviceaccount "$SA" \
-o jsonpath='{.metadata.annotations.azure\.workload\.identity/client-id}{"\n"}{.metadata.annotations.azure\.workload\.identity/tenant-id}{"\n"}'

kubectl -n "$NS" get pod "$POD" -o json \
| jq '{uid:.metadata.uid,
     serviceAccount:.spec.serviceAccountName,
     azureEnv:[.spec.containers[].env[]? | select(.name | startswith("AZURE_")) | .name],
     azureVolumes:[.spec.volumes[]? | select(.name | contains("azure")) | .name]}'

Expect AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE in the relevant container, plus the projected token volume. Compare failing and healthy pods. If one was created before the label, annotation or webhook became effective, restart only a canary replica after correcting the template. Do not restart the entire Deployment to compensate for an unproven mutation problem.

Also check whether azure.workload.identity/skip-containers excludes the failing container, or whether a sidecar receives the projection while the application does not. A successful token request from one container does not prove that every container has the same mount and environment.

Prove rotation without disclosing the assertion

The projected Kubernetes token is short-lived. Its lifetime is distinct from the Microsoft Entra access token obtained through token exchange. Increasing service-account-token-expiration may postpone the symptom, but it does not repair an application that reads the assertion once and never reloads it.

First prove that the file is present and changes over time. Capture only metadata and a one-way digest in a restricted incident record. The digest can prove change without exposing the JWT.

bash 03-observe-projected-token-rotation.sh
NS="payments"
POD="settlement-api-7c6b9f8d4f-k2m8q"
CONTAINER="api"

kubectl -n "$NS" exec "$POD" -c "$CONTAINER" -- sh -c '
set -eu
test -n "$AZURE_FEDERATED_TOKEN_FILE"
test -r "$AZURE_FEDERATED_TOKEN_FILE"
stat -c "modified=%y bytes=%s" "$AZURE_FEDERATED_TOKEN_FILE"
sha256sum "$AZURE_FEDERATED_TOKEN_FILE" | cut -d" " -f1
'

Repeat after the expected refresh interval and compare both pods. Interpret the result narrowly:

  • unchanged metadata and digest beyond the configured lifetime point toward projection or node-level refresh;
  • a changed digest with continued failures points toward application reload, federation or downstream token use;
  • a healthy new pod and failing old pod with different token metadata strongly justify investigating cached assertion content;
  • a readable and rotating file does not prove that Microsoft Entra accepts its claims.

Avoid mounting the projected token with subPath: projected volume updates do not propagate through a subPath mount. Also verify that the application uses a current Azure Identity library and a file-based workload identity credential path. A custom implementation must reopen or refresh the file; copying its contents into an environment variable at startup defeats rotation.

Compare the exact federation tuple

Inventory the cluster issuer, the service account coordinates and the federated credential attached to the identity referenced by azure.workload.identity/client-id. Display names are insufficient because an identity can be deleted and recreated with the same name but a different client or principal ID.

bash 04-compare-federation-contract.sh
AKS_RG="rg-aks-prod"
AKS_NAME="aks-prod"
IDENTITY_RG="rg-identities-prod"
IDENTITY_NAME="id-settlement-api"
NS="payments"
SA="settlement-api"

ISSUER=$(az aks show \
--resource-group "$AKS_RG" \
--name "$AKS_NAME" \
--query oidcIssuerProfile.issuerUrl \
--output tsv)

printf 'issuer=%s\nsubject=system:serviceaccount:%s:%s\naudience=api://AzureADTokenExchange\n' \
"$ISSUER" "$NS" "$SA"

az identity show \
--resource-group "$IDENTITY_RG" \
--name "$IDENTITY_NAME" \
--query '{clientId:clientId,principalId:principalId,tenantId:tenantId}' \
--output yaml

az identity federated-credential list \
--resource-group "$IDENTITY_RG" \
--identity-name "$IDENTITY_NAME" \
--query '[].{name:name,issuer:issuer,subject:subject,audiences:audiences}' \
--output yaml

The comparison is exact:

  • issuer: the current AKS OIDC issuer URL;
  • subject: system:serviceaccount:<namespace>:<service-account>;
  • audience: api://AzureADTokenExchange;
  • client ID: the identity annotated on the ServiceAccount and injected into the pod;
  • tenant: the tenant expected by the application and identity.

A namespace migration, service account rename, cluster recreation or identity recreation can break the mapping while leaving YAML and RBAC that look familiar. Repair only the mismatched contract. Do not broaden RBAC when token exchange has not succeeded.

Separate token exchange from target authorization

Use correlation IDs and UTC windows from the application error. Microsoft Entra sign-in evidence can show whether the federated principal obtained a token. Target diagnostics then establish whether the request arrived and why it was rejected.

Keep the status vocabulary precise:

  • no Entra attempt: the SDK, pod environment or projected file path failed before exchange;
  • failed Entra exchange: inspect issuer, subject, audience, tenant and identity;
  • successful Entra exchange, target 401: inspect requested resource audience, cached token use and target authentication logs;
  • successful exchange, target 403: inspect the effective principal, role, scope and data-plane permission;
  • target request absent: investigate network, DNS or application flow without relabeling it as an identity failure.

If the target is Key Vault, Storage or another service with data-plane RBAC, an ARM role may not authorize the data operation. Conversely, adding a data role cannot fix an assertion rejected by Microsoft Entra.

Canary one controlled correction

Prepare a dedicated canary Deployment using the same image digest, service account, node pool and target as production, with a single replica and no write capability. Its test should obtain a token through the normal SDK path, read one known resource and verify that an unauthorized resource remains denied.

yaml 05-workload-identity-canary-gates.yml
canary:
replicas: 1
image_digest_matches_production: true
service_account_matches_production: true
operation: read-known-key-vault-secret-metadata
write_operations: disabled

positive_gates:
- pod mutated with Azure environment and projected volume
- token file digest changes after kubelet refresh
- application continues succeeding after refresh
- Entra sign-in maps to expected principal
- target read succeeds with correlation evidence

negative_gates:
- unauthorized vault remains denied
- write operation remains denied
- deleting the candidate federation mapping breaks only the canary

promotion:
- two complete token refresh cycles pass
- no client secret is present
- old replicas can be replaced in bounded batches

Two complete refresh cycles matter. A canary that succeeds only at startup has not tested the reported failure mode. When the code change concerns token reload, compare the current and candidate image against the same federation contract. When the change concerns the federated credential, keep the image and RBAC fixed.

Decide, validate or roll back

Repair pod injection when the pod template lacks the required label, uses the wrong ServiceAccount or never received the projected volume. Roll out one replica, verify mutation and complete two refresh cycles before expanding.

Repair the federated credential when issuer, subject or audience differs from the current cluster and service account contract. Add the corrected credential to the same intended identity, canary it, then remove the obsolete mapping after the rollback window. Do not change the identity and Azure roles in the same step.

Update the application when the file rotates but the process continues using a stale assertion. Promote a credential implementation that rereads the file through its supported SDK behavior, then replace replicas in bounded batches. Increasing token lifetime is a temporary containment measure only when its owner, expiry and residual risk are explicit.

Roll back the application release when the previous image passes repeated refresh cycles under the same identity contract and the candidate does not. Roll back the identity change when the prior federation mapping remains valid and can be restored without widening access. Stop the rollout if the effective principal cannot be proven or the negative control unexpectedly succeeds.

Bringing back a client secret is justified only by an established emergency procedure with minimum scope, short expiration, named owner, secure delivery and verified deletion. It must not erase the evidence needed to repair workload identity.

Conclusion

AKS Workload Identity is not a single credential switch. It is a live chain from pod mutation and projected token rotation to application reload, federated claim matching and target authorization.

Preserve one failing replica, prove each gate in order and canary through at least two token refresh cycles. The production decision then becomes bounded: correct one contract, roll back one change, or hold the deployment. A cluster-wide restart or durable secret should never substitute for locating the failed gate.