AKS Hour 5: Automated Operations — IaC, GitOps and Pipelines
- Use Azure Verified Modules (AVM) to declare a production-baseline AKS cluster in both Bicep (
br/public:avm/res/container-service/managed-cluster:0.14.0) and Terraform (Azure/avm-res-containerservice-managedcluster/azurerm0.9.0), and explain the ARM calls behind what-if / plan. - Enable the Flux cluster extension (
microsoft.flux) and createfluxConfigurations. Be able to explain the full reconciliation chain: Azure resource → fluxconfig-agent → FluxConfig CR → GitRepository/Kustomization → source/kustomize-controller. Know when to use the Argo CD extension instead. - Design the cluster-side deployment permissions for GitHub Actions and Azure Pipelines: Workload Identity federation (OIDC), namespace-scoped Azure RBAC, kubelogin, private cluster access, and “push mode vs GitOps pull mode”. Tool details are covered in hour 3 of the GitHub and Azure DevOps courses and are not repeated here.
- Use update runs, stages, groups, approval gates and auto-upgrade profiles in Azure Kubernetes Fleet Manager to upgrade multiple clusters in stages.
- Provide namespace self-service from a platform engineering perspective: AKS managed namespaces (
az aks namespace add) deliver a ResourceQuota, default network policies and RBAC in one step. - Use Azure Backup for AKS (backup extension + Backup vault + Trusted Access) and Velero for cluster backup and restore. Understand the Operational and Vault tiers and the limits on cross-region restore.
- Write Azure Policy / Deployment Safeguards / Gatekeeper as code and ship it with the cluster. Understand the timing gaps between admission webhooks, audit scans and compliance reports.
1-Hour Timetable
| # | Time | Module | Core content | Animation / interactive | Lab |
|---|---|---|---|---|---|
| 0 | Before class | Setup: code repository and service connections | Reuse aks-lab, ACR and variables; prepare the GitOps repository and CLI extensions | Automation maturity self-assessment | Environment check |
| 1 | 00–06 | Bicep and Terraform (AVM) | AVM modules, parameter baseline, what-if/plan, state and drift, azapi | Bicep vs Terraform deployment call chain | Build aks-lab-bicep with AVM Bicep |
| 2 | 06–13 | GitOps: Flux extension and Argo CD | microsoft.flux, fluxConfigurations, Kustomization dependencies, prune, drift repair, Argo CD extension | Core animation: full Flux extension reconciliation flow | Flux deploys myapp to aks-lab |
| 3 | 13–21 | Pipeline deployment to AKS | OIDC federated credentials, namespace-scoped RBAC, kubelogin, private cluster, push vs pull | Pipeline tokens and authorization chain | Grant namespace permissions to the pipeline identity |
| 4 | 21–28 | Fleet Manager | Members, update groups, policies, stages, approval gates, maintenance windows, auto-upgrade profiles | Core animation: Fleet staged update run | Staged NodeImageOnly update across two clusters |
| 5 | 28–35 | Platform engineering: namespace self-service and quotas | Managed namespaces, ResourceQuota/LimitRange, default network policies, golden path | Quota admission calculator | Provision a managed namespace for team-a |
| 6 | 35–42 | Backup and restore | Azure Backup for AKS, Trusted Access, Operational/Vault tiers, Velero 1.18 | Backup and restore data flow | Back up the myapp namespace and restore it |
| 7 | 42–50 | Policy as code | Azure Policy add-on, Deployment Safeguards, Gatekeeper/VAP, compliance scanning | Admission decision simulator | Warn → Enforce drill |
| 8 | 50–60 | Summary of the first five hours, self-check and cleanup | Connecting the knowledge, cleanup order, cost review | Cleanup command generator + troubleshooting tree | Clean up in dependency order |
| — | After class | Cheat sheet · Capstone lab | End-to-end “cluster as code”: AVM → Flux → Fleet → backup → policy | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Declare AKS with AVM modules (Bicep / Terraform) | ✓ | · | · | · | ✓ | · | ✓ | ✓ | az deployment group what-if, terraform plan | aks-lab-bicep |
| GitOps reconciliation and drift repair | · | ✓ | ✓ | · | ✓ | · | · | ✓ | az k8s-configuration flux create/show | Flux deploys myapp |
| Pipeline securely accesses the cluster | · | · | ✓ | · | ✓ | · | · | · | az identity federated-credential create, kubelogin | Namespace-scoped authorization |
| Multi-cluster staged upgrade | · | · | · | ✓ | · | · | · | ✓ | az fleet updaterun create/start, az fleet gate approve | NodeImageOnly update run |
| Namespace self-service, quotas and isolation | · | ✓ | ✓ | · | ✓ | · | ✓ | · | az aks namespace add, kubectl describe quota | team-a |
| Backup and restore (Azure Backup / Velero) | · | · | · | · | · | ✓ | · | ✓ | az dataprotection …, velero backup create | myapp backup and restore |
| Policy as code and compliance | ✓ | · | ✓ | · | ✓ | · | ✓ | ✓ | az aks safeguards create, az policy assignment create | Warn → Enforce |
| Cost and cleanup | ✓ | · | · | ✓ | · | ✓ | · | ✓ | az group delete, az aks stop | Clean up by dependency |
What this hour does not cover (and where to learn it)
| Topic | Why it is not in this hour | Where to learn it |
|---|---|---|
| General Kubernetes GitOps concepts, native Argo CD/Flux installation and ApplicationSet | The concepts get a quick overview in hour 6 of the K8s course. Native installation and ApplicationSet are covered in depth in the GitOps and Argo CD course. This hour covers only the AKS managed extensions. | K8s Hour 6, Module 1 · GitOps and Argo CD, 8 hours |
| GitHub Actions / Azure Pipelines syntax, building images, environments and approvals | Tool details are already covered in the relevant courses | GitHub Hour 3 · Azure DevOps Hour 3 |
| Writing Helm charts, HelmRelease details, Helm + GitOps | Covered in the Helm course | Helm Hour 3 (Azure) |
| Terraform language, state backends, module authoring | Covered in the Terraform course; this hour only uses AVM modules | Terraform Hour 3 (Azure) |
| Velero internals and general CSI snapshot details | Covered in the K8s course; this hour focuses on Azure integration | K8s Hour 4: Storage |
| Node pool surge upgrade mechanics, PDBs and drain | Covered in upgrades and operations | AKS Hour 6 |
| Managed Prometheus / Grafana alerts | Covered in the observability course | Prometheus & Grafana Hour 3 |
How to use this course material
Principles · Diagrams · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. This hour has two core animations, in module 2 (Flux reconciliation) and module 4 (Fleet staged updates). Watch the animations before doing the labs.
A module counts toward your progress when your quiz score is ≥ 70% or you click “Mark this module complete”. Progress is saved in this browser (if local storage is blocked, it is cleared on refresh).
The “Voice” tab reads the lecture script aloud using the browser's built-in Web Speech API (en-US). If no English voice pack is installed, read the page directly or pass the script to a TTS tool.
az aks get-versions, and patch numbers are never hard-coded. The latest Bicep AVM module is 0.14.0 (MCR tag list). The latest Terraform AVM module is 0.9.0 (released 2026-11-04; requires Terraform ≥ 1.11 and azapi ~> 2.12). The latest microsoft.flux is 1.26.4 (based on Flux v2.9.6). This hour also creates an extra single-node cluster aks-lab-bicep, a Fleet without a hub, a Backup vault and a storage account. Completing everything takes about 1.5 hours. The extra cost is on the order of “one D4-class node plus a small amount of storage and snapshots”. Check the Azure pricing calculator for exact figures, and clean up in order in module 8.Module 0 · Setup: code repository and service connections (complete before class)
aks-lab, ACR and variables from the first four hours. Prepare a GitOps repository, the CLI extensions and the resource providers.- Completed hours 1–4: resource group
rg-aks-lab(canadacentral) contains the clusteraks-lab(managed identity, OIDC issuer and Workload Identity enabled, see hour 3), and ACRacraks<suffix>already hasmyapp:1.0andmyapp:1.1. - On your machine or in Cloud Shell: Azure CLI ≥ 2.82.0 (required by the Fleet quickstart), kubectl, kubelogin and Git. Optional: Terraform ≥ 1.11 (for the Terraform variant in module 1) and Velero CLI 1.18 (for the Velero variant in module 6).
- A GitHub account you can push to (for the GitOps repository). A public repository is simplest. For a private repository, see the authentication notes in module 2.
- Azure roles: on
rg-aks-lab, you need at least Contributor. Modules 3 and 6 create role assignments, so you also need User Access Administrator (or Owner). The policy assignments in module 7 require Resource Policy Contributor.
Step 1: Set common variables (same as the first four hours)
RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab
SUB=$(az account show --query id -o tsv)
ACR=$(az acr list -g $RG --query "[0].name" -o tsv) # acraks<suffix>; in hour 1 it was created with ACR=acraks$RANDOM
AKS_ID=$(az aks show -g $RG -n $CLUSTER --query id -o tsv)
echo "SUB=$SUB ACR=$ACR"
az aks show -g $RG -n $CLUSTER --query "{state:powerState.code, k8s:currentKubernetesVersion, oidc:oidcIssuerProfile.enabled, wi:securityProfile.workloadIdentity.enabled, aadRbac:aadProfile.enableAzureRbac}" -o table
SUB=00000000-0000-0000-0000-000000000000 ACR=acraks12345 State K8s Oidc Wi AadRbac ------- ------ ------ ------ --------- Running 1.36.x True True True
az aks stop at the end of the last hour, first run az aks start -g $RG -n $CLUSTER (about 5–10 minutes). If the whole resource group was deleted, rebuild aks-lab and ACR using the “rebuild” steps from hour 1, then come back and continue.Step 2: Register resource providers and CLI extensions
for ns in Microsoft.KubernetesConfiguration Microsoft.ContainerService Microsoft.DataProtection Microsoft.PolicyInsights; do
az provider register --namespace $ns
done
az provider show -n Microsoft.KubernetesConfiguration --query registrationState -o tsv # wait for Registered (usually < 10 minutes)
az extension add --upgrade -n k8s-configuration # az k8s-configuration flux …
az extension add --upgrade -n k8s-extension # az k8s-extension … (Flux/Argo CD/backup extensions)
az extension add --upgrade -n fleet # az fleet … (quickstart requires ≥ 1.8.3)
az extension add --upgrade -n dataprotection # az dataprotection … (enable-backup requires ≥ 1.9.0)
az extension list --query "[?contains('k8s-configuration k8s-extension fleet dataprotection', name)].{name:name,version:version}" -o table
Name Version ----------------- --------- dataprotection 1.x.x fleet 1.x.x k8s-configuration 2.x.x k8s-extension 1.x.x
Step 3: Create the GitOps repository skeleton
The GitOps repository for this hour is named aks-gitops. It uses a two-layer structure, “infrastructure before apps”, which matches the two dependent Kustomizations in module 2 (infra → apps).
mkdir aks-gitops && cd aks-gitops && git init -b main
mkdir -p infrastructure apps/myapp
cat > infrastructure/namespace.yaml <<'EOF'
apiVersion: v1
kind: Namespace
metadata:
name: myapp
labels:
app.kubernetes.io/managed-by: flux
EOF
cat > infrastructure/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- namespace.yaml
EOF
git add . && git commit -m "infra: myapp namespace"
# After you create the empty aks-gitops repository on GitHub:
git remote add origin https://github.com/<your-account>/aks-gitops.git
git push -u origin main
The application manifests (myapp + redis) are added in the module 2 lab. Keeping the repository public lets Flux pull without credentials. In production, use a private repository with Workload Identity or a GitHub App (see the module 2 troubleshooting).
Connecting from the previous hour
- Cluster Autoscaler / NAP configuration: module 1 writes these manual switches into AVM parameters.
- myapp requests/limits: the quota calculations in module 5 depend on them.
- Fleet update runs only control the order. The node surge upgrade and cordon/drain mechanics inside each cluster are covered in hour 6.
- Maintenance windows (
aksManagedAutoUpgradeSchedule) appear in this hour as a Fleet constraint. Configuration details are in hour 6.
Warm-up: automation maturity self-assessment (10 items)
Check the items your team already does today (results are saved in this browser). Come back and check again after finishing this hour.
Module 1 · Build AKS with Bicep and Terraform (AVM)
- Explain the two kinds of AVM modules, resource (
res) and pattern (ptn), plus the versioning rules and sources: Bicep comes from the public registrybr/public:avm/res/container-service/managed-cluster(MCR), and Terraform comes from the Terraform RegistryAzure/avm-res-containerservice-managedcluster/azurerm(built on the azapi provider). - Write the production baseline parameters: Entra + Azure RBAC, local accounts disabled, OIDC + Workload Identity, Azure CNI Overlay + Cilium, the Azure Policy add-on, and cluster auto-upgrade turned off when Fleet manages upgrades.
- Explain the difference between the ARM calls behind
what-ifandterraform plan, and what state, drift and “plan before apply” mean for cluster-level changes.
az aks create from hour 1; hour 3 of the Terraform course. Importance: ★★★★★ (the starting point for all later automation)What: what Azure Verified Modules are
Azure Verified Modules (AVM) is Microsoft's official IaC module library. The same standards produce both Bicep and Terraform versions. Resource modules (res) wrap a single resource and its surrounding pieces (diagnostic settings, locks, role assignments, private endpoints). Pattern modules (ptn) combine several resources into a scenario. This hour uses the resource module managed-cluster. It directly exposes most properties of Microsoft.ContainerService/managedClusters@2025-10-01 and provides a consistent interface for lock, roleAssignments, diagnosticSettings, enableTelemetry and similar.
- Bicep:
br/public:avm/res/container-service/managed-cluster:0.14.0. As of 2026-11-15, the highest version in the MCR tag list is 0.14.0. The module is stored as an OCI artifact atmcr.microsoft.com/bicep/...and downloaded to the local cache duringbicep restore. - Terraform:
Azure/avm-res-containerservice-managedcluster/azurerm0.9.0 (2026-11-04). Note that it depends only on the azapi provider (~> 2.12) and random, and requires Terraform>= 1.11, < 2.0. Inputs useparent_id(the resource group ID) instead ofresource_group_name. The default node pool variable isdefault_agent_pool(default name systempool, 3 nodes).
Why: why not just write az aks create or hand-write resources
- Repeatable: the same parameters produce consistent clusters in dev, staging and prod, which is what makes Fleet's “canary first” approach work (module 4).
- Reviewable: cluster-level changes (network plugin, identity, API server access) go through pull requests and are reviewed using the what-if / plan output.
- Secure defaults: the AVM Bicep module defaults to
disableLocalAccounts = true,publicNetworkAccess = 'Disabled',skuTier = 'Standard',azurePolicyEnabled = trueandautoUpgradeProfile.upgradeChannel = 'stable'. These defaults favor production, so for labs you must explicitly override them (for example, this hour setspublicNetworkAccesstoEnabledand the tier to Free). - Ongoing maintenance: the module tracks new API versions. You only need to bump the module version and read the CHANGELOG.
How: two deployment paths
| Stage | Bicep | Terraform (AVM, azapi) |
|---|---|---|
| Get the module | bicep restore pulls the OCI artifact from MCR | terraform init downloads the module and the azapi provider from the Registry |
| Compile | Compiled locally to ARM JSON (the module becomes a nested deployment) | No compile step; HCL is evaluated into the JSON body for azapi resources |
| Preview | az deployment group what-if: ARM expands the template server-side and compares it with the current state | terraform plan: the provider GETs each resource and compares it with state and configuration |
| Execute | PUT Microsoft.Resources/deployments; ARM orchestrates dependencies and concurrency | The provider PUTs resources directly (through ARM); Terraform handles concurrency itself based on the dependency graph |
| Long-running operations | ARM polls the AKS RP's Azure-AsyncOperation | azapi polls the same Azure-AsyncOperation header |
| Status | No local state; the “source of truth” is in Azure (deployment history + the resources themselves) | terraform.tfstate (should live in an Azure Storage backend with locking) |
| Delete | Removing a resource from the template does not delete it (incremental mode). Use Deployment Stacks to manage the lifecycle. | Removing it from the configuration → plan shows destroy |
When: which one to choose
- If the team is Azure-first, wants zero state management, and needs deep integration with Azure Policy and Deployment Stacks → Bicep.
- If you are multi-cloud or already have a Terraform platform (remote state, Sentinel/OPA, module registry) → Terraform AVM.
- Either way: use IaC for the cluster, and let GitOps handle what runs inside the cluster (module 2). Do not use Terraform's kubernetes or helm providers to deploy applications. That ties cluster credentials and the application lifecycle to infrastructure state.
Comparison with similar approaches
| AVM module | Hand-written resources | azurerm_kubernetes_cluster (Terraform) | az aks create script | |
|---|---|---|---|---|
| New API features | Module follows along (per release) | You follow along yourself | Wait for provider support | CLI version follow-up |
| Preview changes | what-if / plan | what-if / plan | plan | None |
| Surrounding resources (locks, diagnostics, RBAC) | Consistent interface | Write it yourself | Extra resources | Extra commands |
| Best for | Standardized platform | Rare, special requirements | Existing azurerm estate | Experiments, one-off |
default_agent_pool, aad_profile, network_profile).Architecture diagram: IaC repository → ARM → AKS resource provider
managedClusters resource. The difference is who orchestrates dependencies and who stores state.Flowchart: review process for a cluster baseline change
Step-by-step animation: Bicep and Terraform deployment call chains
Choose a path, then click “Play” or “Next”. Each step highlights the current component. The log below shows the real commands, HTTP calls or state writes for that step (output is sample).
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az bicep upgrade / az bicep version | Update the Bicep CLI (latest as of 2026-11: v0.49.2) | An older version may not recognize new syntax in the module (such as the resourceInput<> type) |
az bicep restore -f main.bicep | Download br/public: modules to the local cache | Offline CI can run restore first, then build |
az deployment group what-if | Preview changes server-side | --result-format FullResourcePayloads (default) / ResourceIdOnly; --exclude-change-types NoChange Ignore |
az deployment group create | Deploy to a resource group | --template-file, --parameters, --name (deployment name, for tracking) |
az aks get-versions -l $LOC | Query versions available in a region | Use JMESPath to get the N-1 minor version, avoiding hard-coded patch numbers |
terraform init / plan -out / apply | Terraform AVM path | plan -out tfplan, then apply tfplan, so you apply exactly the plan you reviewed |
terraform plan -refresh-only | Drift detection only | Changes nothing; only compares actual Azure values with state |
Minimum viable production baseline (Bicep, AVM 0.14.0)
targetScope = 'resourceGroup'
@description('Cluster name, following the aks-lab-<topic> convention')
param clusterName string = 'aks-lab-bicep'
param location string = resourceGroup().location
@description('Kubernetes minor version, for example 1.36 (AKS picks the latest patch automatically)')
param kubernetesVersion string
module aks 'br/public:avm/res/container-service/managed-cluster:0.14.0' = {
name: 'avm-${clusterName}'
params: {
name: clusterName
location: location
kubernetesVersion: kubernetesVersion
skuTier: 'Free' // Module default is Standard; use Free for labs, Standard/Premium for production
publicNetworkAccess: 'Enabled' // Module default is Disabled! Labs need public access to the API server
managedIdentities: { systemAssigned: true }
// Identity: Entra + Azure RBAC, local admin accounts disabled (module default disableLocalAccounts = true)
aadProfile: { managed: true, enableAzureRBAC: true }
disableLocalAccounts: true
enableOidcIssuerProfile: true
securityProfile: { workloadIdentity: { enabled: true } }
// Network: Overlay + Cilium, same as hour 2; the address plan follows the course convention
networkPlugin: 'azure'
networkPluginMode: 'overlay'
networkDataplane: 'cilium'
networkPolicy: 'cilium'
podCidr: '192.168.0.0/16'
serviceCidr: '10.0.0.0/16'
dnsServiceIP: '10.0.0.10'
primaryAgentPoolProfiles: [
{
name: 'system'
mode: 'System'
count: 1
vmSize: 'Standard_D4ds_v5'
osSKU: 'AzureLinux'
}
]
// Fleet (module 4) orchestrates upgrades: turn off the cluster's own Kubernetes auto-upgrade and keep the node image channel
autoUpgradeProfile: { upgradeChannel: 'none', nodeOSUpgradeChannel: 'NodeImage' }
azurePolicyEnabled: true // Module 7's Deployment Safeguards depend on this
omsAgentEnabled: false // Module default is true; this lab does not connect Log Analytics
tags: { course: 'aks-8h', hour: '5' }
}
}
output clusterId string = aks.outputs.resourceId
output oidcIssuerUrl string = aks.outputs.oidcIssuerUrl ?? '' // Module output type is string? (nullable)
How to verify: az bicep build -f main.bicep runs with no errors (it downloads the module first). what-if should show 1 Create. Common mistakes: forgetting to override publicNetworkAccess, so kubectl cannot connect; or, after setting disableLocalAccounts: true without an Entra admin group, finding no admin to sign in as. This hour uses an Azure RBAC role to grant access to yourself (see the lab). Production use: add skuTier, apiServerAccessProfile, maintenanceConfigurations and diagnosticSettings to the environment parameter file.
The same baseline in Terraform (AVM 0.9.0, azapi)
terraform {
required_version = ">= 1.11, < 2.0"
required_providers {
azapi = { source = "Azure/azapi", version = "~> 2.12" }
}
# backend "azurerm" { ... } # production: remote state + locking, see hour 3 of the Terraform course
}
provider "azapi" {}
data "azapi_client_config" "current" {}
variable "kubernetes_version" { type = string }
module "aks" {
source = "Azure/avm-res-containerservice-managedcluster/azurerm"
version = "0.9.0"
name = "aks-lab-tf"
location = "canadacentral"
parent_id = "/subscriptions/${data.azapi_client_config.current.subscription_id}/resourceGroups/rg-aks-lab"
kubernetes_version = var.kubernetes_version
sku = { name = "Base", tier = "Free" }
aad_profile = { managed = true, enable_azure_rbac = true }
disable_local_accounts = true
oidc_issuer_profile = { enabled = true }
security_profile = { workload_identity = { enabled = true } }
network_profile = {
network_plugin = "azure"
network_plugin_mode = "overlay"
network_dataplane = "cilium"
network_policy = "cilium"
pod_cidr = "192.168.0.0/16"
service_cidr = "10.0.0.0/16"
dns_service_ip = "10.0.0.10"
}
default_agent_pool = {
name = "system"
count_of = 1
vm_size = "Standard_D4ds_v5"
os_sku = "AzureLinux"
}
auto_upgrade_profile = { upgrade_channel = "none", node_os_upgrade_channel = "NodeImage" }
addon_profile_azure_policy = { enabled = true }
}
output "oidc_issuer_url" { value = module.aks.oidc_issuer_profile_issuer_url }
Variable names were checked against the module repository's variables.tf (default_agent_pool.count_of defaults to 3, name defaults to systempool; sku.tier accepts Free/Standard/Premium; auto_upgrade_profile.upgrade_channel accepts node-image/none/patch/rapid/stable). Before upgrading the module version, always read the CHANGELOG: between 0.x versions, there may be breaking renames.
How to read what-if / plan
K8S_PREV=$(az aks get-versions -l $LOC --query "sort_by(values[?isPreview!=\`true\`], &version)[-2].version" -o tsv) echo $K8S_PREV # for example 1.36 (N-1, leaving room for the upgrade demo in module 4) az deployment group what-if -g $RG -f main.bicep -p kubernetesVersion=$K8S_PREV --exclude-change-types NoChange Ignore
Resource and property changes are indicated with these symbols:
+ Create
The deployment will update the following scope:
Scope: /subscriptions/…/resourceGroups/rg-aks-lab
+ Microsoft.ContainerService/managedClusters/aks-lab-bicep [2025-10-01]
apiVersion: "2025-10-01"
location: "canadacentral"
properties.aadProfile.enableAzureRBAC: true
properties.disableLocalAccounts: true
properties.networkProfile.networkPluginMode: "overlay"
…
Resource changes: 1 to create.
The AVM module also creates an empty telemetry deployment by default (enableTelemetry, default true). It does not create billable resources. If your organization does not allow it, set it to false.
Lab 1: create aks-lab-bicep with AVM Bicep (about 8–10 minutes, mostly waiting)
Standard_D4ds_v5 node (the Free-tier control plane is not charged) plus managed disks and a Standard Load Balancer. Billed hourly; deleted in module 8. Requires Contributor on the resource group. Granting yourself a cluster RBAC role requires User Access Administrator or Owner. Risk: after disableLocalAccounts, only Entra identities can access the cluster.platform-iac/main.bicep.
mkdir -p platform-iac && cd platform-iac # after pasting main.bicep: az bicep version az bicep build -f main.bicep --stdout | head -5
Bicep CLI version 0.49.2 (…)
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"languageVersion": "2.0",
"contentVersion": "1.0.0.0",K8S_PREV=$(az aks get-versions -l $LOC --query "sort_by(values[?isPreview!=\`true\`], &version)[-2].version" -o tsv) az deployment group what-if -g $RG -f main.bicep -p kubernetesVersion=$K8S_PREV --exclude-change-types NoChange Ignore az deployment group create -g $RG -n avm-aks-lab-bicep -f main.bicep -p kubernetesVersion=$K8S_PREV --query properties.provisioningState -o tsv
Succeeded
--admin credentials are not available:
BICEP_ID=$(az aks show -g $RG -n aks-lab-bicep --query id -o tsv) ME=$(az ad signed-in-user show --query id -o tsv) az role assignment create --assignee-object-id $ME --assignee-principal-type User \ --role "Azure Kubernetes Service RBAC Cluster Admin" --scope $BICEP_ID az aks get-credentials -g $RG -n aks-lab-bicep --overwrite-existing kubelogin convert-kubeconfig -l azurecli kubectl get nodes -o wide
NAME STATUS ROLES AGE VERSION aks-system-12345678-vmss000000 Ready <none> 6m v1.36.x
The role assignment may take 1–2 minutes to take effect. Until then, you will see Forbidden.
az aks update -g $RG -n aks-lab-bicep --auto-upgrade-channel patch az deployment group what-if -g $RG -f main.bicep -p kubernetesVersion=$K8S_PREV --exclude-change-types NoChange Ignore
~ Microsoft.ContainerService/managedClusters/aks-lab-bicep [2025-10-01]
~ properties.autoUpgradeProfile.upgradeChannel: "patch" => "none"
what-if shows that the code will change it back to none. Run az deployment group create … again to fix the drift by making the code the source of truth.
mkdir ../platform-iac-tf && cd ../platform-iac-tf # paste main.tf terraform init terraform plan -var kubernetes_version=$K8S_PREV -out tfplan | tail -5
Plan: 2 to add, 0 to change, 0 to destroy. Saved the plan to: tfplan
The resource count includes the AKS cluster and the module's internal telemetry and helper resources. The actual number depends on the plan.
aks-lab-bicep is still needed in module 4 as a Fleet “canary” member, so keep it for now. Delete everything together in module 8:az aks delete -g $RG -n aks-lab-bicep --yes --no-wait # run in module 8 rm -rf ../platform-iac-tf/.terraform ../platform-iac-tf/tfplan
Case 1: 30 clusters, each set up its own way
Problem: different teams created 30 AKS clusters through the portal and scripts. Network plugins, outbound types, local accounts and upgrade channels all differ. During an audit, nobody can answer “which clusters still allow local admin?” Approach: the platform team defines baseline.bicep with the AVM Bicep module and provides a .bicepparam file per environment. For existing clusters, write the parameters by importing their current state so that what-if shows NoChange, then gradually close the differences. Configuration: disableLocalAccounts: true and aadProfile.enableAzureRBAC: true are non-negotiable. Pair them with the Azure Policy audit “Kubernetes clusters should disable local authentication methods”. Limits: network plugins, Pod CIDRs and similar settings cannot be changed in place. You can only create a new cluster and migrate (see the Fleet work in module 4 and the backup migration in module 6).
Case 2: cluster credentials stored in Terraform state
Problem: a team outputs kube_config in Terraform and deploys apps with the kubernetes provider. The state file contains credentials that give direct access to the cluster, and every application change requires locking the infrastructure state. Approach: Terraform manages only the cluster and its surrounding resources. Applications are handed to Flux (module 2). Disabling local accounts means static credentials no longer exist. Enable encryption, versioning and RBAC on the state backend. Limits: the AVM module still provides kube_config/kube_admin_config outputs, so do not reference them in the root module.
Case 3: an “accidental rebuild” caused by a module upgrade
Problem: after upgrading the AVM module from 0.x to the next minor version, the plan shows the node pool being replaced. Approach: in CI, open a separate PR for module version upgrades. If the plan shows -/+ (Terraform) or a node pool delete/create, flag it in red and block the merge automatically. Read the CHANGELOG to confirm whether it is a field rename or a default value change. Limits: 0.x versions follow AVM's versioning conventions, so a minor upgrade can still include breaking changes. Production should pin an exact version.
Common errors and fixes
Unable to restore the artifact with reference "br:mcr.microsoft.com/bicep/avm/res/container-service/managed-cluster:0.14.0"
Cause: cannot reach MCR (proxy or firewall), a typo in the version number, or an outdated Bicep CLI.
az bicep version curl -s https://mcr.microsoft.com/v2/bicep/avm/res/container-service/managed-cluster/tags/list | head -c 300
Fix: az bicep upgrade; allow mcr.microsoft.com and *.data.mcr.microsoft.com; check version numbers against the tag list.
Unable to connect to the server: dial tcp: lookup aks-lab-bicep-xxxx.hcp.canadacentral.azmk8s.io: no such host (or connection timeout)
Cause: the AVM module defaults to publicNetworkAccess = 'Disabled', or a private cluster is enabled.
az aks show -g $RG -n aks-lab-bicep --query "{pna:publicNetworkAccess, private:apiServerAccessProfile.enablePrivateCluster}"
Fix: in the lab, explicitly set publicNetworkAccess: 'Enabled' and redeploy. For a production private cluster, use a jump box, a self-hosted runner, or az aks command invoke (module 3).
Error from server (Forbidden): nodes is forbidden: User "…" cannot list resource "nodes" … (Azure RBAC)
Cause: Azure RBAC is enabled and local accounts are disabled, but the current user does not have a cluster data-plane role.
az role assignment list --scope $BICEP_ID --query "[].{role:roleDefinitionName,who:principalName}" -o table
Fix: assign one of “Azure Kubernetes Service RBAC Cluster Admin / Admin / Writer / Reader”, wait for it to propagate, and confirm that kubeconfig was converted with kubelogin convert-kubeconfig -l azurecli.
OperationNotAllowed: Changing property 'networkPlugin' is not allowed / podCidr cannot be changed
Cause: you changed an immutable network property. what-if does not tell you whether a change can be made in place.
Fix: revert that parameter. If you need to change the network model, create a new cluster (with a new name), redeploy the apps with GitOps, migrate stateful data with backup, then switch traffic. Some migrations (such as kubenet → Overlay) have official in-place upgrade paths. Follow the hour 2 content and the official docs.
Error: Unsupported argument "resource_group_name" / An argument named "default_node_pool" is not expected here
Cause: you used azurerm_kubernetes_cluster parameter names on the AVM module.
Fix: AVM 0.9.0 uses ARM-style names such as parent_id, default_agent_pool, aad_profile and network_profile. Check the module README's Inputs section.
1. Without hard-coding a patch number, get the second-newest non-preview Kubernetes minor version available in the current region.
az aks get-versions -l canadacentral --query "sort_by(values[?isPreview!=\`true\`], &version)[-2].version" -o tsv
2. Show only the resources that will be modified, created or deleted, ignore unchanged items, and preview the deployment of main.bicep.
az deployment group what-if -g rg-aks-lab -f main.bicep -p kubernetesVersion=1.36 --exclude-change-types NoChange Ignore
Your team wants to bring 30 existing clusters under AVM management, but is worried the first deployment will “break” them. What would you do?
For each cluster, write parameters that match its current state (export the key fields with az aks show). Run what-if repeatedly until only acceptable noise remains. Roll out in batches by environment (dev → staging → prod), and confirm the maintenance window and PDBs before each batch. Do not force immutable differences (network plugin, CIDR) into code. Record them as “migration items” instead. Use Azure Policy to audit key settings that do not match the code. For the Terraform path, first import and then make sure the plan shows zero changes.
Verified teaching videos
Official docs
- Azure Verified Modules home page
- Bicep module source: avm/res/container-service/managed-cluster
- Terraform Registry: avm-res-containerservice-managedcluster
- ARM/Bicep what-if
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
Visual: 30 cluster icons of different shapes, labeled “made in the portal”.
Narration: Clusters without code are each snowflakes. Auditing, upgrading and migrating them turns into archaeology.
Visual: a main.bicep file references a br/public module, with an arrow pointing to MCR.
Narration: Azure Verified Modules is a module library maintained by Microsoft. Bicep pulls modules from a container registry, Terraform downloads them from a module registry, and the version number is your contract.
Visual: on the left, Bicep goes through the deployment engine; on the right, Terraform calls the resource API directly; the two lines meet at the AKS resource provider.
Narration: both paths end with one PUT to the managed cluster resource. The difference is who orchestrates the dependencies and who stores the state.
Visual: a PR page with what-if results pasted in; a red box highlights the network plugin field.
Narration: put the preview results into code review. When you see changes to networking, identity or API server access, stop and think.
Module 2 · GitOps: Flux extension and Argo CD
- Distinguish three layers of objects: the Azure resource
Microsoft.KubernetesConfiguration/extensions(microsoft.flux) andfluxConfigurations; the in-cluster Azure CRDFluxConfig(fluxconfigs.clusterconfig.azure.com); and the upstream Flux CRDsGitRepository,KustomizationandHelmRelease. - Use
az k8s-configuration flux createto create two layers of Kustomizations withdependsOnandprune. Trace fromcomplianceStateall the way down to specific controller logs. - Explain drift repair, prune deletion, the polling interval and the delay between a Git commit and its effect on the cluster. Know when to choose the Argo CD extension.
What: “managed Flux” on AKS
GitOps treats Git as the single source of truth for the desired state of the cluster. Controllers inside the cluster pull from it and continuously reconcile. On AKS, Flux v2 is provided as a cluster extension. After you install the microsoft.flux extension, you create one or more fluxConfigurations resources in Azure. They are synced to the cluster and drive the Flux controllers.
| Layer | Object | Who creates / who consumes |
|---|---|---|
| Azure resource | extensions/flux (type microsoft.flux) | You create it (CLI/Bicep/Policy). The extension manager installs the Flux components into flux-system in the cluster using Helm. |
| Azure resource | fluxConfigurations/cluster-config | You create it. fluxconfig-agent retrieves it from the regional data plane <region>.dp.kubernetesconfiguration.azure.com and writes it into the cluster. |
| Cluster CRD (Azure) | FluxConfig (fluxconfigs.clusterconfig.azure.com) | Written by fluxconfig-agent; fluxconfig-controller reads it and generates the upstream Flux objects |
| Cluster CRD (upstream Flux) | GitRepository, Kustomization (and optionally HelmRelease, OCIRepository, Bucket) | source-controller pulls Git and produces artifacts; kustomize-controller builds them and applies them with server-side apply |
| Status reporting | complianceState, statuses[] | fluxconfig-agent aggregates the Ready conditions of the Flux objects and reports them to Azure. Visible in az k8s-configuration flux show and in the portal. |
The default upstream controllers are source / kustomize / helm / notification. image-automation-controller and image-reflector-controller need the extension configuration image-automation-controller.enabled=true image-reflector-controller.enabled=true to be enabled. In 2026-10, microsoft.flux 1.26.2 upgraded the upstream to Flux v2.9.6, and 1.26.4 is the security fix release. The extension supports “the latest version and the previous two versions (N-2)”. Since 1.25.0 (Flux v2.8), helm-controller uses Helm v4 default behavior (server-side apply, kstatus health checks). You can restore the old behavior with useHelm3Defaults.
Why: why use the extension instead of flux bootstrap
- Azure-native lifecycle: extension versions, configuration and deletion are all ARM resources. They can be managed with Bicep/Terraform (
Microsoft.KubernetesConfiguration/fluxConfigurations) and Azure Policy (to roll out GitOps configuration at scale). The AVM cluster module also has afluxExtensionparameter. - Compliance visibility: each configuration's
complianceStatecan be queried in the portal and in Resource Graph, which suits dozens or hundreds of clusters. - Integration with AKS identity: supports Workload Identity (
workloadIdentity.enable=true) and pulling from ACR with the kubelet identity (useKubeletIdentity=true). - Trade-offs: it can only be installed cluster-wide in
flux-system. The Flux version is determined by the extension, so you cannot simply track the latest upstream release. The cluster must use a managed identity (MSI). Service principal (SPN) clusters are not supported.
How: what happens during one reconciliation
az k8s-configuration flux create→ ARM PUTfluxConfigurations(if the extension does not exist, an extension namedfluxis installed automatically first).- fluxconfig-agent pulls the configuration from the regional data plane over outbound HTTPS, and creates a
FluxConfigin--namespace(cluster-configin this hour). - fluxconfig-controller expands it into
GitRepository/cluster-configand severalKustomization/cluster-config-<name>objects. - source-controller clones the repository at each
interval, creates a tar.gz artifact, and writesmain@sha1:…tostatus.artifact.revision. - kustomize-controller detects the new artifact →
kustomize build→ server-side apply (with dry-run and diff) → executesprunebased on the inventory → health check → updates the Ready condition.dependsOnmakesappswait forinfrato be Ready. - Even if there are no new commits in Git, kustomize-controller reapplies at each interval and reverts manual changes (drift).
- fluxconfig-agent reports the status as
complianceState: Compliant.
When: Flux extension or Argo CD extension
| Flux extension (microsoft.flux) | Argo CD extension (Microsoft.ArgoCD) | Self-installed Flux / Argo CD | |
|---|---|---|---|
| Status | GA (AKS and Arc) | Tutorial note (2026-09): GA on AKS, preview on Arc. The extension list page and the portal entry still show “Preview,” so check the docs at the time before enabling it in production. | Community support |
| Configuration entry point | ARM fluxConfigurations | Extension settings (community Helm chart values); you cannot edit the Argo CD ConfigMap directly | Fully self-managed |
| UI | No UI (the portal shows compliance state) | Argo CD UI, can connect to Entra SSO | Optional |
| Resource needs | Light | Default HA, needs ≥ 4 nodes; for a single node, add redis-ha.enabled=false | Custom |
| Best for | Platform baselines, large-scale rollouts, “hands-off automation with no UI” | App teams that need visual sync/rollback and are used to ApplicationSets | Need the latest upstream version or special plugins |
flux reconcile. ② “If flux show says Compliant, the app is healthy.” Compliant only means the Flux objects are Ready. If the Kustomization has no health checks (wait/healthChecks), a Deployment stuck in ImagePullBackOff can still show Ready. ③ “Deleting fluxConfiguration only stops syncing.” With prune=true, deleting the configuration also deletes the objects it deployed. ④ “You can kubectl edit the Kustomization that Flux generated.” It is managed by fluxconfig-controller and will be overwritten. Change the Azure resource instead.Architecture diagram: Azure control plane, in-cluster controllers, and Git
Flowchart: timeline from a Git commit to a Pod update
Core animation: full Flux extension reconciliation flow (including drift correction and prune)
Pick a scenario, then press “Play” or step through it. The highlighted box is the component currently working. The status table on the right shows changes to Git, the artifact, the cluster, and Azure compliance state. The log shows the command output, events, or API calls you would see in a real environment (sample values).
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az k8s-extension create --extension-type microsoft.flux | Install the Flux extension separately (optional; the create command installs it automatically when needed) | -t managedClusters, --name flux, --config useKubeletIdentity=true / workloadIdentity.enable=true / image-automation-controller.enabled=true |
az k8s-configuration flux create | Create a fluxConfiguration | -n configuration name, --namespace, --scope cluster|namespace, -u repository, --branch, multiple --kustomization name= path= prune= dependsOn= |
az k8s-configuration flux show / list | Check compliance state | --query "{state:complianceState, statuses:statuses[].{kind:kind,name:name,state:complianceState}}" |
az k8s-configuration flux kustomization update | Modify a Kustomization | For example, change path, prune, or sync interval |
az k8s-configuration flux delete | Delete the configuration (also deletes its objects when prune=true) | --yes; delete the configuration before the extension |
kubectl get fluxconfigs,gitrepositories,kustomizations -A | Three layers of objects in the cluster | The READY / STATUS columns show the failure reason directly |
flux reconcile … (optional, flux CLI) | Trigger reconciliation now | Fine for read-only or triggering purposes; do not use flux bootstrap to overwrite the extension install |
az k8s-configuration flux create -g $RG -c $CLUSTER -t managedClusters \ -n cluster-config --namespace cluster-config --scope cluster \ -u https://github.com/<your-account>/aks-gitops --branch main \ --kustomization name=infra path=./infrastructure prune=true \ --kustomization name=apps path=./apps/myapp prune=true dependsOn=\["infra"\]
az k8s-configuration flux show -g $RG -c $CLUSTER -t managedClusters -n cluster-config \
--query "{state:complianceState, prov:provisioningState, statuses:statuses[].{kind:kind,name:name,state:complianceState}}" -o json
{
"prov": "Succeeded",
"state": "Compliant",
"statuses": [
{ "kind": "GitRepository", "name": "cluster-config", "state": "Compliant" },
{ "kind": "Kustomization", "name": "cluster-config-infra", "state": "Compliant" },
{ "kind": "Kustomization", "name": "cluster-config-apps", "state": "Compliant" }
]
}
How to verify: right after the first create, the status may be Pending or Non-Compliant (reconciliation has not finished yet). Check again in about 1 minute. Common errors: forgetting --branch main (the CLI default branch is master); the square brackets in dependsOn need escaping in bash; the path does not start with ./; the repository is private but no credentials were provided. Production use: write the same configuration in Bicep (Microsoft.KubernetesConfiguration/fluxConfigurations), or roll it out to a group of clusters with Azure Policy.
kubectl get pods -n flux-system kubectl get fluxconfigs,gitrepositories,kustomizations -n cluster-config
NAME READY STATUS RESTARTS AGE fluxconfig-agent-7c9d8f6b5-k2x8p 2/2 Running 0 3m fluxconfig-controller-5f8d7c9b4-q7w2n 2/2 Running 0 3m helm-controller-6b8f9d7c5-4mz9k 1/1 Running 0 3m kustomize-controller-7d9f8b6c4-p8n2x 1/1 Running 0 3m notification-controller-5c7d8f9b6-x2k7m 1/1 Running 0 3m source-controller-6f8d9c7b5-n4q8z 1/1 Running 0 3m NAME SCOPE URL PROVISION AGE fluxconfig.clusterconfig.azure.com/cluster-config cluster https://github.com/<you>/aks-gitops Succeeded 2m NAME URL READY STATUS gitrepository.source.toolkit.fluxcd.io/cluster-config https://github.com/<you>/aks-gitops True stored artifact for revision 'main@sha1:4f2c…' NAME READY STATUS kustomization.kustomize.toolkit.fluxcd.io/cluster-config-apps True Applied revision: main@sha1:4f2c… kustomization.kustomize.toolkit.fluxcd.io/cluster-config-infra True Applied revision: main@sha1:4f2c…
Argo CD extension (for comparison, single-node lab configuration)
az k8s-extension create -g $RG -c $CLUSTER -t managedClusters \ --name argocd --extension-type Microsoft.ArgoCD \ --config "redis-ha.enabled=false" \ --config "configs.params.application\.namespaces=myapp" kubectl get pods -n argocd
HA mode (the default) needs at least 4 nodes. For production, install with Bicep and enable azure.workloadIdentity.enabled and Entra SSO. Change all Argo CD settings through extension configuration (az k8s-extension update … --config …); editing the ConfigMap directly gets overwritten. Do not hand the same resources to both Flux and Argo CD.
Lab 2: use the Flux extension to deploy myapp to aks-lab (about 8 minutes)
Microsoft.KubernetesConfiguration/extensions and fluxConfigurations on the cluster (Contributor is enough, or Kubernetes Extension Contributor). Risk: prune=true deletes objects that are no longer in Git but were created by this configuration.<ACR> with your $ACR; aks-lab already granted pull access with --attach-acr in hour 1):
cd aks-gitops
cat > apps/myapp/redis.yaml <<'EOF'
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 } }
spec:
containers:
- name: redis
image: redis:7-alpine
ports: [{ containerPort: 6379 }]
resources: { requests: { cpu: 50m, memory: 64Mi }, limits: { memory: 128Mi } }
---
apiVersion: v1
kind: Service
metadata: { name: redis, namespace: myapp }
spec: { selector: { app: redis }, ports: [{ port: 6379 }] }
EOF
cat > apps/myapp/myapp.yaml <<'EOF'
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 } }
spec:
containers:
- name: myapp
image: <ACR>.azurecr.io/myapp:1.0
env: [{ name: REDIS_HOST, value: redis }]
ports: [{ containerPort: 5000 }]
readinessProbe: { httpGet: { path: /healthz, port: 5000 } }
livenessProbe: { httpGet: { path: /healthz, port: 5000 }, initialDelaySeconds: 10 }
resources: { requests: { cpu: 100m, memory: 128Mi }, limits: { memory: 256Mi } }
---
apiVersion: v1
kind: Service
metadata: { name: myapp, namespace: myapp }
spec: { selector: { app: myapp }, ports: [{ port: 80, targetPort: 5000 }] }
EOF
cat > apps/myapp/kustomization.yaml <<'EOF'
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources: [redis.yaml, myapp.yaml]
EOF
sed -i "s/<ACR>/$ACR/" apps/myapp/myapp.yaml
git add . && git commit -m "apps: myapp 1.0 + redis" && git pushkubectl get all -n myapp kubectl delete deploy,svc --all -n myapp # lab environments only
az k8s-configuration flux create -g $RG -c $CLUSTER -t managedClusters \
-n cluster-config --namespace cluster-config --scope cluster \
-u https://github.com/<your-account>/aks-gitops --branch main \
--kustomization name=infra path=./infrastructure prune=true \
--kustomization name=apps path=./apps/myapp prune=true dependsOn=\["infra"\]
az k8s-extension show -g $RG -c $CLUSTER -t managedClusters -n flux --query "{v:version, state:provisioningState}" -o table
kubectl get kustomizations -n cluster-config -w # press Ctrl+C once both show True
kubectl get deploy,svc -n myapp
V State ------ --------- 1.26.4 Succeeded NAME READY UP-TO-DATE AVAILABLE AGE deployment.apps/myapp 2/2 2 2 1m deployment.apps/redis 1/1 1 1 1m
sed -i 's/myapp:1.0/myapp:1.1/' apps/myapp/myapp.yaml && git commit -am "myapp 1.1" && git push
# Option A (flux CLI installed): flux reconcile source git cluster-config -n cluster-config
# Option B (kubectl only): annotate the object to request immediate reconciliation
kubectl annotate gitrepository cluster-config -n cluster-config reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
kubectl rollout status deploy/myapp -n myapp
kubectl get deploy myapp -n myapp -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}'
deployment "myapp" successfully rolled out acraks12345.azurecr.io/myapp:1.1
kubectl scale deploy/myapp -n myapp --replicas=5 kubectl annotate kustomization cluster-config-apps -n cluster-config reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite sleep 20; kubectl get deploy myapp -n myapp
NAME READY UP-TO-DATE AVAILABLE AGE myapp 2/2 2 2 6m
The replica count goes back to 2, as defined in Git. In production, if an HPA really manages the replica count, remove the replicas field from the manifest; otherwise Flux and the HPA will overwrite each other.
az k8s-configuration flux delete -g $RG -c $CLUSTER -t managedClusters -n cluster-config --yes # will prune myapp az k8s-extension delete -g $RG -c $CLUSTER -t managedClusters -n flux --yes # delete the configuration before the extension
Case 1: pushing configuration to 200 store clusters
Problem: A retail company runs many AKS clusters across several regions and needs to roll out ingress, monitoring agents, and a network policy baseline consistently. Approach: Use the built-in Azure Policy GitOps policy (assigned per resource group or subscription) to create fluxConfigurations on the clusters automatically. Organize the repository as base/ + clusters/<region>/ Kustomize overlays. Use Resource Graph to query complianceState != 'Compliant' and build a daily report. Limits: Policy assignment evaluation has a delay. If two configurations manage the same path, they overwrite each other, so use a naming convention to avoid this.
Case 2: platform and application layers in separate repositories
Problem: The platform team manages CRDs, cert-manager, and policies. Application teams only want to manage their own namespaces. Approach: Create two fluxConfigurations on one cluster: platform (--scope cluster, platform repository) and team-a (--scope namespace --namespace team-a, team repository). The latter only has permissions inside its namespace. The platform Kustomization runs before the application one (you cannot use dependsOn across different configurations, so control the order with health checks or staged rollouts). Limits: A namespace-scoped configuration cannot create cluster-level objects (such as CRDs or ClusterRoles).
Case 3: migrating from a self-installed Argo CD to the managed extension
Problem: The team maintains Argo CD itself, and upgrades keep getting postponed. Approach: Follow the official migration path: inventory Applications, ApplicationSets, AppProjects, and repository credentials → scale the self-managed controller down to 0 to prevent dual control → install the Microsoft.ArgoCD extension and configure the same application.namespaces → migrate credentials and cluster Secrets → verify sync → delete the old deployment. Limits: The extension does not support editing the ConfigMap directly. If you also use Azure Backup for AKS, set application.resourceTrackingMethod: annotation+label in the Argo CD ConfigMap (through extension configuration).
Common errors and fixes
complianceState: Non-Compliant — GitRepository: failed to checkout and determine revision: unable to clone 'https://github.com/…': authentication required
Cause: The repository is private, or the URL is misspelled.
kubectl describe gitrepository cluster-config -n cluster-config | sed -n '/Conditions/,$p'
Fix: For a public repository, check the URL. For a private repository, use --https-user/--https-key (a PAT; rotate it regularly), an SSH private key (--ssh-private-key-file, must match an ssh:// URL), or workload identity to access Azure DevOps or ACR OCI sources. Credentials are stored as a Secret in the configuration namespace.
Kustomization cluster-config-apps: dependency 'cluster-config/cluster-config-infra' is not ready
Cause: The infra that apps depends on has failed or is still reconciling. This is a protective mechanism, not a bug.
kubectl get kustomization cluster-config-infra -n cluster-config -o jsonpath='{.status.conditions[?(@.type=="Ready")].message}{"\n"}'
Fix: Fix infra first (common causes: the path does not exist, YAML syntax errors, CRDs not ready).
kustomize build failed: accumulating resources: … 'apps/myapp' must resolve to a file / no such file or directory
Cause: path= is wrong, or the directory has no kustomization.yaml and contains non-Kubernetes files.
Fix: Verify locally with kubectl kustomize ./apps/myapp. Paths are relative to the repository root and use a ./ prefix.
Pod stuck in ImagePullBackOff, but flux show reports Compliant
Cause: A Kustomization only guarantees that the objects were applied. Without health waiting enabled, it does not check Pod status. The image does not exist, or ACR is not authorized.
kubectl describe pod -n myapp -l app=myapp | grep -A3 Events az aks check-acr -g $RG -n $CLUSTER --acr $ACR.azurecr.io
Fix: Correct the image tag, or run az aks update --attach-acr. The Azure CLI kustomization parameters (name/path/prune/depends_on/timeout/sync_interval/retry_interval/validation/force) do not include health waiting. The officially suggested workaround is to put an upstream Kustomization CR with wait: true or healthChecks into Git and let the fluxConfiguration deploy it, so an unhealthy Pod shows up as Not Ready.
Error: The extension microsoft.flux is not supported for clusters using service principal
Cause: Both the Flux and Argo CD extensions require a cluster with a managed identity.
az aks show -g $RG -n $CLUSTER --query "{sp:servicePrincipalProfile.clientId, id:identity.type}"
Fix: az aks update -g $RG -n $CLUSTER --enable-managed-identity (this rolls the nodes, so run it in a maintenance window).
1. List only the non-compliant Flux object names in cluster-config.
az k8s-configuration flux show -g rg-aks-lab -c aks-lab -t managedClusters -n cluster-config \
--query "statuses[?complianceState!='Compliant'].{kind:kind,name:name,msg:statusConditions[0].message}" -o table2. Without installing the flux CLI, immediately trigger a fresh pull of the GitRepository.
kubectl annotate gitrepository cluster-config -n cluster-config reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite
An on-call engineer rolled myapp back to 1.0 by hand to stop the bleeding, but ten minutes later it “automatically changed back” to 1.1. Why? What is the correct way to roll back?
Flux's kustomize-controller reconciles the cluster back to the desired state in Git on its interval. A manual change is drift, so it gets overwritten. The correct approach is to git revert the release commit and push it (trigger a reconciliation manually if needed). If you need a temporary freeze, you can suspend reconciliation for the whole configuration (configuration parameter --suspend: “suspend all source and kustomize reconciliation defined by this configuration”; check az k8s-configuration flux update -h for the exact update syntax). Resume after the incident and record it in the postmortem.
Verified teaching videos
Official docs
- Tutorial: Deploy applications using GitOps with Flux v2
- microsoft.flux release notes
- GitOps (Flux v2) supported parameters
- Tutorial: GitOps with Argo CD
Video storyboard script (about 100 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
On screen: on the left, a “fluxConfiguration” card in an Azure cloud icon; on the right, an empty flux-system namespace in the cluster.
Narration: On AKS, Flux is a cluster extension. You declare the configuration in Azure, and an agent in the cluster pulls it down.
On screen: fluxconfig-agent receives the card → it becomes a FluxConfig → it expands into a GitRepository and two Kustomizations.
Narration: Azure's own controller translates the configuration into upstream Flux objects. From then on, the work is handled entirely by the open-source source controller and kustomize controller.
On screen: a Git commit lights up, the artifact version changes, and the Deployment rolls out. Then someone runs kubectl scale, and a few seconds later the value is reverted.
Narration: New commits are pulled and applied. Manual changes are reverted at the next reconciliation. Git is the only source of truth.
On screen: the compliance state in the portal changes from Pending to Compliant.
Narration: Finally, the agent reports status back to Azure. The GitOps state of hundreds of clusters can be seen in a single query.
Module 3 · Pipelines: deploying to AKS with GitHub Actions and Azure Pipelines
- Set up a keyless identity for the pipeline: a user-assigned managed identity + a federated credential (the GitHub
repo:…:environment:productionsubject, or the Azure DevOps workload identity federation service connection). - Grant permissions on least-privilege principles: at the ARM layer, only the “Azure Kubernetes Service Cluster User Role” (to get kubeconfig). For the data plane, use Azure RBAC to scope “Azure Kubernetes Service RBAC Writer” to
namespaces/myapp. - Handle private clusters and disabled local accounts: kubelogin, self-hosted runners / Managed DevOps Pools,
az aks command invoke. - Compare the push model (the pipeline runs kubectl/helm against the cluster) with the GitOps pull model (the pipeline only changes Git and Flux deploys), and choose the right one for each environment.
What: the three gates a pipeline passes to reach the cluster
| Gate | Who checks | What the pipeline needs | Typical failure |
|---|---|---|---|
| ① Sign in to Azure | Microsoft Entra ID | OIDC token matches the federated credential (issuer / subject / audience) | AADSTS70021: No matching federated identity record found |
| ② Get kubeconfig | ARM (Azure RBAC, control plane) | Microsoft.ContainerService/managedClusters/listClusterUserCredential/action (Cluster User Role) | AuthorizationFailed … listClusterUserCredential |
| ③ Call kube-apiserver | AKS Entra authentication webhook + Azure RBAC authorization webhook (or K8s RBAC) | Entra token from kubelogin; data-plane role on the target namespace | Forbidden: User "…" cannot create resource "deployments" … in the namespace "myapp" |
| ④ Admission | Gatekeeper / Deployment Safeguards / VAP (module 7) | Compliant manifests | admission webhook "validation.gatekeeper.sh" denied the request |
Why: why cluster administrators should care about pipelines
- A pipeline identity is often the most privileged and least audited identity. A service principal that can
kubectl applyto every namespace, plus a client secret stored in a repository Secret, is a common entry point for lateral movement. - Once
disableLocalAccountsis enabled, old pipelines that fetch credentials with--adminfail outright. A private cluster also means a managed runner cannot reach the API server at all. - More and more deployment failures come from cluster-side policies (quotas, safeguards) rather than from the YAML itself.
How: two recommended models
| Push model | GitOps pull model | |
|---|---|---|
| What the pipeline does | Build image → push to ACR → sign in to Azure → kubelogin → kubectl apply/helm upgrade | Build image → push to ACR → update the image tag in the GitOps repository (PR or direct commit) |
| Pipeline needs cluster permissions | Yes (namespace-level) | No; only write access to the GitOps repository |
| Private cluster | Needs a runner inside the VNet or command invoke | No effect (Flux pulls outbound from inside the cluster) |
| Drift correction and audit | None; audit uses pipeline logs | Flux reconciles continuously; audit uses Git history |
| Deployment feedback | Synchronous (rollout status) | Asynchronous (needs notification-controller to write commit status back, or to send alerts) |
| Best for | Dev/test environments and scenarios that need immediate feedback | Production, multi-cluster, private clusters |
When: how to choose
- Production and multi-cluster: use the pull model. The pipeline's “deploy” step is a PR against
aks-gitops, and approving it is the release. - Dev environments: the push model is acceptable, but still use OIDC and namespace-level permissions. Do not use Cluster Admin.
- Database migrations and one-off tasks: run a Job with the push model, or use a hash-suffixed Job name in GitOps.
Comparison with other authentication methods
| Method | Where the secret is stored | Rotation | Verdict |
|---|---|---|---|
| Workload identity federation (OIDC) | None | Not needed | Recommended |
| Service principal + client secret | Repository/library Secret | Manual | Phase out |
az aks get-credentials --admin | Certificate in kubeconfig | Cluster certificate must be rotated | Unusable once local accounts are disabled |
| Kubernetes ServiceAccount long-lived token | Repository Secret | Manual | Not recommended; bypasses Entra auditing |
repo:org/repo:environment:production, and for a branch push it is repo:org/repo:ref:refs/heads/main. If they don't match, you get AADSTS70021. ③ “With the pull model you don't need a pipeline.” You still need CI to build, scan, and sign images, and changes to the GitOps repository still need approval.Architecture diagram: trust boundaries for the push and pull models
Flowchart: how the exec plugin in kubeconfig gets a token
Interactive animation: the token and authorization chain that a push-model deployment goes through
First choose a “fault injection,” then step through. The log shows the real requests, claims, or error messages at each hop (sample values).
Core commands and parameters (cluster side)
| Command | Purpose | Key parameters / notes |
|---|---|---|
az identity create | Create pipeline identity id-aks-deployer | Separate from the application's id-myapp for separation of duties |
az identity federated-credential create | Trust GitHub OIDC tokens | --issuer https://token.actions.githubusercontent.com, --subject repo:ORG/REPO:environment:production, --audiences api://AzureADTokenExchange |
az role assignment create --scope $AKS_ID | Allow fetching kubeconfig | Role “Azure Kubernetes Service Cluster User Role” |
az role assignment create --scope $AKS_ID/namespaces/myapp | Namespace-level data-plane permissions | Role “Azure Kubernetes Service RBAC Writer” (does not include Role/RoleBinding management) |
kubelogin convert-kubeconfig -l azurecli | Change kubeconfig to use the exec plugin | In pipelines you can also use -l workloadidentity |
az aks command invoke | Run commands inside a private cluster | --command "kubectl apply -f manifest.yaml" --file manifest.yaml; requires ARM permissions and suits ad-hoc operations |
GitHub Actions: cluster-related snippet for the push model
permissions:
id-token: write # allow requesting an OIDC token
contents: read
jobs:
deploy:
runs-on: ubuntu-latest # for a private cluster, switch to a self-hosted runner inside the VNet
environment: production # determines the OIDC subject: repo:ORG/REPO:environment:production
steps:
- uses: actions/checkout@v4
- uses: azure/login@v3
with:
client-id: ${{ vars.AZURE_CLIENT_ID }} # clientId of id-aks-deployer
tenant-id: ${{ vars.AZURE_TENANT_ID }}
subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
- uses: azure/use-kubelogin@v1
with: { kubelogin-version: 'v0.2.22' }
- run: |
az aks get-credentials -g rg-aks-lab -n aks-lab --overwrite-existing
kubelogin convert-kubeconfig -l azurecli
kubectl -n myapp set image deploy/myapp myapp=${{ vars.ACR }}.azurecr.io/myapp:${{ github.sha }}
kubectl -n myapp rollout status deploy/myapp --timeout=180s
Action versions checked against GitHub Releases (2026-11): azure/login v3.1.0, azure/use-kubelogin v1.3, kubelogin v0.2.22. For details on building and pushing images, environment approvals, reusable workflows, and similar topics, see GitHub hour 3. Note: if Flux manages myapp on this cluster (Module 2), changing the image in push mode will be reverted by Flux. That is exactly the problem the next snippet solves.
GitHub Actions: pull model (only changes the GitOps repository)
promote:
runs-on: ubuntu-latest
needs: build
steps:
- uses: actions/checkout@v4
with:
repository: ORG/aks-gitops
token: ${{ secrets.GITOPS_PR_TOKEN }} # fine-grained token / GitHub App with only contents + pull_requests write access to aks-gitops
- run: |
sed -i "s#myapp:.*#myapp:${{ github.sha }}#" apps/myapp/myapp.yaml
git checkout -b promote-${{ github.sha }}
git commit -am "promote myapp ${{ github.sha }}" && git push -u origin HEAD
gh pr create --fill --base main
env: { GH_TOKEN: ${{ secrets.GITOPS_PR_TOKEN }} }
Azure Pipelines equivalent
- For the service connection type, choose “Azure Resource Manager → Workload identity federation.” Under the hood it is the same federated credential. Grant this identity the two AKS roles above.
- If a hosted agent cannot reach a private cluster, use Managed DevOps Pools with VNet injection, or a self-hosted agent.
- Environments + approvals and checks correspond to GitHub's environment protection rules. For details, see Azure DevOps hour 3.
Lab 3: configure pipeline identity permissions so it can only deploy myapp (about 6 minutes)
az identity create -g $RG -n id-aks-deployer -l $LOC
DEPLOYER_CLIENT=$(az identity show -g $RG -n id-aks-deployer --query clientId -o tsv)
DEPLOYER_OID=$(az identity show -g $RG -n id-aks-deployer --query principalId -o tsv)
az identity federated-credential create -g $RG --identity-name id-aks-deployer -n gh-production \
--issuer https://token.actions.githubusercontent.com \
--subject "repo:ORG/REPO:environment:production" \
--audiences api://AzureADTokenExchange
az identity federated-credential list -g $RG --identity-name id-aks-deployer --query "[].{name:name,subject:subject}" -o table
Name Subject ------------- ------------------------------------- gh-production repo:ORG/REPO:environment:production
az role assignment create --assignee-object-id $DEPLOYER_OID --assignee-principal-type ServicePrincipal \
--role "Azure Kubernetes Service Cluster User Role" --scope $AKS_ID
az role assignment create --assignee-object-id $DEPLOYER_OID --assignee-principal-type ServicePrincipal \
--role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp
ACR_ID=$(az acr show -n $ACR --query id -o tsv)
az role assignment create --assignee-object-id $DEPLOYER_OID --assignee-principal-type ServicePrincipal \
--role AcrPush --scope $ACR_ID
az role assignment list --assignee $DEPLOYER_OID --all --query "[].{role:roleDefinitionName, scope:scope}" -o table
Role Scope ------------------------------------------ --------------------------------------------------------------- Azure Kubernetes Service Cluster User Role /subscriptions/…/managedClusters/aks-lab Azure Kubernetes Service RBAC Writer /subscriptions/…/managedClusters/aks-lab/namespaces/myapp AcrPush /subscriptions/…/registries/acraks12345
kubectl auth can-i create deployments -n myapp kubectl auth can-i create deployments -n default kubectl auth can-i create rolebindings -n myapp
yes no no
RBAC Writer does not include Role/RoleBinding management permissions, so the third check returns no. Role assignments can take a few minutes to propagate to the cluster authorization webhook, so a temporary no may appear during that time.
AZURE_CLIENT_ID=$DEPLOYER_CLIENT, AZURE_TENANT_ID, AZURE_SUBSCRIPTION_ID, and ACR. Create an environment named production, then run the deploy job from the “Commands” tab. You should see rollout status succeed. If Flux manages myapp, the image will revert to the version in Git after a few minutes, so use the pull-model snippet instead.az identity delete -g $RG -n id-aks-deployer
After you delete the identity, its role assignments remain as “unknown identity” leftovers. Check for them and delete them with az role assignment list --scope $AKS_ID.
Case 1: remediation after a pipeline secret leak
Problem: A repository's Actions secret held the key of a service principal with Contributor on the subscription, and a malicious PR's workflow printed it to the logs. Approach: Revoke the key immediately. Switch to a user-assigned managed identity + federated credential, with the subject bound to environment:production and approval required on that environment. Narrow ARM permissions to Cluster User Role, and limit data-plane permissions to the namespace. Workflows triggered by pull_request do not get id-token: write. Limits: Each repository/environment combination needs its own federated credential (a single identity has a limit on the number of federated credentials). At scale, consider flexible federated identity credentials or split identities per team.
Case 2: private cluster + GitHub-hosted runners
Problem: After the cluster switched to a private API server, all deployment jobs timed out. Approach: For production, switch to the GitOps pull model (Flux pulls outbound, so no inbound access to the API server is needed). For maintenance tasks that still need a push, use a self-hosted runner inside the VNet (or Azure DevOps Managed DevOps Pools). In emergencies, use az aks command invoke. Limits: command invoke creates a temporary Pod inside the cluster to run the command, so it is subject to node resources and policies. It is not suitable for large-scale routine deployments.
Case 3: a deployment blocked by Safeguards, with no one knowing why
Problem: After the platform team switched Deployment Safeguards from Warn to Enforce, pipelines failed across several teams. The logs only said “admission webhook denied.” Approach: Add a pre-check step to the pipeline: kubectl apply --dry-run=server with the full error output. Keep Safeguards in Warn for two weeks before the switch and collect Azure Policy compliance reports. In the team template repository, fix the latest tags, missing probes, and requests. Limits: A server-side dry run also needs the API server to be reachable and the right permissions.
Common errors and fixes
AADSTS70021: No matching federated identity record found for presented assertion. Assertion Issuer: 'https://token.actions.githubusercontent.com'. Assertion Subject: 'repo:org/app:ref:refs/heads/main'.
Cause: The workflow does not use an environment (so the subject becomes ref:…), or the repository/environment name differs in case or spelling.
az identity federated-credential list -g $RG --identity-name id-aks-deployer -o table
Fix: Make the federated credential's subject exactly match the Assertion Subject in the error message. We recommend declaring environment: production on the job and using that environment in the federated credential.
(AuthorizationFailed) The client '…' does not have authorization to perform action 'Microsoft.ContainerService/managedClusters/listClusterUserCredential/action'
Cause: The Cluster User Role is missing (or assigned at the wrong scope).
Fix: Assign “Azure Kubernetes Service Cluster User Role” on the cluster resource. Do not use Cluster Admin Role instead. It allows retrieving admin credentials, which is pointless once local accounts are disabled.
error: unknown flag: --admin / Getting static credential is not allowed because this cluster is set to disable local accounts.
Cause: The old pipeline uses az aks get-credentials --admin.
Fix: Remove --admin, install kubelogin, run kubelogin convert-kubeconfig -l azurecli (or workloadidentity), and grant the data-plane role.
Error from server (Forbidden): deployments.apps "myapp" is forbidden: User "…" cannot patch resource "deployments" in API group "apps" in the namespace "myapp": User does not have access to the resource in Azure. Update role assignment to allow access.
Cause: The data-plane role is missing, the scope points to another namespace, or the assignment was just created and is still propagating.
az role assignment list --assignee $DEPLOYER_OID --all --query "[?contains(scope,'managedClusters')].{role:roleDefinitionName,scope:scope}" -o table
Fix: Use the scope $AKS_ID/namespaces/myapp, then wait a few minutes and retry.
dial tcp 10.x.x.x:443: i/o timeout (private cluster)
Cause: The hosted runner is on the public internet and cannot reach the private endpoint of the private API server.
Fix: Switch to the pull model, use a runner inside the VNet or Managed DevOps Pools, or temporarily run az aks command invoke -g $RG -n $CLUSTER --command "kubectl get pods -n myapp".
1. Create a federated credential for the staging environment of the GitHub repository contoso/shop.
az identity federated-credential create -g rg-aks-lab --identity-name id-aks-deployer -n gh-staging \ --issuer https://token.actions.githubusercontent.com \ --subject "repo:contoso/shop:environment:staging" --audiences api://AzureADTokenExchange
2. Grant the pipeline read-only data-plane permission on the myapp namespace only.
az role assignment create --assignee-object-id $DEPLOYER_OID --assignee-principal-type ServicePrincipal \ --role "Azure Kubernetes Service RBAC Reader" --scope $AKS_ID/namespaces/myapp
A company has 12 private AKS clusters and 40 application repositories. The security team requires that “pipelines must not hold any cluster access.” How would you design the delivery?
Use the GitOps pull model: install the Flux extension on every cluster (rolled out consistently via Azure Policy or AVM parameters), with a platform repository plus per-team application repositories or directories. CI only builds, scans, signs, and pushes to ACR (AcrPush via OIDC), then opens a PR against the GitOps repository. The GitOps repository has branch protection and CODEOWNERS approval. Control the release order across clusters with directories or branches per environment, or with Fleet resource placement (which requires a hub). Report deployment results back as commit status, or send alerts, through the Flux notification-controller. Keep cluster access only for a small number of break-glass identities (activated through PIM).
Verified teaching videos
Official docs
- Use GitHub Actions to connect to Azure (OIDC)
- Use Azure RBAC for Kubernetes authorization
- Use kubelogin to authenticate
- Access a private AKS cluster (command invoke)
Video storyboard script (about 80 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
On screen: a pipeline figure holds a “master key” (client secret), crossed out with a red X.
Narration: A pipeline should never hold a long-lived secret. Use federated credentials, so a short-lived token issued by GitHub is exchanged for an Azure token.
On screen: four doors open one after another: Entra, ARM, API server, admission.
Narration: Signing in to Azure is only the first gate. Getting kubeconfig requires the cluster user role, operating within a namespace requires a data-plane role, and finally the request must pass policy admission.
On screen: the pipeline only submits a PR to the GitOps repository, and Flux in the cluster pulls the change in.
Narration: The safer approach is the pull model. The pipeline only changes Git, and the cluster pulls the change for itself. Private clusters are fine with this too.
Module 4 · Multi-cluster: Azure Kubernetes Fleet Manager
- Distinguish the two Fleet forms: without a hub (multi-cluster update orchestration only) and with a hub (adds resource placement, multi-cluster load balancing, and hub-managed Fleet namespaces). Know that “a hubless Fleet can be upgraded to one with a hub, but not the other way around.”
- Explain the execution semantics of an update run: stages run in order, groups within a stage run in parallel, and members within a group run one at a time by default (group-level max concurrency defaults to 1, stage-level to 50). Explain how post-stage waits, approval gates, and maintenance windows put a run into Pending.
- Use the CLI to: create a Fleet, add members and assign update groups, create an update strategy with approval gates, start an update run with NodeImageOnly, approve gates, and skip or restart.
- Use auto-upgrade profiles (Rapid / Stable / TargetKubernetesVersion / NodeImage / SecurityPatch preview) to keep updates running continuously, and understand how they conflict with the AKS cluster's own auto-upgrade.
What: what Fleet Manager is
Azure Kubernetes Fleet Manager is a regional Azure resource (Microsoft.ContainerService/fleets) that organizes up to 1,000 AKS clusters (and Arc-enabled Kubernetes clusters) as members. This hour uses its multi-cluster update orchestration capability:
| Concept | Meaning | Key rules (official docs, 2026-08/10 version) |
|---|---|---|
| Update run | One execution of “which clusters to upgrade to what” | Upgrade types Full / ControlPlaneOnly / NodeImageOnly; node image selection Latest / Consistent; you can only specify the Kubernetes target version, and the system selects the node image version |
| Update strategy | Reusable stage/group template | A created run copies it at run time, so later changes to the strategy do not affect existing runs |
| Stage | Runs in order | Can set afterStageWaitInSeconds, pre/post approval gates (preview), and a stage-level max concurrency (preview, default 50) |
| Group | Runs in parallel within a stage | Up to 50 groups per stage; group-level max concurrency defaults to 1 (so members within a group are upgraded one at a time) |
| Member | One cluster | Can belong to only one update group; can also be selected with member labels + memberSelector (preview, the direction the official docs recommend) |
| Gate | Pause point | Approval gate (preview; az fleet gate approve; does not expire and cannot be approved in advance); scheduled start gate (preview) |
| Auto-upgrade profile | Automatically creates and starts a run when a new version is released | Channels Rapid (N) / Stable (N-1) / TargetKubernetesVersion (fixed minor, optional LTS) / NodeImage / SecurityPatch (preview, Linux only) |
Why: why not let each cluster auto-upgrade on its own
- Ordering and blast radius: AKS cluster auto-upgrade only guarantees that a single cluster upgrades within its maintenance window. It does not guarantee that dev goes before prod. Fleet lets a new version run on canary clusters for a while before it moves on to production.
- Consistency: the
Consistentnode image selection picks the latest common image that has been published in every region where the members are located. This avoids a situation where the image you validated earlier is not the one production uses later. - Observability and control: the state of runs, stages, groups, and members is written to Azure Resource Graph, where you can set alerts. You can stop, skip, or restart at any time (resuming from the last unprocessed cluster).
How: execution semantics
- Run starts → enters the first stage → if there is a “pre-stage” approval gate, it waits in Pending for approval.
- All groups in a stage start at the same time. Within each group, member clusters are upgraded one at a time, subject to max concurrency (default 1). NodeImageOnly runs a node image upgrade on each node pool; Full upgrades the control plane first, then the node pools.
- If a member's maintenance window is not open → that member goes to Pending, and the run tries the next member in the same group. Fleet polls maintenance windows once per hour. If the target version is not yet published in that region → also Pending.
- If any member fails (when maxAllowedFailures is not configured) → the group, stage, and run become Failed, while the other members already upgrading finish (the run shows Stopping).
- When all groups in a stage finish → the “post-stage” approval gate and
afterStageWaitInSecondsstart timing at the same time. The next stage begins only when both are satisfied. - When all stages finish → Completed. Note: when maxAllowedFailures is configured, Completed does not mean everything succeeded. Check
FailureCount.
When: choose the form and channel
- If you only need “ordered upgrades”: a hubless Fleet (this hour). If you need to push the same Kubernetes resources to multiple clusters (ClusterResourcePlacement) or to hub-managed Fleet namespaces: a hub (the hub is a single-node AKS cluster managed by Microsoft, and it incurs charges while running).
- Members managed by Fleet orchestration should have the cluster's own Kubernetes auto-upgrade turned off. Otherwise, whoever upgrades first wins (quoted from the FAQ). The same applies to node image channels: use Fleet's NodeImage channel auto-upgrade profile instead.
- AKS Automatic members are only partially supported (cluster-level auto-upgrade cannot be turned off, so upgrades can happen out of order). Clusters with NAP enabled only support control plane upgrades. Arc clusters do not support multi-cluster updates.
- A cluster that stays on an EOL version beyond the 60-day platform support grace period will be subject to forced platform upgrades from AKS, which Fleet's ordering and maintenance windows do not control. Use an auto-upgrade profile to keep members within the support window at all times.
Comparison with similar approaches
| Fleet update run | Per-cluster auto-upgrade channel | Pipeline script running az aks upgrade one cluster at a time | |
|---|---|---|---|
| Ordering across clusters | Stage / group | None | Write it yourself |
| Approval and waiting | Approval gates, post-stage wait | None | Pipeline approval |
| Maintenance window | Honored | Honored | Needs your own judgment |
| Image consistency | Consistent option | Each cluster takes the latest | You must specify it yourself |
| Failure handling | Fails fast by default; tolerance can be set (preview) | Single cluster | Write it yourself |
Architecture diagram: this hour's Fleet topology and update strategy
State machine: the update run lifecycle
Core animation: Fleet staged update run simulator
A 5-cluster Fleet: stage canary (1 group / 1 member) → stage prod (2 groups in parallel, each upgrading 2 members one at a time). Choose the options you want, then press “Play.” The log shows the real operations Fleet sends to member clusters (NodeImageOnly calls upgradeNodeImageVersion for each node pool; Full first PUTs the control plane version) and the CLI commands. Time is compressed.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az fleet create | Create Fleet | --enable-managed-identity; --enable-hub creates the hub (irreversible); a private hub also needs --enable-private-cluster --enable-vnet-integration … |
az fleet member create / update | Add members / change update groups | --member-cluster-id, --update-group, --labels "env=staging tier=frontend" (preview) |
az fleet updatestrategy create | Save stage/group template | --stages strategy.json |
az fleet updaterun create | Create update run (does not start automatically) | --upgrade-type Full|ControlPlaneOnly|NodeImageOnly, --kubernetes-version (Full/ControlPlaneOnly), --node-image-selection Latest|Consistent, --update-strategy-name or --stages |
az fleet updaterun start / stop / skip / show / delete | Manage runs | skip --targets Group:name Stage:name |
az fleet gate list / approve | Approval gate (preview, fleet extension ≥ 1.6.0) | list --gate-type Approval --state Pending |
az fleet autoupgradeprofile create / generate-update-run | Auto-upgrade | --channel Stable|Rapid|TargetKubernetesVersion|NodeImage|SecurityPatch, --update-strategy-id, --node-image-selection, --target-kubernetes-version 1.37, --long-term-support, --disabled |
Strategy file with approval gate
{
"stages": [
{
"name": "canary",
"groups": [ { "name": "canary" } ],
"afterStageWaitInSeconds": 60,
"afterGates": [ { "displayName": "Verify canary", "type": "Approval" } ]
},
{
"name": "prod",
"groups": [ { "name": "prod" } ]
}
]
}
FLEET=fleet-aks-lab az fleet updatestrategy create -g $RG --fleet-name $FLEET -n staged --stages strategy.json az fleet updaterun create -g $RG --fleet-name $FLEET -n run-nodeimage-1 \ --upgrade-type NodeImageOnly --node-image-selection Consistent --update-strategy-name staged az fleet updaterun start -g $RG --fleet-name $FLEET -n run-nodeimage-1
Observe and approve
az fleet updaterun show -g $RG --fleet-name $FLEET -n run-nodeimage-1 \
--query "{run:status.status.state, stages:status.stages[].{stage:name, state:status.state, groups:groups[].{group:name, state:status.state, members:members[].{m:name, s:status.state, msg:message}}}}" -o json
az fleet gate list -g $RG --fleet-name $FLEET --gate-type Approval --state Pending -o table
az fleet gate approve -g $RG --fleet-name $FLEET -n <gate-name>
{
"run": "Pending",
"stages": [
{ "stage": "canary", "state": "Pending",
"groups": [ { "group": "canary", "state": "Completed",
"members": [ { "m": "aks-lab-bicep", "s": "Completed", "msg": null } ] } ] },
{ "stage": "prod", "state": "NotStarted",
"groups": [ { "group": "prod", "state": "NotStarted",
"members": [ { "m": "aks-lab", "s": "NotStarted", "msg": null } ] } ] }
]
}
How to verify: after stage canary completes, the run enters Pending (waiting on the approval gate and the 60-second wait). After approval, prod starts. Common errors: a member not assigned to any update group does not appear in any group; approval gates cannot be used with one-by-one runs. Production use: use az fleet updaterun show … --query "status.nodeImageSelection.selectedNodeImageVersions" to record the image selected for this run, and attach it to the change ticket.
Auto-upgrade profile (ongoing)
STRATEGY_ID=$(az fleet updatestrategy show -g $RG --fleet-name $FLEET -n staged --query id -o tsv) az fleet autoupgradeprofile create -g $RG --fleet-name $FLEET -n nodeimage-weekly \ --channel NodeImage --update-strategy-id $STRATEGY_ID az fleet autoupgradeprofile generate-update-run -g $RG --fleet-name $FLEET -n nodeimage-weekly # generate one run now from the current release (does not start automatically)
Lab 4: two-cluster staged node image update (about 15–30 minutes, including waits)
Microsoft.ContainerService/fleets/* and managedClusters/write on the member clusters (Contributor is enough). Risk: a node image update rebuilds nodes one at a time according to the surge setting. On a single-node cluster, Pods are evicted and rebuilt, so myapp will have a brief outage. If a node is already on the latest image, the member shows Skipped (this is also a normal result).FLEET=fleet-aks-lab
az fleet create -g $RG -n $FLEET -l $LOC --enable-managed-identity
BICEP_ID=$(az aks show -g $RG -n aks-lab-bicep --query id -o tsv)
az fleet member create -g $RG --fleet-name $FLEET -n aks-lab-bicep --member-cluster-id $BICEP_ID --update-group canary
az fleet member create -g $RG --fleet-name $FLEET -n aks-lab --member-cluster-id $AKS_ID --update-group prod
az fleet member list -g $RG --fleet-name $FLEET --query "[].{name:name, group:group, state:provisioningState}" -o table
Name Group State ------------- ------- --------- aks-lab-bicep canary Succeeded aks-lab prod Succeeded
for c in aks-lab-bicep aks-lab; do
az aks show -g $RG -n $c --query "{name:name, k8s:currentKubernetesVersion, channel:autoUpgradeProfile.upgradeChannel, nodeOs:autoUpgradeProfile.nodeOsUpgradeChannel}" -o tsv
done
This lab only runs a one-time NodeImageOnly run and does not change the channel settings of aks-lab (hour 6 covers this in depth). In production, set each member's upgradeChannel to none and replace it with Fleet's auto-upgrade profile.
az fleet updatestrategy create -g $RG --fleet-name $FLEET -n staged --stages strategy.json az fleet updaterun create -g $RG --fleet-name $FLEET -n run-nodeimage-1 \ --upgrade-type NodeImageOnly --node-image-selection Consistent --update-strategy-name staged az fleet updaterun start -g $RG --fleet-name $FLEET -n run-nodeimage-1 az fleet updaterun show -g $RG --fleet-name $FLEET -n run-nodeimage-1 --query "status.nodeImageSelection.selectedNodeImageVersions"
kubectl --context aks-lab-bicep get nodes -o custom-columns=NAME:.metadata.name,IMAGE:.metadata.labels.kubernetes\.azure\.com/node-image-version
az fleet gate list -g $RG --fleet-name $FLEET --gate-type Approval --state Pending --query "[].{name:name, display:displayName}" -o table
GATE=$(az fleet gate list -g $RG --fleet-name $FLEET --gate-type Approval --state Pending --query "[0].name" -o tsv)
az fleet gate approve -g $RG --fleet-name $FLEET -n $GATE
Name Display ------------------------------------ ---------- aaaa0a0a-bb1b-cc2c-dd3d-eeeeee4e4e4e Verify canary
The node label kubernetes.azure.com/node-image-version shows the current image. The kubeconfig context name defaults to the cluster name. After approval, you still need to wait 60 seconds for the post-stage wait.
kubectl --context aks-lab get pods -n myapp -w # watch Pods migrate during node rebuilds az fleet updaterun show -g $RG --fleet-name $FLEET -n run-nodeimage-1 --query "status.status.state" -o tsv
Completed
aks-lab-bicep:
az fleet updaterun delete -g $RG --fleet-name $FLEET -n run-nodeimage-1 --yes az fleet member delete -g $RG --fleet-name $FLEET -n aks-lab-bicep --yes az fleet member delete -g $RG --fleet-name $FLEET -n aks-lab --yes az fleet delete -g $RG -n $FLEET --yes
Case 1: quarterly minor upgrades across 40 clusters in three regions
Problem: Every minor upgrade depends on engineers working overtime to run them one by one, and production incidents often happen at the “first production cluster.” Approach: Divide members by the labels env=dev/staging/prod and region. The strategy runs dev → staging (post-stage wait of 24 hours + approval gate) → prod-ring1 (one cluster per region) → prod-ring2 (the remaining groups in parallel). Use the Consistent node image. Set the auto-upgrade profile to TargetKubernetesVersion, and after platform team review, change the target minor from 1.36 to 1.37. Limits: Approval gates, max concurrency, and member label selection are still preview features. Fleet polls maintenance windows once per hour, so leave a buffer in the schedule.
Case 2: an update run stuck for three days
Problem: The run stayed in Pending. Approach: Checking the member messages showed that the maintenance windows of two members only open on Sundays, and the new node image for another region had not been published yet (you can check the Release Tracker). For window problems, wait or adjust the maintenance configuration. For region publishing problems, skip that member and run it separately later. Limits: Skipped clusters end up on a different version from the rest, so record them in the CMDB. A node image must be completed within its 90-day validity period.
Case 3: automating approvals
Problem: Manual approvals often go unhandled overnight. Approach: Use an Azure Monitor alert (based on gate state in Resource Graph) to trigger a Logic App or Function. Run smoke tests and SLO checks against the canary cluster. If they pass, call az fleet gate approve (or the REST API). If they fail, stop the run and send a notification. Limits: Gates do not expire and cannot be approved in advance. If you need neither a manual nor an automated check, do not configure a gate.
Common errors and fixes
Update run status Pending, member message: Maintenance window is not open. Next opening: 2026-11-22T02:00:00Z
Cause: The member cluster has a maintenance window configured via aksManagedAutoUpgradeSchedule (Full/ControlPlaneOnly) or aksManagedNodeOSUpgradeSchedule (NodeImageOnly), and it is currently closed.
az aks maintenanceconfiguration list -g $RG --cluster-name aks-lab -o table
Fix: Wait for the window; or run az fleet updaterun skip … --targets Group:prod and handle that member separately. The long-term fix is to align the windows of members in the same group.
Member status Skipped: Cluster is already at the target node image version
Cause: During a NodeImageOnly run, all node pools on the member are already on the target image. This is not an error.
Fix: No action needed. To demonstrate a real upgrade, use Full with a --kubernetes-version higher than the current version (all members must be able to upgrade to that version).
Update run Failed: member 'aks-lab' failed: (UpgradeFailed) Drain node … failed when evicting pod … Cannot evict pod as it would violate the pod's disruption budget.
Cause: The node upgrade inside the member cluster was blocked by a PodDisruptionBudget (the single-cluster upgrade mechanics are covered in hour 6).
kubectl --context aks-lab get pdb -A
az aks show -g $RG -n aks-lab --query "agentPoolProfiles[].{pool:name, state:provisioningState}" -o table
Fix: Correct an overly strict PDB (for example, minAvailable equal to the replica count) or add replicas. Then restart with az fleet updaterun start; it resumes from the last unprocessed cluster.
(InvalidParameter) Approval gates can't be used with a One-by-one update sequence / gate not found
Cause: No stages were used (neither --stages nor --update-strategy-name was specified), or the gate was deleted along with the run.
Fix: Create the run with a strategy that includes stages. Get the gate name from az fleet gate list or from the last segment of gateId in the run JSON.
A cluster was upgraded outside of the Fleet run
Cause: The member kept AKS's own auto-upgrade channel (FAQ: whichever runs first, Fleet or AKS, executes), or the platform forced an upgrade after the version reached end of life.
Fix: On the member, run az aks update --auto-upgrade-channel none, and manage the node OS channel through the Fleet NodeImage configuration profile. Use an auto-upgrade profile to keep clusters within the supported window at all times.
1. Create a run that upgrades only the control plane to 1.37, using the staged strategy.
az fleet updaterun create -g rg-aks-lab --fleet-name fleet-aks-lab -n run-cp-137 \ --upgrade-type ControlPlaneOnly --kubernetes-version 1.37.x --update-strategy-name staged # Replace 1.37.x with the full patch version from az aks get-versions
2. Skip the prod group that is in Pending.
az fleet updaterun skip -g rg-aks-lab --fleet-name fleet-aks-lab -n run-nodeimage-1 --targets Group:prod
A stage has 3 groups with 4 clusters each, all using the default concurrency. Each cluster's node image upgrade takes about 30 minutes. Roughly how long does this stage take, and how can you shorten it without adding risk?
Groups run in parallel, and clusters within each group run one at a time: about 4 × 30 = 120 minutes (not counting maintenance windows and waiting). To shorten it, split the clusters into more groups (fewer members per group), or set a group-level maxConcurrency (preview) on groups where the risk is acceptable, and also set a stage-level limit as an overall cap. Keep canary stages small and slow, and speed up production stages after validation. Also confirm that each member's maintenance window is long enough.
Verified teaching videos
Official docs
- Safely update Kubernetes and node images across multiple clusters (concept)
- Update orchestration (how-to)
- Add approvals to update strategies
- Auto-upgrade profiles
- Fleet Manager FAQ
Video storyboard script (about 100 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
Visual: five cluster icons line up in a row, all flashing “Upgrading,” and one of them turns red.
Narration: If every cluster upgrades at the same time, a single problem becomes five incidents.
Visual: the clusters are arranged on two tiers of steps: the canary on top, production below. The production tier is split into two side-by-side groups.
Narration: Fleet uses stages to control order and groups to control parallelism. Clusters inside a group upgrade one after another by default.
Visual: after the canary finishes, a locked gate appears, and an engineer clicks “Approve.” Beside it, an hourglass counts down.
Narration: You can set approval gates and wait times between stages. Production stages start only when both conditions are met.
Visual: a production cluster shows “Maintenance window not open” and turns yellow to wait. The run keeps going with the next cluster in the same group.
Narration: Fleet respects each cluster's maintenance window. A blocked cluster waits, and it is never upgraded by force.
Module 5 · Platform Engineering: cluster templates, namespace self-service, and quotas
- Split platform capabilities into three layers: cluster templates (the AVM parameters from module 1), namespace templates (AKS managed namespaces or a GitOps platform repo), and application templates (Helm or Kustomize baselines).
- Use
az aks namespace addto create a managed namespace. Understand the meaning and defaults of--cpu-request/--cpu-limit/--memory-request/--memory-limit,--ingress-policy/--egress-policy,--adoption-policy, and--delete-policy. - Explain how ResourceQuota admission behaves (why “Pods without requests are rejected”) and the complementary role of LimitRange.
What: AKS managed namespace
A managed namespace is an ARM child resource of an AKS cluster, Microsoft.ContainerService/managedClusters/managedNamespaces. You declare the namespace's quotas, default network policy, and labels/annotations in Azure. A reconciling component in the cluster turns them into a Kubernetes Namespace, ResourceQuota, and NetworkPolicy, and blocks changes to these managed fields through the Kubernetes API. Access control uses Azure roles at two levels:
| Level | Built-in role | What it allows |
|---|---|---|
| Control plane (ARM) | Azure Kubernetes Service Namespace User | See the namespace in the portal, CLI, or ARM, and get connection credentials with az aks namespace get-credentials |
| Control plane (ARM) | Azure Kubernetes Service Namespace Contributor | Create and modify managed namespaces (used by the platform team or the self-service portal) |
| Data plane (Kubernetes) | Azure Kubernetes Service RBAC Reader / Writer / Admin | When scoped to …/managedNamespaces/<name>, it applies only within that namespace |
| Parameter | Allowed values | Default (az aks namespace add -h, tested on CLI 2.84) |
|---|---|---|
--ingress-policy | AllowAll / AllowSameNamespace / DenyAll | AllowSameNamespace |
--egress-policy | AllowAll / AllowSameNamespace / DenyAll | AllowAll |
--adoption-policy | Never / IfIdentical / Always | Never (do not adopt an existing namespace with the same name) |
--delete-policy | Keep / Delete | Keep (keep the Kubernetes namespace when the managed resource is deleted) |
--cpu-request/--cpu-limit/--memory-request/--memory-limit | Required | ResourceQuota applied to the namespace |
Why: why platform teams need self-service
- Ticket-based namespace requests can take days, so teams share the default namespace or ask for cluster-admin. Both break isolation and cost attribution.
- Quotas are the unit for capacity planning and cost allocation. A namespace's total requests correspond to the share of nodes its team should pay for (the scaling decisions in hour 4 are also based on requests).
- Denying cross-namespace inbound traffic by default (AllowSameNamespace) is the minimum network isolation for multi-tenancy.
How: how ResourceQuota takes effect at admission
- A Pod creation request passes through the ResourceQuota admission plugin in kube-apiserver, in the validation phase after webhooks such as Gatekeeper.
- If the quota includes compute resources such as
requests.cpuorlimits.memory, every container must declare the corresponding values, or the request is rejected:must specify limits.memory…. - It checks whether “used + this request” exceeds
hard, and rejects the request if it does:exceeded quota … requested: … used: … limited: …. - After it passes,
status.usedis updated. Note: the Deployment itself is always created successfully. What gets rejected is the ReplicaSet's request to create Pods. The symptom is a Deployment showing 0/N, and the error appears in the ReplicaSet's events. - LimitRange fills in default values for containers without requests or limits at an earlier mutating admission stage, so “quota + LimitRange” usually come as a pair.
When: managed namespace vs. GitOps platform repo vs. Fleet-managed namespace
| AKS managed namespace | GitOps platform repo (Namespace + Quota + NetworkPolicy + RoleBinding manifests) | Fleet-managed Fleet namespace (requires a hub) | |
|---|---|---|---|
| Where it is declared | ARM (CLI, Bicep, portal) | Git | Fleet hub |
| Access control | Azure RBAC, built-in roles | K8s RBAC or Azure RBAC | Across member clusters |
| Tamper resistance | Managed fields are blocked from changes through the K8s API | Flux drift correction (changes get reverted) | — |
| Best for | Single-cluster self-service, portal experience | Needs custom objects (LimitRange, PDB templates, default ServiceAccount) | Teams need same-named namespaces across multiple clusters |
kubectl top. ② “A successful Deployment creation means the quota is sufficient.” Pods are created by the ReplicaSet controller. When a Pod is rejected, the Deployment still exists, just with 0 available replicas. ③ “The default network policy works on any cluster.” The cluster must have a network policy engine configured (Cilium recommended). Otherwise, NetworkPolicy objects exist but have no effect. ④ “Managed namespaces can manage kube-system.” System namespaces (kube-system, gatekeeper-system, app-routing-system, and so on) cannot be managed.Diagram: the golden path for namespace self-service
Flowchart: the quota check a Pod creation request goes through
Interactive simulator: namespace quota admission calculator
Quota: requests.cpu = 1, limits.cpu = 2, requests.memory = 1Gi, limits.memory = 2Gi (matches the lab). Adjust the Pod spec and replica count, click “Scale to target replicas,” and watch how the ResourceQuota admission plugin judges each Pod. You can turn LimitRange defaults on or off.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks namespace add | Create managed namespace | Required: -g --cluster-name -n --cpu-request --cpu-limit --memory-request --memory-limit. Optional: policies, --labels a=b, --annotations, --tags |
az aks namespace update / show / list / delete | Manage | list --resource-group or --subscription to list across clusters |
az aks namespace get-credentials | Get namespace-scoped connection credentials | Requires the Namespace User role |
kubectl describe quota -n team-a | View used / hard | Basis for capacity and cost allocation |
kubectl describe rs -n team-a | Find quota rejection events | Check here first when a Deployment shows 0/N |
az aks namespace add -g $RG --cluster-name $CLUSTER -n team-a \
--cpu-request 1000m --cpu-limit 2000m --memory-request 1Gi --memory-limit 2Gi \
--ingress-policy AllowSameNamespace --egress-policy AllowAll \
--adoption-policy Never --delete-policy Delete \
--labels team=a cost-center=cc-1001
az aks namespace show -g $RG --cluster-name $CLUSTER -n team-a --query "{state:properties.provisioningState, quota:properties.defaultResourceQuota, net:properties.defaultNetworkPolicy}" -o json
{
"net": { "egress": "AllowAll", "ingress": "AllowSameNamespace" },
"quota": { "cpuLimit": "2000m", "cpuRequest": "1000m", "memoryLimit": "2Gi", "memoryRequest": "1Gi" },
"state": "Succeeded"
}
The same declaration written in Bicep (platform repo)
resource aks 'Microsoft.ContainerService/managedClusters@2025-10-01' existing = {
name: 'aks-lab'
}
resource teamA 'Microsoft.ContainerService/managedClusters/managedNamespaces@2025-09-01' = {
parent: aks
name: 'team-a'
location: resourceGroup().location
properties: {
defaultResourceQuota: { cpuRequest: '1000m', cpuLimit: '2000m', memoryRequest: '1Gi', memoryLimit: '2Gi' }
defaultNetworkPolicy: { ingress: 'AllowSameNamespace', egress: 'AllowAll' }
adoptionPolicy: 'Never'
deletePolicy: 'Delete'
labels: { team: 'a', 'cost-center': 'cc-1001' }
}
}
Grant access to the team
NS_ID=$(az aks namespace show -g $RG --cluster-name $CLUSTER -n team-a --query id -o tsv) GRP=$(az ad group show -g grp-team-a --query id -o tsv) # The team's Entra group (example name) az role assignment create --assignee-object-id $GRP --assignee-principal-type Group --role "Azure Kubernetes Service Namespace User" --scope $NS_ID az role assignment create --assignee-object-id $GRP --assignee-principal-type Group --role "Azure Kubernetes Service RBAC Writer" --scope $NS_ID # Team members: az aks namespace get-credentials -g $RG --cluster-name $CLUSTER -n team-a
Lab 5: Deliver a managed namespace to team-a and trigger a quota rejection (about 6 minutes)
Microsoft.Resources/deployments/*. Prerequisites: aks-lab has Azure RBAC enabled (hour 3), and the default network policy requires a network policy engine (Cilium from hour 2). Risk: --delete-policy Delete deletes everything inside the namespace when the managed resource is deleted.az aks namespace add from the “Commands” tab, then check the materialized objects in the cluster:
kubectl get ns team-a --show-labels kubectl get resourcequota,networkpolicy -n team-a
NAME STATUS AGE LABELS team-a Active 40s cost-center=cc-1001,kubernetes.io/metadata.name=team-a,team=a,… NAME AGE REQUEST LIMIT resourcequota/default 40s requests.cpu: 0/1, requests.memory: 0/1Gi limits.cpu: 0/2, limits.memory: 0/2Gi NAME POD-SELECTOR AGE networkpolicy.networking.k8s.io/default-… <none> 40s
kubectl label ns team-a team=b --overwrite
Error from server (Forbidden): … namespace "team-a" is managed by AKS managed namespaces; changes must be made through Azure Resource Manager
The exact error text may vary. The key point is that managed fields can only be changed through ARM (az aks namespace update).
kubectl create deployment web -n team-a --image=$ACR.azurecr.io/myapp:1.0 --replicas=2 --port=5000 kubectl get deploy web -n team-a kubectl describe rs -n team-a -l app=web | grep -A3 Events
NAME READY UP-TO-DATE AVAILABLE AGE web 0/2 0 0 15s Events: Warning FailedCreate … Error creating: pods "web-…" is forbidden: failed quota: default: must specify limits.cpu for: myapp; limits.memory for: myapp; requests.cpu for: myapp; requests.memory for: myapp
kubectl set resources deploy/web -n team-a --requests=cpu=250m,memory=128Mi --limits=cpu=500m,memory=256Mi kubectl scale deploy/web -n team-a --replicas=6 sleep 10; kubectl get deploy web -n team-a; kubectl describe quota -n team-a
NAME READY UP-TO-DATE AVAILABLE AGE web 4/6 4 4 2m Name: default Resource Used Hard -------- ---- ---- limits.cpu 2 2 limits.memory 1Gi 2Gi requests.cpu 1 1 requests.memory 512Mi 1Gi
Pods 5 and 6 are rejected because requests.cpu and limits.cpu are used up. This matches the results of the calculator on the Animation tab.
az aks namespace update -g $RG --cluster-name $CLUSTER -n team-a \ --cpu-request 2000m --cpu-limit 4000m --memory-request 1Gi --memory-limit 2Gi sleep 30; kubectl get deploy web -n team-a
az aks namespace delete -g $RG --cluster-name $CLUSTER -n team-a --yes # deletePolicy=Delete: the namespace and its contents are deleted together
Case 1: Consolidating from “one cluster per team” to a shared cluster
Problem: The company has 25 small teams, each with its own AKS cluster. Average CPU utilization is below 15%, and no one is responsible for patching or upgrades. Approach: The platform team uses AVM to build 3 shared clusters (one per environment), uses managed namespaces to provision space for teams, and converts quotas from team budgets. Teams deploy through namespace-scoped Flux configuration, and the cost analysis add-on allocates costs by namespace and labels. Limits: Strong isolation needs (compliance, different Kubernetes versions, privileged workloads) still require dedicated clusters. A shared cluster has a larger blast radius, so it needs staged Fleet upgrades and strict policies.
Case 2: Quotas make the HPA “fail”
Problem: During a promotion, the HPA calculated that 20 replicas were needed, but only 12 started. Approach: Investigation found exceeded quota events on the ReplicaSet. The platform raised the limits ceiling for the namespace and enabled an alert that notifies the team when used/hard > 80%. Quota changes go through PRs, and scale-ups “within budget” are approved automatically. Limits: Quotas are hard ceilings, so plan burst capacity in advance. You can set the limits quota generously and the requests quota tightly.
Case 3: Orphaned namespaces
Problem: Namespaces created by hand have no owner, and they hold on to requests for a long time. Approach: All new namespaces can only be created through managed namespaces or the platform repo (Azure Policy audits namespaces without a team label). Existing namespaces are brought under management gradually with --adoption-policy IfIdentical or Always. deletePolicy defaults to Keep, so deletion requires explicit confirmation. Limits: Always overwrites the existing configuration, so export the current state before adopting.
Common errors and fixes
pods "web-…" is forbidden: failed quota: default: must specify limits.memory for: myapp; requests.cpu for: myapp
Cause: The namespace has a compute resource quota, but the containers do not declare the corresponding requests and limits.
Fix: Declare the resources in the manifest, or have the platform place a LimitRange in the namespace to provide defaults (through the GitOps platform repo).
pods "web-…" is forbidden: exceeded quota: default, requested: requests.cpu=250m, used: requests.cpu=1, limited: requests.cpu=1
Cause: The namespace's total requests are used up.
kubectl describe quota -n team-a kubectl get pods -n team-a -o custom-columns=NAME:.metadata.name,CPU:.spec.containers[*].resources.requests.cpu
Fix: Lower oversized requests (based on actual usage), clean up Completed or Failed Pods, or adjust the quota with az aks namespace update.
(BadRequest) Managed namespace 'kube-system' is not allowed / namespace already exists and adoption policy is Never
Cause: System namespaces cannot be managed, or a namespace with the same name already exists and its adoptionPolicy is the default, Never.
Fix: Rename it. For existing namespaces, use --adoption-policy IfIdentical (adopt only if it matches the declaration) or Always (overwrite).
A team member runs az aks namespace get-credentials successfully, but kubectl get pods returns Forbidden
Cause: Only the control-plane role Namespace User was assigned, without a data-plane role. Or Azure RBAC is not enabled on the cluster.
Fix: Assign “Azure Kubernetes Service RBAC Writer/Reader” at the managed namespace scope, and confirm aadProfile.enableAzureRBAC = true.
NetworkPolicy is created, but cross-namespace access is not blocked
Cause: No network policy engine is configured on the cluster (networkProfile.networkPolicy is empty).
az aks show -g $RG -n $CLUSTER --query "networkProfile.{policy:networkPolicy, dataplane:networkDataplane}"
Fix: Enable Cilium or Azure Network Policy Manager (see hour 2).
1. List the managed namespaces of all clusters in resource group rg-aks-lab.
az aks namespace list --resource-group rg-aks-lab -o table
2. Change the default inbound policy of team-a to DenyAll.
az aks namespace update -g rg-aks-lab --cluster-name aks-lab -n team-a \ --cpu-request 1000m --cpu-limit 2000m --memory-request 1Gi --memory-limit 2Gi --ingress-policy DenyAll
Whether update requires you to repeat the quota parameters: check az aks namespace update -h. To be safe, pass them in too.
The platform needs to give 60 teams “ready-to-use” namespaces, including quotas, default inbound deny, LimitRange, PDB templates, and team-specific Flux configuration. How would you combine managed namespaces and GitOps?
Use managed namespaces (generated with a Bicep loop) for the parts that ARM can express and that need tamper protection: the namespace, quota, default network policy, labels, and the two Azure roles. Use the platform GitOps repo (cluster-scoped Flux configuration) to add objects such as LimitRange and default PDB or NetworkPolicy exceptions. Then create a namespace-scoped fluxConfiguration for each team that points to the team's repo. Requests come in through a PR or a portal form, with automatic checks for budget and naming rules. Azure Policy audits objects that do not meet the label and resource standards.
Verified teaching videos
Official docs
- How to use managed namespaces in AKS
- Managed namespaces overview
- Kubernetes Resource Quotas
- Limit Ranges
Video storyboard script (about 80 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
Visual: the ticket queue keeps growing, and beside it one team is crammed into the default namespace.
Narration: When namespaces depend on tickets, teams take shortcuts. Platform engineering's job is to make it self-service.
Visual: one request creates one Azure child resource, and in the cluster three blocks appear: a namespace, a quota, and a network policy.
Narration: A managed namespace delivers quotas, default network isolation, and permissions in one go, and they can only be changed through Azure.
Visual: the replica count goes from four to six, and the fifth Pod is blocked at the door with an “exceeded quota” pop-up.
Narration: Quota checks look at declared requests, not actual usage. When a deployment is stuck, check the ReplicaSet events first.
Module 6 · Backup and Restore: Azure Backup for AKS and Velero
- Describe the components of Azure Backup for AKS: the Backup vault, backup policies, the in-cluster backup extension (
microsoft.dataprotection.kubernetes, namespacedataprotection-microsoft), the blob container in the storage account, the snapshot resource group, and Trusted Access. - Distinguish the Operational tier (disk snapshots in the same region and your subscription, plus resource manifests in blob storage, taken at intervals as short as every 4 hours) from the Vault tier (the first successful backup each day is stored off-site; with GRS and cross-region restore, you can restore to the paired region).
- Complete one “back up → delete → restore to a new namespace” cycle, and choose the right Velero plugin version and identity method.
What: two approaches
| Azure Backup for AKS | Velero (open source) + velero-plugin-for-microsoft-azure | |
|---|---|---|
| In-cluster component | Backup extension (cluster extension, managed through ARM) | Velero Deployment + plugin initContainer (installed with Helm or CLI) |
| Control plane | Backup vault + backup policy + backup instance (Azure resources) | In-cluster CRDs: Backup, Schedule, Restore, BackupStorageLocation |
| Where resource manifests are stored | Blob container in the storage account you specify | Blob container that the BackupStorageLocation points to |
| Volume data | Azure Disk snapshots (snapshot resource group) and Azure Files (SMB) snapshots. The Vault tier supports only Azure Disk. | Azure Disk snapshots or CSI snapshots; file system backup is also possible |
| Off-site / immutable | Vault tier: off-site, enhanced soft delete, immutable vault, multi-user authorization, CMK. GRS + CRR restores to the paired region. | Configure storage redundancy and locks yourself |
| Frequency and retention | Operational: every 4, 6, 8, 12, or 24 hours; retention up to 360 days (Azure Files 30 days); up to 10 on-demand backups per instance per day | Any cron schedule |
| Monitoring | Azure Monitor alerts, Backup reports, Resource Graph | Prometheus metrics, self-built alerts |
Key limitations (support matrix as of 2026-10-31): only CSI volumes are supported (in-tree volumes are skipped). The cluster must use managed identity. The backup extension can only be installed on Ubuntu or Azure Linux node pools. The Backup vault must be in the same region as the cluster. kube-system, kube-node-lease, kube-public, and gatekeeper-system are not backed up. Do not install it together with Velero or any Velero-based solution, and do not put velero.io-prefixed labels or annotations on resources. Clusters that use Argo CD need application.resourceTrackingMethod: annotation+label.
Why: why back up when you already have GitOps
- Persistent volume data: databases and uploaded files are not in Git.
- Runtime-generated objects: Secrets created by operators, certificates, and manually created configuration that never made it into Git.
- Accidental deletion and ransomware:
kubectl delete nsor malicious wiping. The Vault tier's immutability and soft delete provide an isolated copy. - Migration: cross-cluster (for example, moving from a cluster on the old networking model to a new one), cross-subscription, and cross-region restore.
How: the flow of one Azure Backup run
- The policy triggers on schedule (the default template runs every 4 hours and keeps 7 days). The Backup vault interacts directly with the cluster through Trusted Access (role
Microsoft.DataProtection/backupVaults/backup-operator). - The backup extension enumerates objects according to the backup configuration (included or excluded namespaces, resource types, labels, whether to include cluster-scoped resources, and whether to snapshot volumes), and writes the manifests to the blob container. The extension's user identity needs Storage Blob Data Contributor.
- Snapshots are created for CSI volumes. Azure Disk snapshots go to the snapshot resource group. The cluster identity needs Contributor on it, and the vault needs Reader.
- Recovery points are formed. If the policy includes a Vault-tier retention rule, the first successful backup each day starts moving to the Vault tier within about 4 hours (disks up to 1 TB, up to 100 disks per instance).
- Restore: select a recovery point → generate a restore configuration (conflict policy Skip or Update, namespace mapping, whether to include volume data) → validate permissions → trigger. The target cluster must also have the extension installed and Trusted Access enabled.
When: which one to choose
- Azure-centric, needs compliance (immutability, MUA, reporting), needs cross-region restore → Azure Backup for AKS.
- Unified multi-cloud tooling, needs Velero's hooks or resource modifier ecosystem, or needs to back up to non-Azure storage → Velero (Velero v1.18.x with plugin v1.14.x; v1.19.x with v1.15.x).
- The two are either/or. Do not install both on the same cluster.
Diagram: components and permissions of Azure Backup for AKS
Flowchart: Operational tier and Vault tier
Step-by-step animation: data flow of backup and restore
Select a flow and an action, and watch the control flow (who calls whom) and the data flow (where manifests and snapshots are written). Logs show the matching real commands, CRD status, or job status (sample values).
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az dataprotection backup-vault create | Create Backup vault | --type SystemAssigned --storage-settings datastore-type="VaultStore" type="LocallyRedundant" (use GeoRedundant for cross-region restore) |
az dataprotection backup-policy get-default-policy-template --datasource-type AzureKubernetesService | Use the default policy | Default trigger PT4H, retention P7D. Add a Vault-tier rule with retention-rule create-lifecycle |
az k8s-extension create --extension-type microsoft.dataprotection.kubernetes | Install the backup extension | --configuration-settings blobContainer= storageAccount= storageAccountResourceGroup= storageAccountSubscriptionId= |
az aks trustedaccess rolebinding create | Enable Trusted Access | --roles Microsoft.DataProtection/backupVaults/backup-operator --source-resource-id <vault ID> |
az dataprotection backup-instance initialize-backupconfig / initialize / validate-for-backup / update-msi-permissions / create | Configure backup instance | --snapshot-resource-group-name. In the configuration, included_namespaces and snapshot_volumes |
az dataprotection backup-instance adhoc-backup | On-demand backup | --rule-name takes the backup rule name from the policy (the default template uses BackupHourly) |
az dataprotection backup-instance restore initialize-for-item-recovery / initialize-for-data-recovery / restore trigger | Restore (original cluster or another cluster) | namespace_mappings, conflict_policy, and persistent_volume_restore_mode in the restore configuration |
az dataprotection enable-backup trigger | One command does all of the above preparation | dataprotection extension ≥ 1.9.0; --backup-strategy Week|Month|DisasterRecovery|Custom |
velero install / backup create / restore create | Velero approach | Plugin velero/velero-plugin-for-microsoft-azure:v1.14.4 (for Velero 1.18.x) |
Velero (workload identity + AAD access to storage, per the plugin README)
# Run only on clusters where the Azure Backup extension is not installed (for example aks-lab-bicep) cat > credentials-velero <<EOF AZURE_SUBSCRIPTION_ID=$SUB AZURE_RESOURCE_GROUP=$RG AZURE_CLOUD_NAME=AzurePublicCloud EOF velero install \ --provider azure \ --service-account-name velero \ --pod-labels azure.workload.identity/use=true \ --plugins velero/velero-plugin-for-microsoft-azure:v1.14.4 \ --bucket velero \ --secret-file ./credentials-velero \ --backup-location-config useAAD="true",resourceGroup=$RG,storageAccount=$SA \ --snapshot-location-config apiTimeout=5m,resourceGroup=$RG velero backup create myapp-$(date +%Y%m%d%H%M) --include-namespaces myapp --wait velero backup describe --details | head -30
Prerequisites: create a user-assigned managed identity and a federated credential for Velero (subject system:serviceaccount:velero:velero). Grant the snapshot roles needed on the subscription or resource group, plus Storage Blob Data Contributor and Reader on the storage account (the plugin reads storage account properties to get the blob endpoint). The ServiceAccount needs the annotation azure.workload.identity/client-id. For the full steps, see “Option 3” in the plugin README.
Lab 6: Back up myapp and a namespace with a disk, delete it, then restore to a new namespace (about 15 minutes, including waiting for jobs)
kubectl create ns backup-demo
cat <<'EOF' | kubectl apply -n backup-demo -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata: { name: data }
spec: { accessModes: [ReadWriteOnce], storageClassName: managed-csi, resources: { requests: { storage: 1Gi } } }
---
apiVersion: v1
kind: Pod
metadata: { name: writer }
spec:
containers:
- name: w
image: mcr.microsoft.com/azurelinux/base/core:3.0
command: ["sh","-c","[ -f /data/created.txt ] || date > /data/created.txt; sleep 36000"]
volumeMounts: [{ name: d, mountPath: /data }]
resources: { requests: { cpu: 10m, memory: 16Mi }, limits: { memory: 32Mi } }
volumes: [{ name: d, persistentVolumeClaim: { claimName: data } }]
EOF
kubectl wait pod/writer -n backup-demo --for=condition=Ready --timeout=180s
kubectl exec -n backup-demo writer -- cat /data/created.txtVAULT=bv-aks-lab; SA=staksbk$RANDOM; SNAP_RG=rg-aks-lab-snap az group create -n $SNAP_RG -l $LOC az dataprotection backup-vault create -g $RG --vault-name $VAULT -l $LOC --type SystemAssigned \ --storage-settings datastore-type="VaultStore" type="LocallyRedundant" az dataprotection backup-policy get-default-policy-template --datasource-type AzureKubernetesService > akspolicy.json az dataprotection backup-policy create -g $RG --vault-name $VAULT -n aks-4h-7d --policy akspolicy.json az storage account create -n $SA -g $RG -l $LOC --sku Standard_LRS --kind StorageV2 az storage container create -n aks-backup --account-name $SA --auth-mode login
az k8s-extension create -g $RG -c $CLUSTER -t managedClusters --name azure-aks-backup \ --extension-type microsoft.dataprotection.kubernetes --scope cluster --release-train stable \ --configuration-settings blobContainer=aks-backup storageAccount=$SA storageAccountResourceGroup=$RG storageAccountSubscriptionId=$SUB EXT_PID=$(az k8s-extension show -g $RG -c $CLUSTER -t managedClusters -n azure-aks-backup --query aksAssignedIdentity.principalId -o tsv) az role assignment create --assignee-object-id $EXT_PID --assignee-principal-type ServicePrincipal \ --role "Storage Blob Data Contributor" --scope $(az storage account show -n $SA -g $RG --query id -o tsv) VAULT_ID=$(az dataprotection backup-vault show -g $RG --vault-name $VAULT --query id -o tsv) az aks trustedaccess rolebinding create -g $RG --cluster-name $CLUSTER -n backuprolebinding \ --roles Microsoft.DataProtection/backupVaults/backup-operator --source-resource-id $VAULT_ID kubectl get pods -n dataprotection-microsoft
az dataprotection backup-instance initialize-backupconfig --datasource-type AzureKubernetesService > bkcfg.json
python3 - <<'EOF'
import json; c=json.load(open('bkcfg.json')); c['included_namespaces']=['myapp','backup-demo']; c['include_cluster_scope_resources']=False
json.dump(c, open('bkcfg.json','w'), indent=1)
EOF
POLICY_ID=$(az dataprotection backup-policy show -g $RG --vault-name $VAULT -n aks-4h-7d --query id -o tsv)
az dataprotection backup-instance initialize --datasource-type AzureKubernetesService --datasource-id $AKS_ID \
--datasource-location $LOC --policy-id $POLICY_ID --backup-configuration ./bkcfg.json \
--friendly-name aks-lab-myapp --snapshot-resource-group-name $SNAP_RG > bi.json
az dataprotection backup-instance update-msi-permissions --datasource-type AzureKubernetesService --operation Backup \
--permissions-scope ResourceGroup --vault-name $VAULT -g $RG --backup-instance bi.json --yes
az dataprotection backup-instance validate-for-backup --backup-instance ./bi.json --ids $VAULT_ID
az dataprotection backup-instance create --backup-instance bi.json -g $RG --vault-name $VAULT
Permission changes take a few minutes to propagate. If validate fails, retry later.
BI=$(az dataprotection backup-instance list -g $RG --vault-name $VAULT --query "[0].name" -o tsv)
az dataprotection backup-instance adhoc-backup -g $RG --vault-name $VAULT --backup-instance-name $BI --rule-name BackupHourly
az dataprotection job list -g $RG --vault-name $VAULT --query "[].{op:properties.operation, status:properties.status, start:properties.startTime}" -o table
Op Status Start ------------------ ---------- ------------------------- OnDemandBackup Completed 2026-11-15T10:12:03Z
kubectl delete ns backup-demo --wait=true
RP=$(az dataprotection recovery-point list -g $RG --vault-name $VAULT --backup-instance-name $BI --query "[0].name" -o tsv)
az dataprotection backup-instance initialize-restoreconfig --datasource-type AzureKubernetesService > rcfg.json
python3 - <<'EOF'
import json; c=json.load(open('rcfg.json'))
c['included_namespaces']=['backup-demo']; c['namespace_mappings']={'backup-demo':'backup-demo-restore'}; c['include_cluster_scope_resources']=False
json.dump(c, open('rcfg.json','w'), indent=1)
EOF
az dataprotection backup-instance restore initialize-for-item-recovery --datasource-type AzureKubernetesService \
--restore-location $LOC --source-datastore OperationalStore --recovery-point-id $RP \
--restore-configuration rcfg.json --backup-instance-id $VAULT_ID/backupInstances/$BI > restore.json
az dataprotection backup-instance validate-for-restore -g $RG --vault-name $VAULT --backup-instance-name $BI --restore-request-object restore.json
az dataprotection backup-instance restore trigger -g $RG --vault-name $VAULT --backup-instance-name $BI --restore-request-object restore.json
# After the job completes:
kubectl get pvc,pod -n backup-demo-restore
kubectl exec -n backup-demo-restore writer -- cat /data/created.txt
NAME STATUS VOLUME CAPACITY STORAGECLASS persistentvolumeclaim/data Bound pvc-7f3c… 1Gi managed-csi NAME READY STATUS RESTARTS AGE pod/writer 1/1 Running 0 1m Sat Nov 15 10:05:41 UTC 2026
The file contents are the time the data was written before the backup (the startup command writes only if the file does not exist). This shows that the volume data came from the snapshot, not from a new empty disk.
kubectl delete ns backup-demo-restore az dataprotection backup-instance delete -g $RG --vault-name $VAULT -n $BI --yes # Stop protection first az aks trustedaccess rolebinding delete -g $RG --cluster-name $CLUSTER -n backuprolebinding --yes az k8s-extension delete -g $RG -c $CLUSTER -t managedClusters -n azure-aks-backup --yes az dataprotection backup-vault delete -g $RG --vault-name $VAULT --yes # Soft delete may block deletion for a short time; see Troubleshooting az group delete -n $SNAP_RG --yes --no-wait
Case 1: Migrating to a cluster with a new network model
Problem: The old cluster's network configuration cannot be changed in place, so it has to be migrated to a new AVM-baseline cluster. Approach: Build the new cluster with IaC → deploy stateless apps with Flux → install the backup extension on the new cluster and enable Trusted Access → run a “restore to another cluster” for stateful namespaces (initialize-for-data-recovery --target-resource-id) → validate, then switch DNS and traffic. Limits: If the two clusters' Kubernetes versions differ too much, the restore may warn or fail (deprecated APIs). Reserve a time window for disk snapshots and the restore.
Case 2: Regional disaster drill
Problem: Regulators require a yearly drill for regional failure recovery. Approach: The vault uses GeoRedundant with cross-region restore enabled, and the policy adds Vault-tier retention. A minimum-size cluster is pre-built with IaC in the paired region (canadaeast). During the drill, run recovery-point list --use-secondary-region true, restore from VaultStore, and provide a staging resource group and storage account. Limits: RPO is up to about 36 hours. The Vault tier supports only Azure Disk volumes and has size and count limits. Hydrated resources must be cleaned up manually.
Case 3: Velero conflicts with Azure Backup
Problem: A team installed Velero on a cluster that already had Azure Backup enabled, for extra backups. During restore, resources were processed twice and backups failed. Approach: As the support matrix requires, pick one. Keep Azure Backup, uninstall Velero, and clean up the velero.io-prefixed labels and annotations. Limits: If you need certain Velero hook capabilities, Azure Backup's restore configuration also supports restore hooks and resource modifier references, so evaluate that first.
Common errors and fixes
validate-for-backup fails: UserErrorMissingRoleAssignment / The Backup vault doesn't have required permissions on the snapshot resource group
Cause: The vault or cluster identity is missing roles on the cluster or the snapshot resource group.
az dataprotection backup-instance update-msi-permissions --datasource-type AzureKubernetesService --operation Backup \ --permissions-scope ResourceGroup --vault-name $VAULT -g $RG --backup-instance bi.json --yes
Fix: After the roles are added automatically, wait a few minutes and validate again. For manual assignment, follow the permissions list in the diagram.
Backup job fails: Trusted Access role binding not found / UserErrorTrustedAccessGatewayReturnedForbidden
Cause: The Trusted Access role binding was never created or was deleted by mistake, or the vault was recreated (the resource ID changed).
az aks trustedaccess rolebinding list -g $RG --cluster-name $CLUSTER -o table
Fix: Recreate the role binding with the current vault's resource ID.
Backup extension Pod CrashLoopBackOff: AuthorizationPermissionMismatch / This request is not authorized to perform this operation using this permission
Cause: The extension identity does not have Storage Blob Data Contributor on the storage account. Or the storage account has a firewall enabled, and the private cluster has no private endpoint.
kubectl logs -n dataprotection-microsoft -l app.kubernetes.io/name=dataprotection-microsoft-kubernetes --tail=50 2>/dev/null || kubectl get pods -n dataprotection-microsoft
Fix: Add the missing roles. For a private cluster, create a blob private endpoint for the storage account.
Restore job succeeds, but the PVC data is empty / objects did not change
Cause: The restore targeted a same-named namespace with conflict policy Skip, so existing objects were skipped. Or persistent_volume_restore_mode is RestoreWithoutVolumeData. Or the volume is an in-tree or static volume without a declared StorageClass, so it was skipped at backup time.
Fix: Use namespace_mappings to restore to a new namespace. Check the backup job details for skipped volumes, and migrate in-tree volumes to CSI.
Cannot delete the Backup vault: Cannot delete the Backup vault as there are existing backup instances or soft-deleted items
Cause: Backup instances still exist, or enhanced soft delete is retaining deleted items.
Fix: Delete the backup instances first. Soft-deleted items must wait until the retention period ends, or be permanently deleted when the relevant setting is enabled. For a lab vault, you can turn off soft delete at creation (not recommended for production). Finally, you can delete the whole resource group.
1. List all restore jobs on aks-lab.
az dataprotection job list-from-resourcegraph --datasource-type AzureKubernetesService \ --datasource-id $AKS_ID --operation Restore
2. Check whether the target cluster has Trusted Access enabled for the vault.
az aks trustedaccess rolebinding list -g rg-aks-lab --cluster-name aks-lab -o table
Business requirements: RPO ≤ 4 hours for accidental namespace deletion; RPO ≤ 48 hours for regional failure; backups must not be deletable by an administrator. Design an AKS backup approach.
Azure Backup for AKS: set the policy to Operational backups every 4 hours (retain 7 to 14 days) to cover accidental deletion. Add a Vault-tier retention rule (the first successful backup each day, retained 30 to 90 days). Use GeoRedundant with cross-region restore for the vault. The paired-region RPO of up to about 36 hours meets the 48-hour target. Enable immutability (locking), enhanced soft delete, and multi-user authorization (Resource Guard) on the vault, so no single administrator can delete backups. Pre-provision a recovery cluster in the paired region with IaC that can scale up quickly. Drill restores every quarter and record the RTO. Note that the Vault tier supports only Azure Disk volumes, so Azure Files volumes need a separate design.
Verified teaching videos
Official docs
- Back up AKS using Azure CLI
- Restore AKS using Azure CLI
- AKS backup support matrix
- velero-plugin-for-microsoft-azure
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
Visual: the Git repository is intact, but a database disk icon cracks.
Narration: GitOps can rebuild what you declare, but it cannot rebuild data. Backup is the last line of defense.
Visual: the Backup vault connects through a “Trusted Access” line to the extension in the cluster. The extension writes manifests to a storage account and puts disk snapshots in the snapshot resource group.
Narration: The vault does not pull data directly. It directs the backup extension in the cluster. Manifests and snapshots both stay in your own subscription.
Visual: the first recovery point of each day is copied to an off-site vault, and an arrow points to the paired region.
Narration: If you need off-site and immutable copies, add the Vault tier. Note that it transfers only once a day, so cross-region recovery points will be older.
Module 7 · Policy as Code and Compliance Automation
- Describe the two paths of Azure Policy for Kubernetes: admission (Gatekeeper validating or mutating webhooks, or ValidatingAdmissionPolicy generated from CEL policies) and audit (a full scan every 15 minutes, reporting back to Azure Policy compliance).
- Use
az aks safeguards create/updateto enable Deployment Safeguards at the Warn or Enforce level, and set Pod Security Standards levels. Understand the default values of its mutator. - Write policy assignments (built-in definitions, parameters, excluded namespaces, exemptions) as Bicep or Terraform, and plan a rollout of “Audit → Warn → Deny.”
What: components and objects
| Component | Location | Responsibility |
|---|---|---|
| azure-policy Pod | kube-system | Every 15 minutes, checks for assignment changes with the Azure Policy service and creates, updates, or deletes ConstraintTemplates and Constraints. Every 15 minutes, runs a full scan and reports compliance results. |
| Gatekeeper (OPA) | gatekeeper-system | Validating webhook (validation.gatekeeper.sh), mutating webhook, audit controller (audit.gatekeeper.sh) |
| ValidatingAdmissionPolicy (VAP) | Inside the kube-apiserver process | Azure policies containing CEL can generate VAPs on K8s 1.30+. They are evaluated in-process with lower latency, and can fail-close (from Arc extension 1.18.1; AKS add-on support follows the official documentation). |
| Azure Policy definition | ARM | Mode Microsoft.Kubernetes.Data; effects audit / deny / disabled / mutate; details.templateInfo carries the ConstraintTemplate as a URI or Base64 |
| Deployment Safeguards | AKS feature (based on the Azure Policy add-on) | A set of preset best-practice policies and mutators, at Warn or Enforce levels. You can set the PSS level and excluded namespaces. |
By default, the add-on excludes kube-system and gatekeeper-system from evaluation. The docs recommend also excluding azure-arc in the assignment parameters (for Arc scenarios). The Arc version of the extension, 1.21.0 (2026-11), corresponds to Gatekeeper 3.23.1. To check the actual version of the AKS add-on, use kubectl get pod -n gatekeeper-system -o jsonpath='{..image}'.
Policies included in Deployment Safeguards (docs as of 2026-06)
| Policy | Change under Enforce (if any) |
|---|---|
| Cannot Edit Individual Nodes | — |
| Containers must define CPU and memory requests | When missing, set to 500m / 2048Mi (requests = limits). Raised to 100m / 100Mi if below the minimum. |
| Multi-replica workloads must have anti-affinity or topologySpreadConstraints | Adds preferred anti-affinity with weight 100, and maxSkew: 1, ScheduleAnyway topology spread (by hostname) |
| No AKS Specific Labels / Reserved System Pool Taints | Removes the CriticalAddonsOnly taint from user node pools |
| Only allowed images; readiness and liveness probes required; CSI StorageClass required; Service selectors must be unique; images must not use the latest tag | — |
AKS Automatic: Safeguards default to Enforce and cannot be changed to Warn; PSS defaults to Baseline. AKS Standard: Warn or Enforce is optional; PSS defaults to Privileged and can be set to Baseline or Restricted. Safeguards is all or nothing. You cannot pick individual policies or customize the mutators.
Why: why “policy as code”
- Reviews and documentation cannot stop a
kubectl applyat 3 a.m. Admission policies catch it centrally at the API server entry point. - Compliance needs evidence. The Azure Policy compliance view rolls up the status of every cluster and resource to the subscription and management group level.
- Policies can be wrong too. Put them in Git, review them in PRs, and roll them out per environment (dev Warn → prod Deny), with the same rigor as application releases.
How: the decision order for a request
- Authentication → authorization (Azure RBAC, module 3).
- Mutating admission: Safeguards mutators at Enforce, Gatekeeper mutation, LimitRanger, and other components that modify the object.
- Object schema validation.
- Validating admission: VAP (in-process), the Gatekeeper validating webhook (deny rejects; Warn returns a
Warning:header), and ResourceQuota. - Written to etcd. Afterward, the audit controller periodically scans existing objects, and azure-policy reports results to Azure Policy every 15 minutes, so the compliance view lags.
When: rollout cadence and tool choice
| Stage | Azure Policy effect / Safeguards level | Goal |
|---|---|---|
| Weeks 1–2 | Audit / Warn | Collect a list of violations and notify teams to fix their templates |
| Week 3 | dev/staging: Deny / Enforce; prod: Warn | Validate in non-production so nothing gets hit by accident |
| From week 4 | prod: Deny / Enforce, with exemptions managed using exemptions that have an expiry date | Ongoing |
| Azure Policy add-on / Safeguards | Self-installed Gatekeeper | Kyverno (OSS, latest v1.20.0 as of 2026-11) | Native VAP | |
|---|---|---|---|---|
| Management plane | ARM, cross-subscription compliance view | In-cluster CRDs | In-cluster CRDs | In-cluster objects |
| Policy language | Rego (built-in definitions), CEL | Rego | YAML/CEL | CEL |
| Mutate / generate | Limited mutation | Supports mutation | Strong (mutate and generate) | MutatingAdmissionPolicy (newer) |
| Used together with Azure Policy | — | Conflicts (the add-on bundles its own Gatekeeper) | Can coexist, but avoid overlapping rules | Can coexist |
Diagram: the two paths of Azure Policy for AKS
Flowchart: rolling out Audit → Warn → Deny
Interactive simulator: admission decision for a Deployment request
Select the manifest problems and the Safeguards level, then click “Submit kubectl apply.” Below, each step of the admission chain is shown with the real returned messages (error text from the official docs). “Fast-forward 15 minutes” shows how the audit scan reports existing violating objects to Azure Policy.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az aks enable-addons --addons azure-policy | Enable Azure Policy add-on | Requires registering Microsoft.PolicyInsights. The AVM module enables it by default. |
az aks safeguards create / update / show / delete | Deployment Safeguards | --level Warn|Enforce, --excluded-ns ns1 ns2, --pss-level Baseline|Restricted|Privileged. You can also use --cluster <resource ID>. |
az policy definition list --query "[?displayName=='…']" | Find built-in definitions by display name | Built-in definition IDs are GUIDs. Do not hard-code them from memory. |
az policy assignment create | Assign to a cluster or resource group | --policy, --scope, --params (effect, excludedNamespaces) |
az policy state list / trigger-scan | Query compliance / trigger evaluation | Kubernetes results are still subject to the add-on's 15-minute reporting cycle |
kubectl get constrainttemplates,constraints | Policies landed in the cluster | Names look like azurepolicy-k8sazurev… |
kubectl apply --dry-run=server | Pre-check admission in CI | Passes through admission webhooks, but is not persisted |
az aks safeguards create -g $RG -n $CLUSTER --level Warn --excluded-ns flux-system cluster-config dataprotection-microsoft az aks safeguards show -g $RG -n $CLUSTER -o json | head -20
Write the policy assignment in Bicep (resource group scope)
targetScope = 'resourceGroup'
@description('Built-in definition ID, looked up by CI from the display name and passed in')
param noPrivilegedDefinitionId string
param effect string = 'Audit' // Audit → Deny is controlled by the environment parameter file
resource noPriv 'Microsoft.Authorization/policyAssignments@2024-04-01' = {
name: 'aks-no-privileged'
properties: {
displayName: 'AKS: Disallow privileged containers'
policyDefinitionId: noPrivilegedDefinitionId
parameters: {
effect: { value: effect }
excludedNamespaces: { value: [ 'kube-system', 'gatekeeper-system', 'flux-system' ] }
}
enforcementMode: 'Default'
}
}
DEF=$(az policy definition list --query "[?displayName=='Kubernetes cluster should not allow privileged containers'].id | [0]" -o tsv) echo $DEF az deployment group what-if -g $RG -f policy.bicep -p noPrivilegedDefinitionId=$DEF effect=Audit
How to verify: Within 15 minutes, kubectl get constraints shows the corresponding constraint. Common errors: Built-in definition parameter names vary by definition, so check them first with az policy definition show --name <GUID> --query parameters. The excludedNamespaces parameter overrides the default value, so include the system namespaces as well. Production use: At scale, assign an Initiative (for example, a Pod security baseline) at the management group scope, and refer to the open-source Enterprise Policy as Code (EPAC) organization repo.
Lab 7: Deployment Safeguards from Warn to Enforce (about 8 minutes)
az aks show -g $RG -n $CLUSTER --query "addonProfiles.azurepolicy.enabled" -o tsv || true az aks enable-addons -g $RG -n $CLUSTER --addons azure-policy # if the previous command did not return true kubectl get pods -n kube-system -l app=azure-policy; kubectl get pods -n gatekeeper-system
az aks safeguards create -g $RG -n $CLUSTER --level Warn \ --excluded-ns flux-system cluster-config dataprotection-microsoft
Constraint sync takes time (up to about 15 minutes). You can watch it with kubectl get constrainttemplates | grep -i azurepolicy.
kubectl create ns policy-demo kubectl create deployment bad -n policy-demo --image=nginx --replicas=2
Warning: [azurepolicy-k8sazurev1antiaffinityrules-…] Deployment with 2 replicas should have either podAntiAffinity or topologySpreadConstraints set to avoid disruptions due to nodes crashing Warning: [azurepolicy-k8sazurev2containerenforceprob-…] Container nginx in your Pod bad-… has no livenessProbe. Required probes: readinessProbe, livenessProbe Warning: [azurepolicy-k8sazurev1containernolatestima-…] Please specify an explicit, versioned image tag such as '1.0' for container nginx. … Warning: [azurepolicy-k8sazurev1containerrequests-…] container nginx has no resource requests deployment.apps/bad created
kubectl get constraints -o custom-columns=NAME:.metadata.name,VIOLATIONS:.status.totalViolations | head -20
You will notice that redis has no probes. The correct fix is in Git: add a tcpSocket probe to apps/myapp/redis.yaml and push it, rather than running kubectl edit.
readinessProbe: { tcpSocket: { port: 6379 } }
livenessProbe: { tcpSocket: { port: 6379 }, initialDelaySeconds: 10 }az aks safeguards update -g $RG -n $CLUSTER --level Enforce --excluded-ns flux-system cluster-config dataprotection-microsoft
kubectl create deployment bad2 -n policy-demo --image=nginx --replicas=2
kubectl create deployment ok -n policy-demo --image=$ACR.azurecr.io/myapp:1.1 --replicas=2 --dry-run=client -o yaml > ok.yaml
# After adding probes to ok.yaml:
kubectl apply -f ok.yaml
kubectl get deploy ok -n policy-demo -o jsonpath='{.spec.template.spec.containers[0].resources}{"\n"}{.spec.template.spec.topologySpreadConstraints}{"\n"}'
error: failed to create deployment: admission webhook "validation.gatekeeper.sh" denied the request: [azurepolicy-k8sazurev1containernolatestima-…] Please specify an explicit, versioned image tag …
deployment.apps/ok created
{"limits":{"cpu":"500m","memory":"2Gi"},"requests":{"cpu":"500m","memory":"2Gi"}}
[{"labelSelector":{"matchLabels":{"app":"ok"}},"maxSkew":1,"topologyKey":"kubernetes.io/hostname","whenUnsatisfiable":"ScheduleAnyway"}]
The ok deployment, which had no requests, was filled in with 500m / 2Gi by the mutator, and topology spread was added automatically. Note that the 2Gi default can cause Pending on small nodes. This is why setting your own requests is better than relying on the mutator.
kubectl delete ns policy-demo az aks safeguards delete -g $RG -n $CLUSTER --yes
Case 1: The blind spot behind a “100% compliant” privileged container rule
Problem: The compliance report showed every cluster meeting “Disallow privileged containers,” yet a penetration test still found a privileged Pod in one namespace. Approach: Investigation found that a team namespace had been added to the excludedNamespaces parameter of the assignment as a “temporary fix” to get a release out. The fix: keep only system namespaces in the exclusion list, handle exceptions with Azure Policy exemptions instead (with an expiry and an approval record), and require security-team approval for parameter changes through CODEOWNERS in the policy repo. Limits: Exemptions are ARM-level objects and still need periodic review.
Case 2: On the day Enforce went live, all of GitOps became Non-Compliant
Problem: The platform turned on Safeguards Enforce directly in production. On its next reconciliation, Flux failed because of admission rejections, and several apps got stuck on old versions. Approach: Roll back to Warn. Add a kubectl apply --dry-run=server pre-check in CI (against the staging cluster). After teams fix their lists, switch environment by environment. Exclude Flux's own namespace. Limits: Safeguards cannot pick individual rules. Rules that truly cannot be met can only be handled by excluding namespaces or by assigning separate built-in policies.
Case 3: Policy sync delay makes a new policy “untestable right after assignment”
Problem: After the security team assigned a new policy, they tested it right away, found that violating objects could still be created, and concluded the policy had failed. Approach: Explain that the add-on syncs assignments every 15 minutes. Use kubectl get constrainttemplates to confirm the constraint has landed before testing, and add a “wait for the constraint to appear” check to the release process. Limits: Compliance reports also have a periodic delay, so incident response should rely on real-time signals in the cluster.
Common errors and fixes
Error from server (Forbidden): admission webhook "validation.gatekeeper.sh" denied the request: [azurepolicy-k8sazurev1antiaffinityrules-…] Deployment with 2 replicas should have either podAntiAffinity or topologySpreadConstraints set
Cause: Safeguards Enforce (or the corresponding Deny policy) rejected the request. Under Enforce, the mutator usually fills in the missing fields automatically. If the workload already has some affinity settings or its labels are not recognized, it is not mutated.
Fix: Set topologySpreadConstraints or podAntiAffinity explicitly in the manifest, and pre-check in CI with --dry-run=server.
Deployment Safeguards is enabled, but no warnings appear
Cause: Constraints have not synced yet (up to about 15 minutes); the namespace is excluded; or the Azure Policy add-on is not enabled.
az aks safeguards show -g $RG -n $CLUSTER -o json kubectl get constrainttemplates | grep -c azurepolicy kubectl logs -n kube-system -l app=azure-policy --tail=30
Fix: Wait for the sync and confirm the ConstraintTemplate exists; check the exclusion list.
Pod Pending: 0/3 nodes are available: Insufficient memory (appears after Enforce)
Cause: The Safeguards mutator sets a 2048Mi memory request on containers that do not declare requests.
kubectl get pod -n NS POD -o jsonpath='{.spec.containers[*].resources}'
Fix: Declare reasonable requests/limits in the manifest, or use a LimitRange to provide smaller defaults. Whether LimitRanger runs before or after the Gatekeeper mutator depends on admission order, so declaring values explicitly is the most reliable option.
(Conflict) Azure Policy Add-on and Gatekeeper installed by user cannot co-exist / two controllers appear in gatekeeper-system
Cause: Open-source Gatekeeper was installed with Helm on a cluster where the add-on is already enabled.
Fix: Choose one: keep the add-on and uninstall the self-installed Gatekeeper; or convert custom Rego rules into Azure Policy custom definitions (templateInfo references the ConstraintTemplate).
In the policy compliance view, Kubernetes resources show “Not started / Not evaluated”
Cause: The new assignment has not finished its first evaluation yet, or the add-on could not report while the cluster was stopped (az aks stop).
Fix: Start the cluster and wait for at least one 15-minute cycle. az policy state trigger-scan -g $RG only triggers evaluation at the ARM layer; Kubernetes results still depend on the add-on reporting back.
1. Turn on Safeguards at Warn level, and set PSS to Baseline.
az aks safeguards update -g rg-aks-lab -n aks-lab --level Warn --pss-level Baseline
2. Check the number of violations for each constraint in the cluster.
kubectl get constraints -o custom-columns=NAME:.metadata.name,ENFORCEMENT:.spec.enforcementAction,VIOLATIONS:.status.totalViolations
The security team requires “no privileged containers, no latest tag, and requests must be set in production clusters.” The platform team is concerned this will affect Flux and the backup extension. Provide a rollout plan.
Step 1: In the policy repo, assign the three built-in policies in Audit mode (or turn on Safeguards at Warn in dev). Exclude kube-system, gatekeeper-system, and any platform namespaces that have been reviewed and are truly needed (flux-system, dataprotection-microsoft), and record the reasons. Collect two weeks of compliance data and fix the application templates. In CI, run a server dry-run against staging. After dev and staging have run in Deny/Enforce for one week without issues, move production to Warn first, then Deny. Use exemptions with an expiry date for exceptions. Track the compliance rate with a daily Resource Graph report. Remember that Gatekeeper fails open, so pair it with runtime detection from Defender for Containers.
Verified teaching videos
Official docs
- Understand Azure Policy for Kubernetes clusters
- Use Deployment Safeguards
- Azure Policy built-in definitions for AKS
- Gatekeeper: failing closed considerations
Video storyboard (about 90 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
Visual: A PDF “deployment standard” is dropped into the trash, while kubectl apply runs beside it.
Narration: A standard written in a document cannot stop a single deployment. The rules must sit in the API server's admission chain.
Visual: The request passes through the mutator (which fills in requests automatically), then Gatekeeper (a red reject), then quota, and finally is written to etcd.
Narration: Mutating admission changes the object first, then validating admission decides whether to allow or reject it. Warn level only shows a warning. Enforce level rejects and rewrites the request.
Visual: A fifteen-minute clock turns, and existing violating objects in the cluster are rolled up into the Azure compliance dashboard.
Narration: The audit scans existing objects every fifteen minutes and reports back to Azure Policy. Audit first, then warn, and only then deny. That is the safe way to roll this out.
Module 8 · Summary, self-check and cleanup for the first five hours
- Use one layered diagram to explain where each capability from the first five hours sits in “cluster as code”: cluster (IaC) → networking and identity (hours 2–3) → scaling (hour 4) → delivery, orchestration, backup and policy (this hour).
- Clean up in dependency order: update runs → Fleet members → Fleet; backup instances → Trusted Access → backup extension → vault; Flux configuration → Flux extension; Safeguards; finally the cluster and the resource group.
- Use the troubleshooting tree to locate six kinds of automation failure: IaC deployment, GitOps non-compliance, pipeline authentication, Fleet stuck, backup failure, and policy rejection.
What: the big picture of the first five hours
| Hour | Core question | How this hour becomes code |
|---|---|---|
| Hour 1 | What happens behind az aks create | The same PUT is sent by the AVM module (module 1) |
| Hour 2 | Networking: overlay, outbound, ingress | networkPlugin/Mode/Dataplane/Policy and CIDRs written into parameter files; default network policies for managed namespaces depend on the policy engine |
| Hour 3 | Identity: Entra, Workload Identity, Key Vault | aadProfile, disableLocalAccounts, OIDC; pipelines also use federated credentials (module 3) |
| Hour 4 | Scaling: CA, NAP, KEDA | Autoscaling settings are written into AVM parameters; quotas cap scaling (module 5) |
| Hour 5 | Automated operations | GitOps delivery, Fleet orchestration, managed namespaces, backup, policy |
Why: why cleanup discipline matters
- Lab resource costs often come from forgotten side resources: disk snapshots in the snapshot resource group, soft-deleted items in the Backup vault, the Fleet hub (if enabled), and extra clusters.
- Deleting in the wrong order causes failed deletions or orphaned resources. For example, deleting the extension before the Flux configuration leaves the cluster in an unstable state (the official docs require deleting the configuration first). A vault that still has backup instances cannot be deleted.
How: the cleanup dependency order
- Fleet: delete the update run (including its approval gates) → delete the members → delete the Fleet (along with its auto-upgrade profile and policies).
- Backup: delete the backup instances (this stops protection) → delete the Trusted Access role binding → delete the backup extension → delete the vault (watch for soft delete) → delete the snapshot resource group and storage account.
- Policy:
az aks safeguards delete; delete this hour's policy assignments. - GitOps:
az k8s-configuration flux delete(prune deletes the myapp objects, so keep them if you need them) →az k8s-extension delete -n flux. - Cluster:
az aks delete -n aks-lab-bicep; if you will keep studyingaks-labtomorrow, stop it withaz aks stopinstead. - When everything is finished:
az group delete -n rg-aks-lab --yes --no-wait(andrg-aks-lab-snap).
When: keep or delete
| Resource | Continue to hour 6? | Recommendation |
|---|---|---|
aks-lab + ACR | Needed | Keep; when pausing your study, use az aks stop |
| Flux configuration and myapp | Reusable | Keep (during the hour 6 upgrade, you can watch GitOps app availability) |
aks-lab-bicep, Fleet | Not needed | Delete |
| Backup vault, storage, snapshot RG | Not needed | Delete |
| Safeguards, team-a | Not needed | Delete, so it does not affect later labs |
Layered diagram: cluster as code
Dependency diagram: cleanup order
Interactive tool: generate a cleanup script in dependency order
Check the resources you actually created in this course, and the tool will generate commands in dependency order (with explanations). “Check for leftovers” lists objects that are easy to forget, including those outside the resource group. The commands match this hour's variables ($RG, $CLUSTER, $VAULT, etc.).
# The cleanup script will appear here
Inventory and cleanup commands
| Command | Purpose | Notes |
|---|---|---|
az resource list -g $RG -o table | Inventory resources in the resource group | Compare against this hour's creation list |
az k8s-extension list -g $RG -c $CLUSTER -t managedClusters -o table | Inventory cluster extensions | flux, azure-aks-backup, argocd |
az k8s-configuration flux list -g $RG -c $CLUSTER -t managedClusters -o table | Inventory GitOps configurations | Delete configurations before extensions |
az fleet list -g $RG -o table | Inventory Fleet | A Fleet without a hub has no nodes |
az dataprotection backup-instance list -g $RG --vault-name $VAULT -o table | Inventory protected instances | Stop protection before the vault can be deleted |
az snapshot list -g rg-aks-lab-snap -o table | Inventory disk snapshots | Cross-resource-group, easiest to forget |
az aks stop -g $RG -n $CLUSTER | Pause the cluster | Next time: az aks start |
az group delete -n $RG --yes --no-wait | Delete everything | Cannot be recovered |
# Resources added in this hour (for comparison)
az aks list -g $RG --query "[].{name:name, state:powerState.code}" -o table
az fleet list -g $RG -o table
az dataprotection backup-vault list -g $RG -o table
az identity list -g $RG --query "[].name" -o tsv
az group list --query "[?starts_with(name,'rg-aks-lab')].name" -o tsv
Lab 8: Delete this hour's resources in dependency order (about 10 minutes; deletion runs in the background)
aks-lab, ACR, the Flux configuration and myapp.FLEET=fleet-aks-lab for r in $(az fleet updaterun list -g $RG --fleet-name $FLEET --query "[].name" -o tsv); do az fleet updaterun delete -g $RG --fleet-name $FLEET -n $r --yes; done az fleet autoupgradeprofile delete -g $RG --fleet-name $FLEET -n nodeimage-weekly --yes 2>/dev/null || true for m in $(az fleet member list -g $RG --fleet-name $FLEET --query "[].name" -o tsv); do az fleet member delete -g $RG --fleet-name $FLEET -n $m --yes; done az fleet delete -g $RG -n $FLEET --yes
VAULT=bv-aks-lab for bi in $(az dataprotection backup-instance list -g $RG --vault-name $VAULT --query "[].name" -o tsv); do az dataprotection backup-instance delete -g $RG --vault-name $VAULT -n $bi --yes; done az aks trustedaccess rolebinding delete -g $RG --cluster-name $CLUSTER -n backuprolebinding --yes az k8s-extension delete -g $RG -c $CLUSTER -t managedClusters -n azure-aks-backup --yes az dataprotection backup-vault delete -g $RG --vault-name $VAULT --yes az storage account delete -g $RG -n $SA --yes az group delete -n rg-aks-lab-snap --yes --no-wait kubectl delete ns backup-demo-restore --ignore-not-found
az aks safeguards delete -g $RG -n $CLUSTER --yes 2>/dev/null || true az aks namespace delete -g $RG --cluster-name $CLUSTER -n team-a --yes 2>/dev/null || true az policy assignment delete -n aks-no-privileged -g $RG 2>/dev/null || true
az aks delete -g $RG -n aks-lab-bicep --yes --no-wait az identity delete -g $RG -n id-aks-deployer kubectl config delete-context aks-lab-bicep 2>/dev/null || true
# Continue to hour 6: keep Flux and myapp, only pause the cluster az aks stop -g $RG -n $CLUSTER # Finish everything: first delete the GitOps configuration and extension (optional), then the resource group # az k8s-configuration flux delete -g $RG -c $CLUSTER -t managedClusters -n cluster-config --yes # az k8s-extension delete -g $RG -c $CLUSTER -t managedClusters -n flux --yes # az group delete -n $RG --yes --no-wait
az resource list -g $RG --query "[].{type:type,name:name}" -o table
az group exists -n rg-aks-lab-snap
Type Name -------------------------------------------- ------------ Microsoft.ContainerService/managedClusters aks-lab Microsoft.ContainerRegistry/registries acraks12345 Microsoft.ManagedIdentity/userAssignedIdentities id-myapp … false
Case 1: The platform team's “day two” weekly report
Problem: More and more clusters, and management wants to know “are we in a controllable state.” Approach: Use Azure Resource Graph to generate four weekly metrics: Flux configuration compliance rate (kubernetesconfigurationresources), Fleet update run success rate and number in flight, backup job success rate, and policy compliance rate. If any metric falls below its threshold, a ticket is opened automatically. Limits: Resource Graph data has a delay of minutes. Field structures change with API versions, so queries should go through code review.
Case 2: One-click onboarding for a new cluster
Problem: Building a new production cluster takes two weeks, and the steps are scattered across several teams. Approach: Chain this hour's modules into one pipeline: AVM deployment (including Flux extension parameters and Azure Policy) → join the Fleet (specify an update group or labels) → enable Azure Backup (az dataprotection enable-backup trigger --backup-strategy DisasterRecovery) → turn on Safeguards at Warn → the platform GitOps repo delivers the baseline → create managed namespaces for teams. Limits: Each step needs different permissions, so split the pipeline identity by step to avoid one identity holding every permission.
Case 3: Runaway costs in a lab subscription
Problem: One month after training ended, the lab subscription was still generating charges. Approach: Bill analysis found snapshot resource groups and soft-deleted items in the vault. The fix: tag all lab resources with course, run a script every night that lists tagged resources and sends reminders, and set budget alerts on the resource groups. Limits: Soft-deleted backups must wait for the retention period to end before they are fully cleaned up.
Interactive troubleshooting tree: automation operations failures
Common errors during cleanup
(ResourceGroupDeletionBlocked) / Cannot delete resource while nested resources exist (vault)
Cause: The Backup vault still has backup instances or soft-deleted items.
Fix: Delete the backup instances first. Check the vault's soft-delete settings and deleted items, then wait for the retention period, or permanently delete them where allowed.
az k8s-extension delete hangs / namespace stuck in Terminating after the Flux extension is deleted
Cause: The extension was deleted before the configuration, so nothing is handling the finalizers on the Flux objects.
kubectl get fluxconfigs,kustomizations,gitrepositories -A
kubectl get ns cluster-config -o jsonpath='{.spec.finalizers}{"\n"}'
Fix: Follow the official order: run az k8s-configuration flux delete first, then delete the extension. If it is already stuck, reinstall the extension so the controller can handle the finalizers, then delete in order.
(MemberClusterNotFound) After deleting aks-lab-bicep, the Fleet member shows a failed state
Cause: The cluster was deleted before its member.
Fix: Run az fleet member delete to clean up the broken member. In future, follow the order “member → cluster.”
1. List all cluster extensions on aks-lab and their versions.
az k8s-extension list -g rg-aks-lab -c aks-lab -t managedClusters --query "[].{name:name,type:extensionType,version:version}" -o table2. Stop only aks-lab and keep all configuration.
az aks stop -g rg-aks-lab -n aks-lab
In one paragraph, explain to a new colleague why this hour hands the “cluster” to IaC, the “applications” to GitOps, and the “upgrade order” to Fleet, instead of putting everything in one pipeline.
The three have different lifecycles and failure modes. Clusters change rarely but with large impact, so they need what-if/plan review and ARM auditing. Applications change often and need continuous reconciliation and drift repair, and the pipeline should not hold cluster permissions. Upgrade order spans several clusters and maintenance windows, so it needs long-running orchestration that can pause, require approval, and retry. One pipeline that couples all three leads to excessive permissions, failures that are hard to retry, and state that never converges. With layering, each layer has its own declaration, controllers and observability metrics.
Verified teaching videos
Official docs
- Kubernetes versions supported in AKS
- Stop cluster upgrades automatically on API breaking changes (hour 6 preview)
- Stop and start an AKS cluster
Video storyboard (about 70 seconds)
This courseware cannot generate video or MP3 directly. The storyboard and narration script are provided so you can hand them to a video tool.
Visual: Six layers of blocks stack from bottom to top: Azure platform, cluster baseline, delivery and tenancy, orchestration and recovery, policy.
Narration: Over the first five hours, we started from a single create command and built a full cluster-as-code system.
Visual: The cleanup-order arrows light up one after another: update runs, members, Fleet; backup instances, trusted access, extension, vault.
Narration: Cleanup also has an order. Stop orchestration and protection first, then delete the extensions, and finally delete the cluster.
Visual: The aks-lab icon turns gray and shows “Stopped,” while the next hour's upgrade icon waits beside it.
Narration: Keep the lab cluster and stop it to save money. In the next hour, we go deep into upgrading and operating a single cluster.
Command cheat sheet
RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-labIaC (AVM)
az bicep upgrade && az bicep version az bicep build -f main.bicep K8S_PREV=$(az aks get-versions -l $LOC --query "sort_by(values[?isPreview!=\`true\`], &version)[-2].version" -o tsv) az deployment group what-if -g $RG -f main.bicep -p kubernetesVersion=$K8S_PREV --exclude-change-types NoChange Ignore az deployment group create -g $RG -n avm-aks-lab-bicep -f main.bicep -p kubernetesVersion=$K8S_PREV terraform init && terraform plan -out tfplan && terraform apply tfplan terraform plan -refresh-only
GitOps (Flux / Argo CD extensions)
az k8s-configuration flux create -g $RG -c $CLUSTER -t managedClusters \ -n cluster-config --namespace cluster-config --scope cluster \ -u https://github.com/ORG/aks-gitops --branch main \ --kustomization name=infra path=./infrastructure prune=true \ --kustomization name=apps path=./apps/myapp prune=true dependsOn=\["infra"\] az k8s-configuration flux show -g $RG -c $CLUSTER -t managedClusters -n cluster-config --query complianceState kubectl get fluxconfigs,gitrepositories,kustomizations -n cluster-config kubectl annotate gitrepository cluster-config -n cluster-config reconcile.fluxcd.io/requestedAt="$(date +%s)" --overwrite az k8s-extension create -g $RG -c $CLUSTER -t managedClusters -n argocd --extension-type Microsoft.ArgoCD --config "redis-ha.enabled=false"
Pipeline identity (cluster side)
az identity create -g $RG -n id-aks-deployer az identity federated-credential create -g $RG --identity-name id-aks-deployer -n gh-production \ --issuer https://token.actions.githubusercontent.com \ --subject "repo:ORG/REPO:environment:production" --audiences api://AzureADTokenExchange az role assignment create --assignee-object-id $OID --assignee-principal-type ServicePrincipal \ --role "Azure Kubernetes Service Cluster User Role" --scope $AKS_ID az role assignment create --assignee-object-id $OID --assignee-principal-type ServicePrincipal \ --role "Azure Kubernetes Service RBAC Writer" --scope $AKS_ID/namespaces/myapp kubelogin convert-kubeconfig -l azurecli az aks command invoke -g $RG -n $CLUSTER --command "kubectl get pods -n myapp"
Fleet Manager
az fleet create -g $RG -n fleet-aks-lab -l $LOC --enable-managed-identity az fleet member create -g $RG --fleet-name fleet-aks-lab -n aks-lab --member-cluster-id $AKS_ID --update-group prod az fleet updatestrategy create -g $RG --fleet-name fleet-aks-lab -n staged --stages strategy.json az fleet updaterun create -g $RG --fleet-name fleet-aks-lab -n run-1 \ --upgrade-type NodeImageOnly --node-image-selection Consistent --update-strategy-name staged az fleet updaterun start|stop -g $RG --fleet-name fleet-aks-lab -n run-1 az fleet updaterun skip -g $RG --fleet-name fleet-aks-lab -n run-1 --targets Group:prod az fleet gate list -g $RG --fleet-name fleet-aks-lab --gate-type Approval --state Pending az fleet gate approve -g $RG --fleet-name fleet-aks-lab -n <gate> az fleet autoupgradeprofile create -g $RG --fleet-name fleet-aks-lab -n p1 --channel Stable --update-strategy-id $STRATEGY_ID
Managed namespaces and quotas
az aks namespace add -g $RG --cluster-name $CLUSTER -n team-a \ --cpu-request 1000m --cpu-limit 2000m --memory-request 1Gi --memory-limit 2Gi \ --ingress-policy AllowSameNamespace --egress-policy AllowAll --labels team=a az aks namespace list -g $RG --cluster-name $CLUSTER -o table az aks namespace get-credentials -g $RG --cluster-name $CLUSTER -n team-a kubectl describe quota -n team-a kubectl describe rs -n team-a | grep -A3 Events
Backup and recovery
az dataprotection backup-vault create -g $RG --vault-name bv-aks-lab -l $LOC --type SystemAssigned \ --storage-settings datastore-type="VaultStore" type="LocallyRedundant" az k8s-extension create -g $RG -c $CLUSTER -t managedClusters --name azure-aks-backup \ --extension-type microsoft.dataprotection.kubernetes --scope cluster --release-train stable \ --configuration-settings blobContainer=aks-backup storageAccount=$SA storageAccountResourceGroup=$RG storageAccountSubscriptionId=$SUB az aks trustedaccess rolebinding create -g $RG --cluster-name $CLUSTER -n backuprolebinding \ --roles Microsoft.DataProtection/backupVaults/backup-operator --source-resource-id $VAULT_ID az dataprotection enable-backup trigger --datasource-type AzureKubernetesService --datasource-id $AKS_ID --backup-strategy Week velero backup create myapp-1 --include-namespaces myapp --wait # only for clusters without the Azure Backup extension
Policy as code
az aks enable-addons -g $RG -n $CLUSTER --addons azure-policy az aks safeguards create -g $RG -n $CLUSTER --level Warn --excluded-ns flux-system az aks safeguards update -g $RG -n $CLUSTER --level Enforce --pss-level Baseline az aks safeguards delete -g $RG -n $CLUSTER az policy definition list --query "[?displayName=='Kubernetes cluster should not allow privileged containers'].id" -o tsv kubectl get constrainttemplates,constraints kubectl apply --dry-run=server -f deploy.yaml
Inventory and cleanup
az resource list -g $RG -o table az k8s-extension list -g $RG -c $CLUSTER -t managedClusters -o table az k8s-configuration flux delete -g $RG -c $CLUSTER -t managedClusters -n cluster-config --yes az k8s-extension delete -g $RG -c $CLUSTER -t managedClusters -n flux --yes az aks delete -g $RG -n aks-lab-bicep --yes --no-wait az aks stop -g $RG -n $CLUSTER az group delete -n $RG --yes --no-wait
Quick troubleshooting table
| Symptom | Check first | Common causes | Module |
|---|---|---|---|
| Bicep restore fails | az bicep version, MCR connectivity | CLI too old, proxy, version number | 1 |
| New cluster: kubectl cannot connect | publicNetworkAccess | AVM default Disabled | 1 |
| flux show Non-Compliant | kubectl describe gitrepository/kustomization | Authentication, path, dependencies not ready, admission rejection | 2 |
| Manual changes get reverted | Kustomization interval | Drift repair (expected behavior) | 2 |
| AADSTS70021 | Assertion Subject in the error | Federated credential subject mismatch | 3 |
| Pipeline Forbidden | Role assignment scope | Missing data-plane role or wrong scope | 3 |
| Update run Pending | Member message | Maintenance window, region not yet released, approval gate | 4 |
| Deployment 0/N | kubectl describe rs | Quota rejection, admission rejection | 5, 7 |
| Backup validation fails | validate-for-backup output | MSI permissions, Trusted Access | 6 |
| Data is empty after restore | Restore configuration | Conflict policy Skip, no volume data included | 6 |
| Pod Pending after Enforce | Pod resources | Mutator default 2Gi requests | 7 |
Recommended configuration snippet
skuTier: 'Standard'
disableLocalAccounts: true
aadProfile: { managed: true, enableAzureRBAC: true }
enableOidcIssuerProfile: true
securityProfile: { workloadIdentity: { enabled: true } }
autoUpgradeProfile: { upgradeChannel: 'none', nodeOSUpgradeChannel: 'NodeImage' } // handed to Fleet
azurePolicyEnabled: true
maintenanceConfigurations: [ /* aksManagedAutoUpgradeSchedule / aksManagedNodeOSUpgradeSchedule */ ]{
"stages": [
{ "name": "canary", "groups": [ { "name": "canary" } ],
"afterStageWaitInSeconds": 3600,
"afterGates": [ { "displayName": "SLO check", "type": "Approval" } ] },
{ "name": "prod", "groups": [ { "name": "prod-east" }, { "name": "prod-west" } ] }
]
}Capstone lab + final quiz
Your platform team has been asked to prepare a production-ready delivery system for “myapp.” Requirements: all cluster configuration must be reviewable; no one needs cluster credentials to release the application; cluster upgrades must pass a canary first; accidentally deleting a namespace must be recoverable within a 4-hour RPO; images must not use latest, and containers must declare requests. You need to demonstrate all of these capabilities in rg-aks-lab, using aks-lab-bicep (canary) and aks-lab (production).
aks-lab-bicep, and add an aksManagedNodeOSUpgradeSchedule maintenance configuration to the parameters. Save the what-if output as whatif.txt as review material.cluster-config on both clusters (same repo, infra → apps). Declare it for aks-lab-bicep with the Bicep resource Microsoft.KubernetesConfiguration/fluxConfigurations (instead of the CLI), and confirm both are Compliant.aks-gitops. After the merge, verify that both clusters roll to the new version.aks-lab-bicep → canary and aks-lab → prod. The strategy includes an approval gate after the canary stage and a 300-second wait. Run a NodeImageOnly (Consistent) run. Before approving, run a smoke test on the canary (kubectl --context aks-lab-bicep -n myapp port-forward svc/myapp 8080:80, then curl -s localhost:8080/healthz).aks-lab (either with one command, az dataprotection enable-backup trigger --backup-strategy Week, or with the step-by-step method from module 6). Run on-demand backups for myapp and backup-demo. Delete backup-demo, restore it to backup-demo-restore, and record the RTO (the time from trigger to Pod Ready).aks-lab-bicep, fix all warnings in Git (such as redis probes), then switch to Enforce and confirm Flux is still Compliant. Keep aks-lab at Warn.aks-lab (stopped).Open-ended self-check (answer first, then expand)
1. The AVM Bicep module defaults to publicNetworkAccess = 'Disabled'. What does that mean for CI/CD design?
The API server is not exposed to the public internet (usually paired with a private cluster or API server VNet integration), so hosted runners cannot run kubectl directly. Push mode needs a runner inside the VNet or command invoke. Pull mode (Flux) is unaffected. This is one of the key reasons GitOps is preferred for production.
2. In the Flux extension, which components talk to what? Why don't Git credentials pass through the Azure deployment pipeline?
fluxconfig-agent talks to the Azure regional data plane (pulling configuration and reporting status). source-controller talks directly to the Git server (cloning the repository). Git credentials are stored as a Secret in the cluster configuration namespace and used by source-controller. Azure only delivers configuration and collects status.
3. Why should members managed by Fleet orchestration have the cluster's own auto-upgrade channel turned off?
Official FAQ: when both are enabled, whichever runs first performs the upgrade, so Fleet cannot guarantee the order. Fleet also does not change members' auto-upgrade settings. After you turn it off, Fleet's update runs or auto-upgrade profiles control the order, approvals and consistent node images.
4. What is the fundamental difference between a managed namespace and writing a Namespace and ResourceQuota in the GitOps platform repo?
A managed namespace is an ARM sub-resource. Access control uses Azure built-in roles, and managed fields cannot be changed through the Kubernetes API (tamper-resistant). The GitOps approach is more flexible (you can add any object, such as a LimitRange), but tamper resistance depends on Flux's periodic drift repair, so changes take effect briefly and are then reverted.
5. Can the Operational tier of Azure Backup for AKS handle a “regional outage” scenario?
No. Operational-tier snapshots and manifests sit in the same region as the cluster, in your subscription, and snapshots are not protected by soft delete. A regional outage requires the Vault tier, a GeoRedundant vault, and cross-region restore, with an RPO of up to about 36 hours. It also applies only to Azure Disk volumes.
6. Gatekeeper is fail-open. What does that mean, and how would you compensate?
When the webhook is unavailable, requests are allowed through, so admission policies may stop working during an outage. To compensate, rely on periodic audits (a scan every 15 minutes that reports compliance), use the in-process VAP for CEL policies (which can fail closed), monitor Gatekeeper's availability, and use Defender for Containers for runtime detection.
Sources and versions
| Topic | Verification result | Sources (accessed 2026-11-15) |
|---|---|---|
| AKS version calendar | GA: 1.34 (AKS support ends 2026-11), 1.35, 1.36, 1.37 (GA 2026-10); 1.38 preview (2026-11); LTS list on the same page | Supported Kubernetes versions in AKS (page updated 2026-10-21) |
| Bicep AVM module | avm/res/container-service/managed-cluster highest tag 0.14.0; API 2025-10-01; defaults publicNetworkAccess='Disabled', disableLocalAccounts=true, skuTier='Standard', azurePolicyEnabled=true, omsAgentEnabled=true, autoUpgradeProfile.upgradeChannel='stable'; includes the fluxExtension parameter | MCR tag list · Module source (0.14.0 tag) |
| Terraform AVM module | 0.9.0 (2026-11-04); Terraform >= 1.11, < 2.0; azapi ~> 2.12; inputs parent_id, default_agent_pool (count_of defaults to 3), sku, aad_profile, network_profile, security_profile.workload_identity, auto_upgrade_profile | Terraform Registry · GitHub variables.tf |
| Tool versions | Latest Azure CLI 2.93.0 (2026-11-15; 2.84.0 tested on the lab machine); Bicep v0.49.2; Terraform v1.17.2; kubelogin v0.2.22; azure/login v3.1.0; azure/aks-set-context v5.0.1; azure/use-kubelogin v1.3 | Each project's GitHub Releases |
| Flux extension | microsoft.flux 1.26.4 (2026-10, security fix) / 1.26.2 (Flux v2.9.6); supports N-2; since 1.25.0, helm-controller uses Helm v4 default behavior; requires a cluster with MSI; source default interval 10m, kustomization default sync/retry/timeout 10m, CLI default branch master | Flux release notes · Flux tutorial · Parameters |
| Argo CD extension | Tutorial (2026-09-16): GA on AKS, preview on Arc; the extension list page still marks it preview; HA requires 4 nodes; since 1.0.0-preview it is based on the community Helm chart; direct ConfigMap edits are not supported | Argo CD tutorial · Extension list |
| Fleet Manager | Up to 1,000 members; stage ordering and parallel groups (up to 50 groups per stage); group-level max concurrency defaults to 1, stage-level defaults to 50; approval gates, the planned start gate, max concurrency, max failures and member label selection are in preview; auto-upgrade channels Rapid/Stable/TargetKubernetesVersion/NodeImage/SecurityPatch (preview); CLI ≥ 2.82.0, fleet extension ≥ 1.8.3 (gates need ≥ 1.6.0); polls maintenance windows every 1 hour; node images are valid for 90 days | Concepts · Update runs · Approvals · Auto-upgrade · FAQ · Quickstart |
| Managed namespaces | CLI ≥ 2.80.0, API ≥ 2025-09-01; defaults are ingress AllowSameNamespace, egress AllowAll, adoption Never, delete Keep (az aks namespace add -h, tested on CLI 2.84); built-in roles Namespace User / Namespace Contributor; system namespaces cannot be managed | Managed namespaces |
| Azure Backup for AKS | Extension microsoft.dataprotection.kubernetes (namespace dataprotection-microsoft); Trusted Access role backup-operator; default policies PT4H / P7D; frequencies 4/6/8/12/24h; Vault tier: first backup each day, snapshot transfer starts within ≤4h, disks ≤1TB, ≤100 disks; paired-region RPO about 36h; skips kube-system, kube-node-lease, kube-public and gatekeeper-system; cannot coexist with Velero; enable-backup trigger needs dataprotection ≥ 1.9.0 | Backup CLI · Restore CLI · Support matrix (2026-10-31) |
| Velero | Velero v1.18.4 (2026-09-28); Azure plugin v1.14.4; compatibility: plugin 1.14.x ↔ Velero 1.18.x, 1.15.x ↔ 1.19.x; workload identity install parameters --service-account-name velero --pod-labels azure.workload.identity/use=true, useAAD="true" | Velero releases · Plugin README |
| Azure Policy for Kubernetes | The add-on syncs assignments every 15 minutes and runs a full scan and report every 15 minutes; mode Microsoft.Kubernetes.Data, effects audit/deny/disabled/mutate; automatically excludes kube-system and gatekeeper-system; Arc extension 1.21.0 → Gatekeeper 3.23.1; since 1.18.1, CEL policies can generate VAP (K8s 1.30+) | Policy for Kubernetes · Extension release notes |
| Deployment Safeguards | az aks safeguards create/update/delete --level Warn|Enforce --excluded-ns --pss-level; Automatic defaults to Enforce with Baseline PSS; Standard is optional, with PSS defaulting to Privileged; mutator defaults 500m/2048Mi, minimum 100m/100Mi; all-or-nothing; Gatekeeper fail-open | Deployment Safeguards (doc 2026-06-02, updated 2026-10-20); CLI 2.84 -h tested |
| Open-source policy engines | Gatekeeper v3.23.1 (2026-08-27); Kyverno v1.20.0 (2026-11-12) | GitHub Releases |
Video verification notes
All videos listed in this hour were verified on 2026-11-15 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json) for title, channel and video ID: 3FeIFHaJOtg, xcIVgv8ofl4, NY28RELKVCs (module 1); X5W_706-jSY, AduiFs7oCvU, MeU5_k9ssrs (module 2); Ucdq2C7-JLw, 4Oa5HneTuKs (module 3); owDjoZzs6Fw, ANc5MWn_uqs, oqMKiw1_-Nw (module 4); 9lJdOGti0Pg, DkRZEru_gww, K3jNo4z5Jx8 (module 5); nqBtqbLMy2w, zybLTQER0yY, OzoC-wGfBnw (module 6); Hv3K8zJSbow, ZIk_ER5mLTg, 4wGns611G4w (module 7); Qp8E-z5BdO0, h6TnNWDf4n4 (module 8). oEmbed does not provide duration or publish date, so no durations are shown on the cards. Version numbers and commands in third-party videos may predate this hour, so rely on the verified results for this hour. Each module also has a storyboard script that you can hand to a video tool.
Voice narration notes
The “Voice” tab reads the narration aloud in real time using the browser's Web Speech API (speechSynthesis, en-US). English terms are pronounced in en-US. Quality depends on the English voices installed on your operating system (for example, an English voice on Windows or macOS). This courseware cannot call a TTS service in its generation environment, so no MP3 is embedded. If you need offline audio, hand the narration script to any TTS tool.
Known limitations
- All “expected output” in this hour is sample output. The environment used to generate the courseware did not run real Azure resources, so resource IDs, version patch numbers, node names, hashes, times and gate names depend on your environment. The JSON field structure (especially
az fleet updaterun showandaz aks namespace show) follows what is actually returned. - CLI help was checked against Azure CLI 2.84.0 on the lab machine (
az aks namespace,az aks safeguards). Parameters for the fleet, k8s-configuration and dataprotection extensions come from the official docs. After extension versions are updated, recheck them with-h. - Terraform AVM variable names were checked against
variables.tfon the module repo's main branch and the Registry 0.9.0 page. There may be breaking renames between 0.x versions, so read the CHANGELOG before upgrading. - Fleet's approval gates, max concurrency, max failures, member label selection and the SecurityPatch channel are still in preview. Argo CD extension status is described inconsistently across official pages (tutorial: GA on AKS; extension list: preview), so confirm it again before enabling in production.
- Error text for rejected changes to managed namespaces and the suffixes on constraint names in Safeguards warnings are illustrative; the actual text is whatever the cluster returns. Whether a managed namespace generates a LimitRange follows the concept docs (this hour treats it as “not generated; add it through GitOps”).
- The “Gatekeeper generates VAP” behavior comes from the Arc version of the Azure Policy extension release notes (1.18.1). For the specific behavior and versions in the AKS add-on, follow the AKS docs.
- Costs are given only as orders of magnitude and billing items, with no specific unit prices. Check the Azure pricing calculator and each service's pricing page (AKS pricing tiers, Backup, storage, snapshots).
- Times, concurrency and state transitions in the animations are compressed for illustration and do not represent real durations.