AKS Hour 5: Automated Operations — IaC, GitOps and Pipelines

From “manual az aks create” to “everything as code”: clusters are declared with AVM modules, configuration is reconciled by Flux, upgrades roll out in stages with Fleet, and backup and policy also live in the repo
AKS 1.35 / 1.36 / 1.37 GABicep AVM 0.14.0 · Terraform AVM 0.9.0microsoft.flux 1.26.x (Flux v2.9.6)Fleet Manager · fleet CLI extension ≥ 1.8.3Verified against official docs · 2026-11-15
Overall learning goals
  • 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/azurerm 0.9.0), and explain the ARM calls behind what-if / plan.
  • Enable the Flux cluster extension (microsoft.flux) and create fluxConfigurations. 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

#TimeModuleCore contentAnimation / interactiveLab
0Before classSetup: code repository and service connectionsReuse aks-lab, ACR and variables; prepare the GitOps repository and CLI extensionsAutomation maturity self-assessmentEnvironment check
100–06Bicep and Terraform (AVM)AVM modules, parameter baseline, what-if/plan, state and drift, azapiBicep vs Terraform deployment call chainBuild aks-lab-bicep with AVM Bicep
206–13GitOps: Flux extension and Argo CDmicrosoft.flux, fluxConfigurations, Kustomization dependencies, prune, drift repair, Argo CD extensionCore animation: full Flux extension reconciliation flowFlux deploys myapp to aks-lab
313–21Pipeline deployment to AKSOIDC federated credentials, namespace-scoped RBAC, kubelogin, private cluster, push vs pullPipeline tokens and authorization chainGrant namespace permissions to the pipeline identity
421–28Fleet ManagerMembers, update groups, policies, stages, approval gates, maintenance windows, auto-upgrade profilesCore animation: Fleet staged update runStaged NodeImageOnly update across two clusters
528–35Platform engineering: namespace self-service and quotasManaged namespaces, ResourceQuota/LimitRange, default network policies, golden pathQuota admission calculatorProvision a managed namespace for team-a
635–42Backup and restoreAzure Backup for AKS, Trusted Access, Operational/Vault tiers, Velero 1.18Backup and restore data flowBack up the myapp namespace and restore it
742–50Policy as codeAzure Policy add-on, Deployment Safeguards, Gatekeeper/VAP, compliance scanningAdmission decision simulatorWarn → Enforce drill
850–60Summary of the first five hours, self-check and cleanupConnecting the knowledge, cleanup order, cost reviewCleanup command generator + troubleshooting treeClean up in dependency order
—After classCheat sheet · Capstone labEnd-to-end “cluster as code”: AVM → Flux → Fleet → backup → policyFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Declare AKS with AVM modules (Bicep / Terraform)✓···✓·✓✓az deployment group what-if, terraform planaks-lab-bicep
GitOps reconciliation and drift repair·✓✓·✓··✓az k8s-configuration flux create/showFlux deploys myapp
Pipeline securely accesses the cluster··✓·✓···az identity federated-credential create, kubeloginNamespace-scoped authorization
Multi-cluster staged upgrade···✓···✓az fleet updaterun create/start, az fleet gate approveNodeImageOnly update run
Namespace self-service, quotas and isolation·✓✓·✓·✓·az aks namespace add, kubectl describe quotateam-a
Backup and restore (Azure Backup / Velero)·····✓·✓az dataprotection …, velero backup createmyapp backup and restore
Policy as code and compliance✓·✓·✓·✓✓az aks safeguards create, az policy assignment createWarn → Enforce
Cost and cleanup✓··✓·✓·✓az group delete, az aks stopClean up by dependency

What this hour does not cover (and where to learn it)

TopicWhy it is not in this hourWhere to learn it
General Kubernetes GitOps concepts, native Argo CD/Flux installation and ApplicationSetThe 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 approvalsTool details are already covered in the relevant coursesGitHub Hour 3 · Azure DevOps Hour 3
Writing Helm charts, HelmRelease details, Helm + GitOpsCovered in the Helm courseHelm Hour 3 (Azure)
Terraform language, state backends, module authoringCovered in the Terraform course; this hour only uses AVM modulesTerraform Hour 3 (Azure)
Velero internals and general CSI snapshot detailsCovered in the K8s course; this hour focuses on Azure integrationK8s Hour 4: Storage
Node pool surge upgrade mechanics, PDBs and drainCovered in upgrades and operationsAKS Hour 6
Managed Prometheus / Grafana alertsCovered in the observability coursePrometheus & Grafana Hour 3

How to use this course material

10 pages per module
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.
Learning progress
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).
English voice
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.
Version and cost notesThis hour was verified on 2026-11-15. The current AKS GA versions are 1.34 (end of support in 2026-11 per the AKS release calendar), 1.35, 1.36 and 1.37 (GA in 2026-10), with 1.38 in preview. In the labs, Kubernetes versions are always fetched dynamically with 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)

Reuse the aks-lab, ACR and variables from the first four hours. Prepare a GitOps repository, the CLI extensions and the resource providers.
Before class ≈ 10 minAzure CLI ≥ 2.82 (tested on 2.84, latest 2.93.0)Requires Owner or Contributor + User Access Administrator
Prerequisites
  • Completed hours 1–4: resource group rg-aks-lab (canadacentral) contains the cluster aks-lab (managed identity, OIDC issuer and Workload Identity enabled, see hour 3), and ACR acraks<suffix> already has myapp:1.0 and myapp: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
Is the cluster stopped?If you ran 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

Left over from hour 4
  • 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.
Prepared for hour 6
  • 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.

Environment check list

Module 1 · Build AKS with Bicep and Terraform (AVM)

00:00 – 06:00 · No more hand-writing 300 lines of managedClusters resources: declare the cluster baseline with Azure Verified Modules, which Microsoft maintains and tests
6 minBicep AVM 0.14.0 · TF AVM 0.9.0managedClusters API 2025-10-01★★★★★
Learning goals
  • Explain the two kinds of AVM modules, resource (res) and pattern (ptn), plus the versioning rules and sources: Bicep comes from the public registry br/public:avm/res/container-service/managed-cluster (MCR), and Terraform comes from the Terraform Registry Azure/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-if and terraform plan, and what state, drift and “plan before apply” mean for cluster-level changes.
Prerequisites: the ARM → AKS RP flow behind 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 at mcr.microsoft.com/bicep/... and downloaded to the local cache during bicep restore.
  • Terraform: Azure/avm-res-containerservice-managedcluster/azurerm 0.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 use parent_id (the resource group ID) instead of resource_group_name. The default node pool variable is default_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 = true and autoUpgradeProfile.upgradeChannel = 'stable'. These defaults favor production, so for labs you must explicitly override them (for example, this hour sets publicNetworkAccess to Enabled and 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

StageBicepTerraform (AVM, azapi)
Get the modulebicep restore pulls the OCI artifact from MCRterraform init downloads the module and the azapi provider from the Registry
CompileCompiled locally to ARM JSON (the module becomes a nested deployment)No compile step; HCL is evaluated into the JSON body for azapi resources
Previewaz deployment group what-if: ARM expands the template server-side and compares it with the current stateterraform plan: the provider GETs each resource and compares it with state and configuration
ExecutePUT Microsoft.Resources/deployments; ARM orchestrates dependencies and concurrencyThe provider PUTs resources directly (through ARM); Terraform handles concurrency itself based on the dependency graph
Long-running operationsARM polls the AKS RP's Azure-AsyncOperationazapi polls the same Azure-AsyncOperation header
StatusNo 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)
DeleteRemoving 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 moduleHand-written resourcesazurerm_kubernetes_cluster (Terraform)az aks create script
New API featuresModule follows along (per release)You follow along yourselfWait for provider supportCLI version follow-up
Preview changeswhat-if / planwhat-if / planplanNone
Surrounding resources (locks, diagnostics, RBAC)Consistent interfaceWrite it yourselfExtra resourcesExtra commands
Best forStandardized platformRare, special requirementsExisting azurerm estateExperiments, one-off
Common misconceptions ① “AVM modules use the latest API, so what-if is always accurate.” what-if shows noise for some read-only or server-side default properties of AKS (for example, node pool counts and defaults). In review, focus on network, identity and API server access and other immutable or destructive fields. ② “If you remove a node pool from the template, the Bicep deployment will delete it.” ARM incremental mode does not delete resources that are not declared. Terraform does delete them. ③ “Terraform AVM uses azurerm_kubernetes_cluster.” Version 0.9.0 is built on azapi, maps the ARM resource structure directly, and uses variable names close to ARM (default_agent_pool, aad_profile, network_profile).

Architecture diagram: IaC repository → ARM → AKS resource provider

platform-iac repository main.bicep / main.tfenv/dev.bicepparamPR → what-if / plan review Module source MCR: bicep/avm/res/…managed-cluster:0.14.0Registry: Azure/avm-res-…/azurerm 0.9.0 CI identity Azure Resource Manager Authentication (Entra token)Authorization (Azure RBAC)Azure Policy (deny/modify) Bicep: deployments engineTF: PUTs resources directlyRequest routed to RPPoll Azure-AsyncOperation AKS RP Microsoft.ContainerServicemanagedClusters@2025-10-01 Control planeMC_* / node RGVMSS node poolsAdd-ons Where is the state / source of truth Bicep: resources in Azure + deployment history (no local state) Terraform: tfstate (remote backend + lock) ≈ snapshot of the last apply Drift = actual value in Azure ≠ code (≠ state)
Figure 1-1: both paths end with a PUT on the managedClusters resource. The difference is who orchestrates dependencies and who stores state.

Flowchart: review process for a cluster baseline change

Change parametersFor example, upgrade the module version CI: lint/buildbicep build / tf validate what-if / planPost output as a PR comment Manual approvalWatch destructive fields apply / createDev first → then prod Destructive signals: networkPlugin, podCidr, dnsPrefix, private cluster switch, node pool vmSize→ usually requires rebuilding the cluster or creating a new node pool, not changing it in place
Figure 1-2: treat the “cluster baseline” as code under review. what-if / plan is review material, not a formality.

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

Choose a path to start.
$ # waiting to start

Core commands and parameters

CommandPurposeKey parameters / notes
az bicep upgrade / az bicep versionUpdate 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.bicepDownload br/public: modules to the local cacheOffline CI can run restore first, then build
az deployment group what-ifPreview changes server-side--result-format FullResourcePayloads (default) / ResourceIdOnly; --exclude-change-types NoChange Ignore
az deployment group createDeploy to a resource group--template-file, --parameters, --name (deployment name, for tracking)
az aks get-versions -l $LOCQuery versions available in a regionUse JMESPath to get the N-1 minor version, avoiding hard-coded patch numbers
terraform init / plan -out / applyTerraform AVM pathplan -out tfplan, then apply tfplan, so you apply exactly the plan you reviewed
terraform plan -refresh-onlyDrift detection onlyChanges 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)

Cost / permissions / risk Adds one 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.
Write main.bicep: save the Bicep code from the “Commands” tab as 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",
Preview and deploy (N-1 minor version):
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
Grant yourself cluster admin (Azure RBAC) and connect. After local accounts are disabled, the --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.

Create drift and observe it: change one code-managed property manually in the portal or CLI, then run what-if:
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.

(Optional) Terraform path: plan only, do not apply, to avoid building a second cluster at the same time:
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.

Cleanup: 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.

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

▶
Azure Verified Modules Overview — John Savill's Technical Training
English · What AVM is, resource vs pattern modules, versioning and the support model
▶
AKS Labs: Deploy AKS with Terraform & Azure Verified Modules — Azure Kubernetes Service (AKS)
English · Hands-on lab from the official AKS channel, matching the Terraform path in this module (module version follows this course)
▶
Creating an AKS Automatic cluster with custom VNET in Bicep — Will Velida
English · Declaring AKS (Automatic) with Bicep and a custom VNet, for comparison with the Standard baseline in this course

Official docs

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.

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

Module 2 · GitOps: Flux extension and Argo CD

06:00 – 13:00 · What should run in the cluster is decided by Git. Azure installs and upgrades Flux, and Flux keeps pulling the cluster back to the state in Git.
7 minmicrosoft.flux 1.26.4 · Flux v2.9.6Argo CD extension: AKS GA / Arc preview★★★★★
Learning goals
  • Distinguish three layers of objects: the Azure resource Microsoft.KubernetesConfiguration/extensions (microsoft.flux) and fluxConfigurations; the in-cluster Azure CRD FluxConfig (fluxconfigs.clusterconfig.azure.com); and the upstream Flux CRDs GitRepository, Kustomization and HelmRelease.
  • Use az k8s-configuration flux create to create two layers of Kustomizations with dependsOn and prune. Trace from complianceState all 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.
Prerequisites: the GitOps concepts in K8s Hour 6, Module 1; Helm Hour 3. Importance: ★★★★★ (core of this hour)

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.

LayerObjectWho creates / who consumes
Azure resourceextensions/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 resourcefluxConfigurations/cluster-configYou 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 reportingcomplianceState, 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 a fluxExtension parameter.
  • Compliance visibility: each configuration's complianceState can 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

  1. az k8s-configuration flux create → ARM PUT fluxConfigurations (if the extension does not exist, an extension named flux is installed automatically first).
  2. fluxconfig-agent pulls the configuration from the regional data plane over outbound HTTPS, and creates a FluxConfig in --namespace (cluster-config in this hour).
  3. fluxconfig-controller expands it into GitRepository/cluster-config and several Kustomization/cluster-config-<name> objects.
  4. source-controller clones the repository at each interval, creates a tar.gz artifact, and writes main@sha1:… to status.artifact.revision.
  5. kustomize-controller detects the new artifact → kustomize build → server-side apply (with dry-run and diff) → executes prune based on the inventory → health check → updates the Ready condition. dependsOn makes apps wait for infra to be Ready.
  6. Even if there are no new commits in Git, kustomize-controller reapplies at each interval and reverts manual changes (drift).
  7. 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
StatusGA (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 pointARM fluxConfigurationsExtension settings (community Helm chart values); you cannot edit the Argo CD ConfigMap directlyFully self-managed
UINo UI (the portal shows compliance state)Argo CD UI, can connect to Entra SSOOptional
Resource needsLightDefault HA, needs ≥ 4 nodes; for a single node, add redis-ha.enabled=falseCustom
Best forPlatform baselines, large-scale rollouts, “hands-off automation with no UI”App teams that need visual sync/rollback and are used to ApplicationSetsNeed the latest upstream version or special plugins
Common misconceptions ① “A Git change takes effect immediately.” The delay is the source pull interval + the kustomize interval + the app rollout time. For instant reconciliation, use a webhook Receiver or 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

Azure (control plane) ARM: extensions/fluxARM: fluxConfigurations/cluster-config KubernetesConfiguration RPRegional data planecanadacentral.dp.kubernetesconfiguration… Git (aks-gitops) infrastructure/ → Kustomization infraapps/ → Kustomization appsdependsOn: [infra]HTTPS 443 / SSH 22 AKS cluster aks-lab fluxconfig-agentPull config / report statusns: flux-system FluxConfig CRns: cluster-config fluxconfig-controllerGenerate upstream Flux objects source-controllerGitRepository → artifactmain@sha1:… kustomize-controllerbuild → SSA → prune→ health helm / notificationHelmRelease / alerts kube-apiserver → namespace myappDeployment myapp / redis · Service Outbound pull clone Artifact
Figure 2-1 Azure only handles “delivering configuration and collecting status.” Pulling and applying both happen inside the cluster, and Git credentials never pass through Azure's deployment pipeline.

Flowchart: timeline from a Git commit to a Pod update

git pushimage: myapp:1.1 Wait for source interval0 ~ interval (default 10m) New artifact revisionTrigger Kustomization SSA apply + health checkDeployment rolls out complianceStateCompliant To shorten the delay: lower the interval (more Git requests), configure a Receiver webhook, or run flux reconcile source git cluster-config -n cluster-config manually. Drift correction: with no new commit, kustomize-controller still re-applies via SSA on its own interval and changes fields edited with kubectl back to the values in Git.
Figure 2-2 The GitOps delay comes mainly from the pull interval, not from Azure

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

Select scenario ① first.
$ # waiting to start

Core commands and parameters

CommandPurposeKey parameters / notes
az k8s-extension create --extension-type microsoft.fluxInstall 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 createCreate a fluxConfiguration-n configuration name, --namespace, --scope cluster|namespace, -u repository, --branch, multiple --kustomization name= path= prune= dependsOn=
az k8s-configuration flux show / listCheck compliance state--query "{state:complianceState, statuses:statuses[].{kind:kind,name:name,state:complianceState}}"
az k8s-configuration flux kustomization updateModify a KustomizationFor example, change path, prune, or sync interval
az k8s-configuration flux deleteDelete the configuration (also deletes its objects when prune=true)--yes; delete the configuration before the extension
kubectl get fluxconfigs,gitrepositories,kustomizations -AThree layers of objects in the clusterThe READY / STATUS columns show the failure reason directly
flux reconcile … (optional, flux CLI)Trigger reconciliation nowFine 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)

Cost / permissions / risk The extension itself has no extra charge; it uses a small amount of node resources. You need read/write permission on 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.
Add the application manifests to the GitOps repository (replace <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 push
If the myapp namespace was already created by hand in earlier hours: delete the manual objects first to avoid conflicts with the GitOps-managed objects (or keep the namespace, and Flux's SSA will take over same-named objects):
kubectl get all -n myapp
kubectl delete deploy,svc --all -n myapp     # lab environments only
Create the Flux configuration and wait for compliance:
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
Release 1.1 through Git and force an immediate pull (don't wait 10 minutes):
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
Observe drift correction: manually change the replica count to 5, then trigger a Kustomization reconciliation:
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.

Keep for Module 6: the myapp namespace is used by the backup lab, so do not delete the configuration. To clean up after class:
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).

Command-line exercise
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 table
2. 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
Scenario analysis question
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

▶
Introduction to Flux CD on Kubernetes | GitOps | CICD — That DevOps Guy
English · The basic workings of Flux controllers, GitRepository, and Kustomization (upstream Flux, not the Azure extension)
▶
GitOps on AKS with Flux: From Zero to Autopilot — iaMachs
English · A demo of GitOps with Flux on AKS, which you can compare with this module's extension approach
▶
ArgoCD Tutorial for Beginners | GitOps CD for Kubernetes — TechWorld with Nana
English · An introduction to Argo CD concepts, as background for the Argo CD extension

Official docs

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.

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

Module 3 · Pipelines: deploying to AKS with GitHub Actions and Azure Pipelines

13:00 – 21:00 · No repeat of YAML syntax. It answers the questions a cluster administrator cares about: which identity the pipeline runs as, what permissions it gets, where it connects into the cluster from, and what it can change
8 minazure/login v3 · use-kubelogin v1 · kubelogin v0.2.22Workload identity federation (OIDC)★★★★☆
Learning goals
  • Set up a keyless identity for the pipeline: a user-assigned managed identity + a federated credential (the GitHub repo:…:environment:production subject, 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.
Prerequisites: GitHub hour 3 (Actions, environments, OIDC) or Azure DevOps hour 3 (service connections, environments, approvals), plus Workload Identity in hour 3 of this course. Importance: ★★★★☆

What: the three gates a pipeline passes to reach the cluster

GateWho checksWhat the pipeline needsTypical failure
① Sign in to AzureMicrosoft Entra IDOIDC token matches the federated credential (issuer / subject / audience)AADSTS70021: No matching federated identity record found
② Get kubeconfigARM (Azure RBAC, control plane)Microsoft.ContainerService/managedClusters/listClusterUserCredential/action (Cluster User Role)AuthorizationFailed … listClusterUserCredential
③ Call kube-apiserverAKS Entra authentication webhook + Azure RBAC authorization webhook (or K8s RBAC)Entra token from kubelogin; data-plane role on the target namespaceForbidden: User "…" cannot create resource "deployments" … in the namespace "myapp"
④ AdmissionGatekeeper / Deployment Safeguards / VAP (module 7)Compliant manifestsadmission 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 apply to every namespace, plus a client secret stored in a repository Secret, is a common entry point for lateral movement.
  • Once disableLocalAccounts is enabled, old pipelines that fetch credentials with --admin fail 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 modelGitOps pull model
What the pipeline doesBuild image → push to ACR → sign in to Azure → kubelogin → kubectl apply/helm upgradeBuild image → push to ACR → update the image tag in the GitOps repository (PR or direct commit)
Pipeline needs cluster permissionsYes (namespace-level)No; only write access to the GitOps repository
Private clusterNeeds a runner inside the VNet or command invokeNo effect (Flux pulls outbound from inside the cluster)
Drift correction and auditNone; audit uses pipeline logsFlux reconciles continuously; audit uses Git history
Deployment feedbackSynchronous (rollout status)Asynchronous (needs notification-controller to write commit status back, or to send alerts)
Best forDev/test environments and scenarios that need immediate feedbackProduction, 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

MethodWhere the secret is storedRotationVerdict
Workload identity federation (OIDC)NoneNot neededRecommended
Service principal + client secretRepository/library SecretManualPhase out
az aks get-credentials --adminCertificate in kubeconfigCluster certificate must be rotatedUnusable once local accounts are disabled
Kubernetes ServiceAccount long-lived tokenRepository SecretManualNot recommended; bypasses Entra auditing
Common misconceptions ① “Give the pipeline Contributor and it can deploy.” Contributor is an ARM control-plane role. In a cluster with Azure RBAC enabled, data-plane operations need an “Azure Kubernetes Service RBAC …” role. ② “For OIDC, just put the repository name in the subject.” The GitHub subject depends on how the workflow is triggered: with an environment it is 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

CI (GitHub / ADO) build myapp:1.2scan / signOIDC token Identity id-aks-deployer(user-assigned managed identity) Entra IDFederated credential match ACRAcrPush Push model: aks-lab ARM: Cluster User Role → kubeconfig (exec: kubelogin) API Server: Entra token authentication Azure RBAC: RBAC Writer @ namespaces/myapp Admission: Gatekeeper / Safeguards Requires network reachability to the API server aks-gitops repositoryPR: image 1.1 → 1.2Branch protection + approval Pull modelFlux pulls outboundPipeline has zero cluster permissions Token git push / PR (GitHub token)
Figure 3-1 The push model has to cross four gates. The pull model shrinks the pipeline's permissions down to “write to Git.”

Flowchart: how the exec plugin in kubeconfig gets a token

kubectl applyRead kubeconfig exec: kubelogin get-token--login azurecli / workloadidentity Entra tokenaud = AKS server application API ServerToken authentication Azure RBACAuthorization webhook The fixed server application ID for AKS's managed Entra integration is 6dae42f8-4368-4678-94ff-3960e28e3630 (kubelogin handles this automatically, so you do not need to write it by hand).
Figure 3-2 When “azure/login succeeds but kubectl fails,” the problem is usually at the kubelogin hop

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

Choose a fault injection to start.
$ # waiting to start

Core commands and parameters (cluster side)

CommandPurposeKey parameters / notes
az identity createCreate pipeline identity id-aks-deployerSeparate from the application's id-myapp for separation of duties
az identity federated-credential createTrust GitHub OIDC tokens--issuer https://token.actions.githubusercontent.com, --subject repo:ORG/REPO:environment:production, --audiences api://AzureADTokenExchange
az role assignment create --scope $AKS_IDAllow fetching kubeconfigRole “Azure Kubernetes Service Cluster User Role”
az role assignment create --scope $AKS_ID/namespaces/myappNamespace-level data-plane permissionsRole “Azure Kubernetes Service RBAC Writer” (does not include Role/RoleBinding management)
kubelogin convert-kubeconfig -l azurecliChange kubeconfig to use the exec pluginIn pipelines you can also use -l workloadidentity
az aks command invokeRun 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)

Cost / permissions / risk User-assigned managed identities are free. Creating role assignments requires User Access Administrator or Owner. Risk: a federated credential subject that is too broad (for example, a wildcard branch) lets any branch's workflow get deployment permissions.
Create the pipeline identity and federated credential (replace ORG/REPO with your application repository):
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
Least-privilege role assignments:
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
Verify “can only write myapp”: the most reliable check is to have the pipeline identity ask the API server itself. After the kubelogin step in the workflow, add:
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.

(Optional) Run the push-model workflow: in the application repository, set the variables 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.
Clean up (optional after class; the Module 8 cleanup removes everything along with the resource group):
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".

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

▶
Authenticating Azure Deployments in GitHub Actions with Microsoft Entra ID Workload Identities — Will Velida
English · Using GitHub Actions to sign in to Azure through federated credentials; this covers the first gate in this module
▶
Deploy to Azure Kubernetes (AKS) from Azure DevOps with Azure Pipelines | Build LIVE with Me — CoderDave
English · A full demo of deploying to AKS with Azure Pipelines (for service connection details, follow workload identity federation)

Official docs

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.

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

Module 4 · Multi-cluster: Azure Kubernetes Fleet Manager

21:00 – 28:00 · Upgrading one cluster is operations; upgrading fifty clusters is orchestration. Go canary first, then production, with approval gates in between, and respect each cluster's maintenance window.
7 minUpdate runs / strategies / auto-upgrade GAApproval gates, max concurrency, max failures: preview★★★★★
Learning goals
  • 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.
Prerequisites: The surge upgrade mechanics inside a single cluster are covered in hour 6. This module covers only the “order between clusters.” Importance: ★★★★★ (the core of this hour)

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:

ConceptMeaningKey rules (official docs, 2026-08/10 version)
Update runOne 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 strategyReusable stage/group templateA created run copies it at run time, so later changes to the strategy do not affect existing runs
StageRuns in orderCan set afterStageWaitInSeconds, pre/post approval gates (preview), and a stage-level max concurrency (preview, default 50)
GroupRuns in parallel within a stageUp to 50 groups per stage; group-level max concurrency defaults to 1 (so members within a group are upgraded one at a time)
MemberOne clusterCan belong to only one update group; can also be selected with member labels + memberSelector (preview, the direction the official docs recommend)
GatePause pointApproval gate (preview; az fleet gate approve; does not expire and cannot be approved in advance); scheduled start gate (preview)
Auto-upgrade profileAutomatically creates and starts a run when a new version is releasedChannels 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 Consistent node 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

  1. Run starts → enters the first stage → if there is a “pre-stage” approval gate, it waits in Pending for approval.
  2. 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.
  3. 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.
  4. 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).
  5. When all groups in a stage finish → the “post-stage” approval gate and afterStageWaitInSeconds start timing at the same time. The next stage begins only when both are satisfied.
  6. 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 runPer-cluster auto-upgrade channelPipeline script running az aks upgrade one cluster at a time
Ordering across clustersStage / groupNoneWrite it yourself
Approval and waitingApproval gates, post-stage waitNonePipeline approval
Maintenance windowHonoredHonoredNeeds your own judgment
Image consistencyConsistent optionEach cluster takes the latestYou must specify it yourself
Failure handlingFails fast by default; tolerance can be set (preview)Single clusterWrite it yourself
Common misconceptions ① “Clusters within a group also run in parallel.” By default the group-level max concurrency is 1, so clusters in a group run one at a time. To speed things up, add more groups or set a group-level maxConcurrency (preview). ② “If you change the strategy, runs in progress will change too.” The strategy is copied when the run is created. ③ “Completed means success.” When maxAllowedFailures is set, a group can still reach Completed even if 100% of it failed. ④ “You can use a node image version at any time.” A node image version is only valid for 90 days from its release. A run that stays suspended for a long time may fail on later members.

Architecture diagram: this hour's Fleet topology and update strategy

Fleet: fleet-aks-lab (hubless)rg-aks-lab · canadacentral Stage 1: canary Group canaryMember aks-lab-bicep (created in module 1) afterGates: Approval “Verify canary”afterStageWaitInSeconds: 60 Stage 2: prod Group prodMember aks-lab More groups run in parallel within this stageMembers within a group run one at a time by default (maxConcurrency=1) Order
Figure 4-1 Stages decide “which goes first,” groups decide “what runs in parallel,” and each member's maintenance window decides “when it actually starts”

State machine: the update run lifecycle

NotStarted Running PendingGate / maintenance window / region not yet published StoppingIn-flight clusters finish up Failed / Stopped Completed start Start again: resumes from the last unprocessed cluster skip: can skipStage / group / member
Figure 4-2 Runs in Failed or Stopped state can both be restarted. Skipped clusters end up on a different version from the rest.

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.

Set the options, then click “Play.”
$ az fleet updaterun create … --update-strategy-name staged

Core commands and parameters

CommandPurposeKey parameters / notes
az fleet createCreate 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 / updateAdd members / change update groups--member-cluster-id, --update-group, --labels "env=staging tier=frontend" (preview)
az fleet updatestrategy createSave stage/group template--stages strategy.json
az fleet updaterun createCreate 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 / deleteManage runsskip --targets Group:name Stage:name
az fleet gate list / approveApproval gate (preview, fleet extension ≥ 1.6.0)list --gate-type Approval --state Pending
az fleet autoupgradeprofile create / generate-update-runAuto-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)

Cost / permissions / risk A hubless Fleet resource has no compute nodes of its own. Costs come mainly from the member clusters (refer to the official pricing page). You need write permission on 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).
Create the Fleet and add two members:
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
Check the members' auto-upgrade settings (when Fleet orchestrates a cluster, turn off the cluster's own upgrade channel, or the two will compete):
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.

Create the strategy and run, then start it (save strategy.json from the “Commands” tab into the current directory):
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"
Verify on the canary, then approve:
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.

Watch the prod stage and myapp:
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
Clean up: in module 8, delete the update run first (this also deletes its approval gate resources), then the members and the Fleet, and then 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.

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

▶
Azure Kubernetes Fleet Manager - Upgrading your fleet of clusters at scale — Azure Kubernetes Service (AKS)
English · official AKS channel: demos of update runs, stages, and groups
▶
Azure Kubernetes Fleet Manager - Multi-cluster Update Strategies — Steven Rodriguez
English · creating and reusing update strategies
▶
Azure Fleet Manager: Orchestrating Multi-Cluster Upgrades (Part 1: Manual Runs) — KloudWithKasun
English · step-by-step demo of a manual update run

Official docs

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.

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

Module 5 · Platform Engineering: cluster templates, namespace self-service, and quotas

28:00 – 35:00 · The platform team provides a “golden path.” Request a namespace, and you automatically get quotas, default network isolation, Entra permissions, and a GitOps entry point.
7 minAKS managed namespaces (API 2025-09-01+, CLI ≥ 2.80)Requires Azure RBAC; network policy needs a policy engine★★★★☆
Learning goals
  • 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 add to 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.
Prerequisites: K8s Hour 5: Security and Multi-Tenancy; namespace-level Azure RBAC from module 3 of this course. Importance: ★★★★☆

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:

LevelBuilt-in roleWhat it allows
Control plane (ARM)Azure Kubernetes Service Namespace UserSee 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 ContributorCreate and modify managed namespaces (used by the platform team or the self-service portal)
Data plane (Kubernetes)Azure Kubernetes Service RBAC Reader / Writer / AdminWhen scoped to …/managedNamespaces/<name>, it applies only within that namespace
ParameterAllowed valuesDefault (az aks namespace add -h, tested on CLI 2.84)
--ingress-policyAllowAll / AllowSameNamespace / DenyAllAllowSameNamespace
--egress-policyAllowAll / AllowSameNamespace / DenyAllAllowAll
--adoption-policyNever / IfIdentical / AlwaysNever (do not adopt an existing namespace with the same name)
--delete-policyKeep / DeleteKeep (keep the Kubernetes namespace when the managed resource is deleted)
--cpu-request/--cpu-limit/--memory-request/--memory-limitRequiredResourceQuota 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

  1. A Pod creation request passes through the ResourceQuota admission plugin in kube-apiserver, in the validation phase after webhooks such as Gatekeeper.
  2. If the quota includes compute resources such as requests.cpu or limits.memory, every container must declare the corresponding values, or the request is rejected: must specify limits.memory….
  3. It checks whether “used + this request” exceeds hard, and rejects the request if it does: exceeded quota … requested: … used: … limited: ….
  4. After it passes, status.used is 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.
  5. 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 namespaceGitOps platform repo (Namespace + Quota + NetworkPolicy + RoleBinding manifests)Fleet-managed Fleet namespace (requires a hub)
Where it is declaredARM (CLI, Bicep, portal)GitFleet hub
Access controlAzure RBAC, built-in rolesK8s RBAC or Azure RBACAcross member clusters
Tamper resistanceManaged fields are blocked from changes through the K8s APIFlux drift correction (changes get reverted)—
Best forSingle-cluster self-service, portal experienceNeeds custom objects (LimitRange, PDB templates, default ServiceAccount)Teams need same-named namespaces across multiple clusters
Common misconceptions ① “Quotas limit actual usage.” ResourceQuota counts the declared requests and limits, not the actual usage shown by 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

Team ASubmit request (portal or PR)team-a · 2 CPU · 4GiMember group grp-team-a Platform automationApproval + validation (budget and naming)Bicep: managedNamespacesRole assignment (Namespace User + RBAC Writer) aks-lab Reconciling componentARM → K8s, blocks tampering Namespace team-a ResourceQuotarequests.cpu 1 / limits.cpu 2requests.mem 1Gi / limits.mem 2Gi NetworkPolicyingress: AllowSameNamespaceegress: AllowAll labels: team=a(LimitRange is added by the platform GitOps repo) Authorized by Azure RBACScope …/managedNamespaces/team-a Flux (module 2)--scope namespace
Figure 5-1 One request = an ARM child resource + two role assignments. The in-cluster objects are reconciled by AKS, not by tickets.

Flowchart: the quota check a Pod creation request goes through

ReplicaSet controllerPOST pods Mutating admissionLimitRanger fills in defaults Validating webhookGatekeeper (module 7) ResourceQuotaused + req ≤ hard ? Write to etcdUpdate status.used Rejected → 403 Forbidden: exceeded quota / must specify …Event recorded on the ReplicaSet (kubectl describe rs)
Figure 5-2 The quota check happens inside the API server and is independent of the scheduler

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.

requests.cpu per Pod (m): 250m
limits.cpu per Pod (m): 500m
requests.memory per Pod (Mi): 128Mi
limits.memory per Pod (Mi): 256Mi
Target replicas: 6
Adjust the parameters, then click Scale.
$ kubectl describe quota -n team-a

Core commands and parameters

CommandPurposeKey parameters / notes
az aks namespace addCreate managed namespaceRequired: -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 / deleteManagelist --resource-group or --subscription to list across clusters
az aks namespace get-credentialsGet namespace-scoped connection credentialsRequires the Namespace User role
kubectl describe quota -n team-aView used / hardBasis for capacity and cost allocation
kubectl describe rs -n team-aFind quota rejection eventsCheck 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)

Cost / permissions / risk No additional cost. Requires “Azure Kubernetes Service Namespace Contributor” or cluster Contributor, plus 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.
Create the managed namespace: run 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
Verify tamper protection: try to modify a managed object directly:
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).

Trigger the “no requests declared” rejection:
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
Add requests and limits, then trigger “exceeded quota”:
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.

Expand the quota (through ARM) and watch the ReplicaSet retry automatically:
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
Cleanup:
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).

Command-line exercise
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.

Scenario analysis question
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

▶
Managed Namespaces with Ximeng Zhao: AKS Me Anything: Azure Kubernetes Service — Azure Kubernetes Service (AKS)
English · official AKS channel: design and Q&A for managed namespaces
▶
Quick Guide to Managed Namespaces in AKS — Programming with Wolfgang
English · managed namespaces quick start
▶
Kubernetes Namespaces Explained in 15 mins | Kubernetes Tutorial 21 — TechWorld with Nana
English · namespace basics review

Official docs

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.

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

Module 6 · Backup and Restore: Azure Backup for AKS and Velero

35:00 – 42:00 · GitOps can rebuild the declarations, but not the data or the things that never made it into Git. Backup is the last line of defense.
7 minAzure Backup for AKS · Operational and Vault tiersVelero v1.18.4 + Azure plugin v1.14.4★★★★☆
Learning goals
  • Describe the components of Azure Backup for AKS: the Backup vault, backup policies, the in-cluster backup extension (microsoft.dataprotection.kubernetes, namespace dataprotection-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.
Prerequisites: K8s Hour 4 (CSI snapshots, how Velero works), and workload identity from hour 3. Importance: ★★★★☆

What: two approaches

Azure Backup for AKSVelero (open source) + velero-plugin-for-microsoft-azure
In-cluster componentBackup extension (cluster extension, managed through ARM)Velero Deployment + plugin initContainer (installed with Helm or CLI)
Control planeBackup vault + backup policy + backup instance (Azure resources)In-cluster CRDs: Backup, Schedule, Restore, BackupStorageLocation
Where resource manifests are storedBlob container in the storage account you specifyBlob container that the BackupStorageLocation points to
Volume dataAzure 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 / immutableVault 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 retentionOperational: 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 dayAny cron schedule
MonitoringAzure Monitor alerts, Backup reports, Resource GraphPrometheus 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 ns or 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

  1. 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).
  2. 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.
  3. 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.
  4. 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).
  5. 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.
Common misconceptions ① “Backing up the cluster means you can restore all of AKS.” Backups cover Kubernetes resources and volumes, not the cluster itself. Node pools, networking, and identity are rebuilt from IaC. ② “The Operational tier is off-site backup.” It lives in the same region as the cluster, in your subscription, and snapshots are not protected by soft delete. Off-site requires the Vault tier. ③ “A backup every 4 hours means the 4-hour RPO also applies across regions.” The Vault tier moves only one recovery point per day. The primary-region RPO can be up to 24 hours, and the paired region adds up to 12 hours of replication delay (about 36 hours in total). ④ “Restoring to a same-named namespace is safe.” The default conflict policy, Skip, skips existing objects with the same name, so the result can be “restore succeeded, but the data did not come back.”

Diagram: components and permissions of Azure Backup for AKS

Backup vault bv-aks-labSystem-assigned identityPolicy: PT4H, retain 7 days(Optional) Vault tier, 30 daysBackup instance → aks-lab aks-lab Backup extension (dataprotection-microsoft)Extension user identity (in the node resource group) myappDeploy/Svc/Secret backup-demoPVC (disk.csi) Storage account staksbk…Container aks-backupResource manifests (same region, GPv2) Snapshot resource grouprg-aks-lab-snapAzure Disk incremental snapshots Permissions list Trusted Access: vault → cluster (backup-operator) · Extension identity: Storage Blob Data Contributor @ storage account Cluster identity: Contributor @ snapshot RG · Vault identity: Reader @ cluster and snapshot RG (update-msi-permissions can add these automatically) Trusted Access
Figure 6-1 The vault does not pull data directly. It directs the in-cluster extension through Trusted Access, and the data is written to your own storage and snapshot resource group.

Flowchart: Operational tier and Vault tier

Scheduled backupEvery 4 hours Operational recovery pointSame region · fast recovery Vault tier (first of the day)Transfer starts within ≤4h · off-site Paired region (GRS+CRR)canadacentral → canadaeast RPO: Operational at least 4 hours; Vault tier in the primary region up to 24 hours; paired region up to about 36 hours A Vault-tier restore is first “hydrated” into a staging resource group and storage account, and you must clean those up manually afterward
Figure 6-2 Different tiers map to different RPOs and disaster scenarios

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

Select a flow.
$ # waiting to start

Core commands and parameters

CommandPurposeKey parameters / notes
az dataprotection backup-vault createCreate 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 AzureKubernetesServiceUse the default policyDefault trigger PT4H, retention P7D. Add a Vault-tier rule with retention-rule create-lifecycle
az k8s-extension create --extension-type microsoft.dataprotection.kubernetesInstall the backup extension--configuration-settings blobContainer= storageAccount= storageAccountResourceGroup= storageAccountSubscriptionId=
az aks trustedaccess rolebinding createEnable 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 / createConfigure backup instance--snapshot-resource-group-name. In the configuration, included_namespaces and snapshot_volumes
az dataprotection backup-instance adhoc-backupOn-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 triggerRestore (original cluster or another cluster)namespace_mappings, conflict_policy, and persistent_volume_restore_mode in the restore configuration
az dataprotection enable-backup triggerOne command does all of the above preparationdataprotection extension ≥ 1.9.0; --backup-strategy Week|Month|DisasterRecovery|Custom
velero install / backup create / restore createVelero approachPlugin 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)

Cost / permissions / risk The Backup vault is billed by protected instance and storage (see Azure Backup pricing). The storage account and disk incremental snapshots are billed by capacity, and the lab data is very small. Requires Owner, or Contributor + User Access Administrator, because multiple role assignments are created. Risk: an incorrect conflict policy or namespace mapping in the restore configuration could overwrite existing objects. This lab maps to a new namespace.
Prepare a test namespace with a persistent volume (not managed by GitOps):
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.txt
Create the vault, policy, storage, and snapshot resource group:
VAULT=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
Install the backup extension, grant storage permissions, and enable Trusted Access:
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
Configure the backup instance (includes only myapp and backup-demo):
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.

Run an on-demand backup and wait for the job to finish:
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
“Disaster”: delete backup-demo, then restore to backup-demo-restore:
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.

Cleanup (handled together in module 8; the order matters):
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.

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

▶
AKS Backup using Azure Backup Vault — Houssem Dellai
English · Backup vault, backup extension, and restore demo
▶
Kubernetes Backups, Upgrades, Migrations - with Velero — That DevOps Guy
English · Velero backup and migration approach (versions as listed in this hour)
▶
Master Kubernetes Backups with Velero: Step-by-Step Guide — DevOps & AI Toolkit
English · Velero step-by-step hands-on

Official docs

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.

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

Module 7 · Policy as Code and Compliance Automation

42:00 – 50:00 · Rules are written in code and ship with the cluster. Audit first, then warn, and finally deny. Admission blocks in real time, and audits scan on a schedule.
8 minAzure Policy add-on (Gatekeeper) · Deployment SafeguardsGatekeeper fail-open · compliance reporting on a roughly 15-minute cycle★★★★★
Learning goals
  • 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/update to 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.”
Prerequisites: the Azure Policy and Defender overview from hour 3, and the admission failure symptoms from module 3 of this course. Importance: ★★★★★

What: components and objects

ComponentLocationResponsibility
azure-policy Podkube-systemEvery 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-systemValidating webhook (validation.gatekeeper.sh), mutating webhook, audit controller (audit.gatekeeper.sh)
ValidatingAdmissionPolicy (VAP)Inside the kube-apiserver processAzure 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 definitionARMMode Microsoft.Kubernetes.Data; effects audit / deny / disabled / mutate; details.templateInfo carries the ConstraintTemplate as a URI or Base64
Deployment SafeguardsAKS 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)

PolicyChange under Enforce (if any)
Cannot Edit Individual Nodes—
Containers must define CPU and memory requestsWhen missing, set to 500m / 2048Mi (requests = limits). Raised to 100m / 100Mi if below the minimum.
Multi-replica workloads must have anti-affinity or topologySpreadConstraintsAdds preferred anti-affinity with weight 100, and maxSkew: 1, ScheduleAnyway topology spread (by hostname)
No AKS Specific Labels / Reserved System Pool TaintsRemoves 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 apply at 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

  1. Authentication → authorization (Azure RBAC, module 3).
  2. Mutating admission: Safeguards mutators at Enforce, Gatekeeper mutation, LimitRanger, and other components that modify the object.
  3. Object schema validation.
  4. Validating admission: VAP (in-process), the Gatekeeper validating webhook (deny rejects; Warn returns a Warning: header), and ResourceQuota.
  5. 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.
Fail-open reminder: Gatekeeper is fail-open. If the webhook does not respond, the request is allowed through rather than rejected (the official FAQ states this explicitly). So admission policies are not the only line of defense. Audit results and Defender for Containers are still necessary. Generated VAPs are evaluated in-process and can fail-close.

When: rollout cadence and tool choice

StageAzure Policy effect / Safeguards levelGoal
Weeks 1–2Audit / WarnCollect a list of violations and notify teams to fix their templates
Week 3dev/staging: Deny / Enforce; prod: WarnValidate in non-production so nothing gets hit by accident
From week 4prod: Deny / Enforce, with exemptions managed using exemptions that have an expiry dateOngoing
Azure Policy add-on / SafeguardsSelf-installed GatekeeperKyverno (OSS, latest v1.20.0 as of 2026-11)Native VAP
Management planeARM, cross-subscription compliance viewIn-cluster CRDsIn-cluster CRDsIn-cluster objects
Policy languageRego (built-in definitions), CELRegoYAML/CELCEL
Mutate / generateLimited mutationSupports mutationStrong (mutate and generate)MutatingAdmissionPolicy (newer)
Used together with Azure Policy—Conflicts (the add-on bundles its own Gatekeeper)Can coexist, but avoid overlapping rulesCan coexist
Common misconceptions ① “Once a policy is assigned, it takes effect immediately.” The add-on syncs assignments every 15 minutes, and compliance results are also reported on a 15-minute scan cycle, so the first evaluation can take longer. ② “Warn level doesn't affect anything.” Warn does not reject, but mutators under Enforce modify objects (for example, the default 2Gi memory requests), which can leave Pods that the nodes cannot fit. ③ “Excluding a namespace makes it safe.” Exclusions are blind spots in the policy. Prefer exemptions with an expiry date, and record the reason. ④ “Safeguards lets me pick the rules I need.” No. It is all or nothing. When you need finer control, assign individual built-in policies directly.

Diagram: the two paths of Azure Policy for AKS

policy-as-code repopolicyAssignments.bicepParameters: effect, excludedNamespacesexemptions (with expiry)PR review → per-environment rollout Azure Policy serviceAssignment → cluster scopeCompliance view (subscription / management group)Resource Graph query aks-lab azure-policy (kube-system)Syncs assignments every 15 minutesReports compliance every 15 minutes ConstraintTemplate+ Constraint(or generates VAP) Gatekeepergatekeeper-system kube-apiserver admission chainmutating (safeguards mutators) → schema → VAP / validation.gatekeeper.sh → ResourceQuota → etcd Real time: rejections / Warning headersFor new or updated requests Periodic: audit scanFor existing objects → compliance report
Figure 7-1 Admission handles what is new, and audit handles what already exists. Both are driven by the same policy definitions.

Flowchart: rolling out Audit → Warn → Deny

AuditRecord only · build a list Warnkubectl prints Warning Deny (dev)Server dry-run in CI Deny (prod)Exemptions with expiry Each step advances through a PR in the policy repo. Move to the next step only when the compliance rate meets the target.
Figure 7-2 Rolling out a policy is a release of cluster behavior

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.

Manifest problems (select any)
Cluster settings
Safeguards level
PSS level
Submit after setting.
$ kubectl apply -f deployment.yaml

Core commands and parameters

CommandPurposeKey parameters / notes
az aks enable-addons --addons azure-policyEnable Azure Policy add-onRequires registering Microsoft.PolicyInsights. The AVM module enables it by default.
az aks safeguards create / update / show / deleteDeployment 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 nameBuilt-in definition IDs are GUIDs. Do not hard-code them from memory.
az policy assignment createAssign to a cluster or resource group--policy, --scope, --params (effect, excludedNamespaces)
az policy state list / trigger-scanQuery compliance / trigger evaluationKubernetes results are still subject to the add-on's 15-minute reporting cycle
kubectl get constrainttemplates,constraintsPolicies landed in the clusterNames look like azurepolicy-k8sazurev…
kubectl apply --dry-run=serverPre-check admission in CIPasses 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)

Cost / permissions / risk No additional cost. Cluster Contributor is enough to turn on Safeguards. No Azure Policy permissions are needed, but the add-on must be enabled. Risk: Enforce rejects and modifies non-compliant deployments, including objects managed by Flux. Delete Safeguards after the lab so it does not affect hour 6.
Confirm the add-on is enabled:
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
Turn on Warn and exclude platform namespaces:
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.

Deploy a “counterexample”:
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
Check whether the GitOps-managed myapp is compliant (under Warn, existing objects are audited):
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 }
Switch to Enforce and observe the rejections and mutations:
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.

Cleanup (important):
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.

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

▶
Azure Policy and Kubernetes — Microsoft Azure
English · How Azure Policy manages Kubernetes through Gatekeeper
▶
Azure Policy for Kubernetes Clusters — vermacodes
English · Demo of add-on enablement, built-in policy assignment and the compliance view
▶
Anatomy of Azure Policy — John Savill's Technical Training
English · General principles of Azure Policy definitions, assignments, effects and exemptions

Official docs

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.

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

Module 8 · Summary, self-check and cleanup for the first five hours

50:00 – 60:00 · Tie the first five hours into one “cluster as code” map, clean up this hour's resources in dependency order, and walk through common automation failures with the troubleshooting tree
10 minSummary · Troubleshooting tree · CleanupCleanup order has dependencies★★★★☆
Learning goals
  • 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.
Prerequisites: Modules 1–7 of this hour. Importance: ★★★★☆

What: the big picture of the first five hours

HourCore questionHow this hour becomes code
Hour 1What happens behind az aks createThe same PUT is sent by the AVM module (module 1)
Hour 2Networking: overlay, outbound, ingressnetworkPlugin/Mode/Dataplane/Policy and CIDRs written into parameter files; default network policies for managed namespaces depend on the policy engine
Hour 3Identity: Entra, Workload Identity, Key VaultaadProfile, disableLocalAccounts, OIDC; pipelines also use federated credentials (module 3)
Hour 4Scaling: CA, NAP, KEDAAutoscaling settings are written into AVM parameters; quotas cap scaling (module 5)
Hour 5Automated operationsGitOps 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

  1. Fleet: delete the update run (including its approval gates) → delete the members → delete the Fleet (along with its auto-upgrade profile and policies).
  2. 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.
  3. Policy: az aks safeguards delete; delete this hour's policy assignments.
  4. GitOps: az k8s-configuration flux delete (prune deletes the myapp objects, so keep them if you need them) → az k8s-extension delete -n flux.
  5. Cluster: az aks delete -n aks-lab-bicep; if you will keep studying aks-lab tomorrow, stop it with az aks stop instead.
  6. When everything is finished: az group delete -n rg-aks-lab --yes --no-wait (and rg-aks-lab-snap).

When: keep or delete

ResourceContinue to hour 6?Recommendation
aks-lab + ACRNeededKeep; when pausing your study, use az aks stop
Flux configuration and myappReusableKeep (during the hour 6 upgrade, you can watch GitOps app availability)
aks-lab-bicep, FleetNot neededDelete
Backup vault, storage, snapshot RGNot neededDelete
Safeguards, team-aNot neededDelete, so it does not affect later labs
Common misconceptions ① “Deleting the resource group guarantees a clean slate”: objects outside it (snapshot resource groups, role assignments outside the node resource group, subscription-level policy assignments) are not removed with it. ② “az aks stop means I stop paying”: after stopping, the control plane and node compute are not billed, but disks, public IPs, load balancer rules and similar resources may still be billed (check current pricing). ③ “Deleting a Fleet deletes its member clusters”: it does not. Members are only unlinked.

Layered diagram: cluster as code

Policy as code (module 7): Azure Policy / Safeguards — constrains every layer below Orchestration: Fleet update runs (module 4) Recovery: Azure Backup / Velero (module 6) Delivery: GitOps (module 2) + CI (module 3) Tenancy: managed namespaces + quotas (module 5) Cluster baseline: AVM (module 1) = networking (hour 2) + identity (hour 3) + scaling (hour 4) Azure platform: ARM → AKS RP → control plane / node resource group (hour 1) Every layer has the same three parts: a declaration (Git/ARM), reconciliation (controllers), and observation (status/compliance)
Figure 8-1 Where the first five hours' capabilities sit on one diagram

Dependency diagram: cleanup order

updaterun (+gates) fleet members fleet backup instance trusted access backup ext vault / SA / snap RG flux configuration flux extension safeguards aks-lab-bicep rg-aks-lab Arrows mean “delete the left side first, then the right side.” The final resource group deletion can serve as a fallback, but objects outside the group need separate handling.
Figure 8-2 Cleanup dependencies: stop orchestration and protection first, then delete extensions, and finally delete the cluster

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

Generated after you select resources.
# The cleanup script will appear here

Inventory and cleanup commands

CommandPurposeNotes
az resource list -g $RG -o tableInventory resources in the resource groupCompare against this hour's creation list
az k8s-extension list -g $RG -c $CLUSTER -t managedClusters -o tableInventory cluster extensionsflux, azure-aks-backup, argocd
az k8s-configuration flux list -g $RG -c $CLUSTER -t managedClusters -o tableInventory GitOps configurationsDelete configurations before extensions
az fleet list -g $RG -o tableInventory FleetA Fleet without a hub has no nodes
az dataprotection backup-instance list -g $RG --vault-name $VAULT -o tableInventory protected instancesStop protection before the vault can be deleted
az snapshot list -g rg-aks-lab-snap -o tableInventory disk snapshotsCross-resource-group, easiest to forget
az aks stop -g $RG -n $CLUSTERPause the clusterNext time: az aks start
az group delete -n $RG --yes --no-waitDelete everythingCannot 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)

Cost / permissions / risk Deletion cannot be undone. If you plan to continue to hour 6, keep aks-lab, ACR, the Flux configuration and myapp.
Fleet:
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
Backup (cleanup block from module 6):
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
Policy and namespaces:
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
Extra clusters and identities:
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 or finish:
# 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
Verify:
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.”

Command-line exercise
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 table
2. Stop only aks-lab and keep all configuration.
az aks stop -g rg-aks-lab -n aks-lab
Scenario analysis question
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

▶
Deploy Faster with Azure Verified Modules — Microsoft Developer
English · Review of AVM's role in platform delivery
▶
Azure Kubernetes Fleet Manager — Azure Power Lunch
English · Fleet Manager overview, good for reviewing module 4

Official docs

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.

Shot 1 · 0–25s
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.
Shot 2 · 25–50s
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.
Shot 3 · 50–70s
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.
or score ≥ 70% on the quiz

Command cheat sheet

Commands in this hour are grouped by topic. Variables follow the course convention: RG=rg-aks-lab; LOC=canadacentral; CLUSTER=aks-lab

IaC (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

SymptomCheck firstCommon causesModule
Bicep restore failsaz bicep version, MCR connectivityCLI too old, proxy, version number1
New cluster: kubectl cannot connectpublicNetworkAccessAVM default Disabled1
flux show Non-Compliantkubectl describe gitrepository/kustomizationAuthentication, path, dependencies not ready, admission rejection2
Manual changes get revertedKustomization intervalDrift repair (expected behavior)2
AADSTS70021Assertion Subject in the errorFederated credential subject mismatch3
Pipeline ForbiddenRole assignment scopeMissing data-plane role or wrong scope3
Update run PendingMember messageMaintenance window, region not yet released, approval gate4
Deployment 0/Nkubectl describe rsQuota rejection, admission rejection5, 7
Backup validation failsvalidate-for-backup outputMSI permissions, Trusted Access6
Data is empty after restoreRestore configurationConflict policy Skip, no volume data included6
Pod Pending after EnforcePod resourcesMutator default 2Gi requests7

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

End-to-end cluster as code: AVM baseline → GitOps delivery → pipeline changes only Git → Fleet staged node image updates → backup and restore drill → policy rollout
About 60–90 minIncurs costs; clean up per module 8 when done
Scenario

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

Cluster baseline: Use the module 1 AVM Bicep to deploy aks-lab-bicep, and add an aksManagedNodeOSUpgradeSchedule maintenance configuration to the parameters. Save the what-if output as whatif.txt as review material.
GitOps delivery: Create 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.
Pipeline changes only Git: Set up the module 3 “pull mode” workflow: build the new myapp version, push it to ACR (OIDC + AcrPush), then open a PR against aks-gitops. After the merge, verify that both clusters roll to the new version.
Fleet staged update: Create a Fleet with 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).
Backup and restore drill: Enable Azure Backup for 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).
Policy rollout: Turn on Safeguards at Warn on 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.
Team self-service: Create a managed namespace for team-a (2 CPU / 4Gi limits) and grant two roles to the Entra group. Use a namespace-scoped fluxConfiguration to deploy a Deployment for team-a, and verify what happens when the quota is exceeded.
Cleanup: Use the module 8 “cleanup script generator” to clean up in dependency order. Keep only aks-lab (stopped).
Acceptance checklist

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

Verification basis for every technical fact in this hour (verified 2026-11-15)
TopicVerification resultSources (accessed 2026-11-15)
AKS version calendarGA: 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 pageSupported Kubernetes versions in AKS (page updated 2026-10-21)
Bicep AVM moduleavm/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 parameterMCR tag list · Module source (0.14.0 tag)
Terraform AVM module0.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_profileTerraform Registry · GitHub variables.tf
Tool versionsLatest 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.3Each project's GitHub Releases
Flux extensionmicrosoft.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 masterFlux release notes · Flux tutorial · Parameters
Argo CD extensionTutorial (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 supportedArgo CD tutorial · Extension list
Fleet ManagerUp 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 daysConcepts · Update runs · Approvals · Auto-upgrade · FAQ · Quickstart
Managed namespacesCLI ≥ 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 managedManaged namespaces
Azure Backup for AKSExtension 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.0Backup CLI · Restore CLI · Support matrix (2026-10-31)
VeleroVelero 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 KubernetesThe 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 Safeguardsaz 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-openDeployment Safeguards (doc 2026-06-02, updated 2026-10-20); CLI 2.84 -h tested
Open-source policy enginesGatekeeper 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 show and az 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.tf on 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.