Prometheus & Grafana Lesson 3: Moving to the Cloud (Azure)

Replace the “Prometheus + Alertmanager + Grafana” stack you built locally with Compose in Lessons 1 and 2 with Azure managed services: AKS managed collection → Azure Monitor workspace → Azure Managed Grafana → Azure Monitor alerting
Azure Monitor managed PrometheusAzure Managed Grafana · StandardAKS · canadacentralCRD group azmonitoring.coreos.com/v1Verified against learn.microsoft.com · 2026-11-15
Overall learning goals
  • Be able to explain self-managed Prometheus, Azure Monitor managed Prometheus, and Container Insights the boundaries between the three and how they combine, and make a justified architecture choice for an AKS team.
  • Use az aks update --enable-azure-monitor-metrics to connect the AKS cluster aks-prom-lab to an Azure Monitor workspace amw-prom-lab, and identify the extra ama-metrics* components in the cluster and how data is written to the workspace with the managed identity token.
  • Scrape myapp in three ways (port 5000,myapp_http_requests_total unified metrics, etc.): PodMonitor / ServiceMonitor (group azmonitoring.coreos.com/v1),ama-metrics-prometheus-config ConfigMap, Pod annotations; and tune ama-metrics-settings-configmap (minimal ingestion profile, keep list, cluster_alias).
  • Create Azure Managed Grafana amg-prom-lab, and understand the two identity chains: people → Entra ID → Grafana Admin/Editor/Viewer; Grafana managed identity → Monitoring Data Reader → workspace query endpoint.
  • Rewrite the Lesson 2 Prometheus rules as managed Prometheus rule groups (Microsoft.AlertsManagement/prometheusRuleGroups), via Action Group to send email; enable recommended alerts.
  • Use Container Insights (ContainerLogV2,KubeEvents,KubePodInventory), to align logs and metrics at the same point in time; independently troubleshoot cloud faults such as “no data / 403 / rule not firing / throttled”, and estimate costs and clean up resources per the checklist.

1-hour time allocation table

#TimeModuleCore contentAnimation / interactionLab (AKS aks-prom-lab)
0Before classWarm-up and AKS preparationResource providers, variables, ACR + AKS, push myapp to ACR and deployEnvironment self-check listmyapp on AKS /metrics reachable
100–05Monitoring architecture choices on AzureSelf-managed kps / managed Prometheus / Container Insights / hybrid remote_write; responsibility boundariesRequirements → architecture recommenderDraw this lesson's target architecture and list resources
205–13Managed Prometheus and AKS integrationAzure Monitor workspace, DCR/DCE, ama-metrics components, default targets and minimal ingestion profile, control-plane metricsCore animation: Managed collection → workspace → Grafana data and identity flowCreate amw-prom-lab and enable metrics
313–21Scrape configuration: ConfigMap, PodMonitor, ServiceMonitorFour scrape entry points, target allocator, settings ConfigMap, promconfigvalidator, label limitsScrape configuration diagnostic simulatorPodMonitor scrapes myapp, verify targets
421–29Managed Grafana: identity, permissions and data sourcesStandard X1/X2, Entra sign-in, Grafana roles, system-assigned managed identity, Monitoring Data Reader, provisioned dashboardsStep-by-step animation of the two identity chains (you can “unplug” a role to see the error)Create amg-prom-lab and build the myapp dashboard
529–37Managed alert rule groups and Action GroupsRule group scope, record/alert, for/severity/autoResolve, Action Groups, recommended alerts, rule conversion toolAlert timeline simulator5xx alert → email → auto-resolve
637–45Container Insights, correlating logs and metricsama-logs, DCR streams, cost presets, ContainerLogV2, KQL, side-by-side correlation in GrafanaMetric spike → logs for the same time windowEnable the “Logs and events” preset, query myapp errors with KQL
745–54Cloud troubleshooting in practiceNo data, 403, rule not firing, throttling, case insensitivity, 422 duplicate seriesFault injection: which hop is brokenReproduce and fix 5 faults
854–60Cost, cleanup and self-testMetering items and estimates, cost-saving measures, least privilege, cleanup order and leftover resourcesCost calculator + troubleshooting decision treeEstimate this lab's cost and clean up completely
—After classCheat sheet · Capstone labOne-click script builds the full managed monitoring chain from scratch and verifies itFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillM1M2M3M4M5M6M7M8Key commandsLab
Choose a monitoring architecture for AKS✓✓···✓·✓—M1 architecture diagram
Enable managed Prometheus·✓····✓·az monitor account create,az aks update --enable-azure-monitor-metricsM2
scrape custom application metrics··✓···✓·kubectl apply PodMonitor,kubectl create configmap ama-metrics-prometheus-configM3
control ingestion volume and cardinality·✓✓···✓✓ama-metrics-settings-configmap,metricRelabelingsM3 / M8
Grafana identity and permissions···✓··✓✓az grafana create,az role assignment createM4
PromQL queries and dashboards·✓✓✓✓✓··az grafana dashboard import, query APIM4
managed rules and notifications····✓·✓·az alerts-management prometheus-rule-group create,az monitor action-group createM5
log and metric correlation···✓·✓✓·az aks enable-addons --addon monitoring, KQLM6
cloud fault localization·✓✓✓✓·✓✓kubectl logs -c prometheus-collector/config-reader/addon-token-adapterM7
cost estimation and cleanup✓····✓·✓az group delete, Retail Prices APIM8

Topics excluded from this lesson (and where to learn them)

TopicWhy it's not in this lessonWhere to learn it
PromQL basics, scrape interval,rate() principlesCovered in Lesson 1; used directly in this lessonLesson 1
Alertmanager routing tree, inhibition, silencesOn the managed path, Azure Monitor alerts + Action Groups replace this; concept mapping in module 5Lesson 2
AWS managed services (AMP / AMG / ADOT)Belongs to another cloudLesson 4
kube-prometheus-stack, Prometheus Operator reconciliation detailsThis lesson only uses managed add-ons; the self-managed stack is explained more thoroughly on kindLesson 5
remote_write to an Azure Monitor workspace (self-managed Prometheus remote_write + managed identity sidecar), Azure Arc clustersBelongs to hybrid/migration architecture; module 1 only positions itLesson 6 · Official: remote-write
Application Insights / OpenTelemetry tracingBeyond the scope of “metrics + logs”Official: AKS OTLP
Full IaC (Bicep/Terraform) of this lesson's resourcesThis lesson uses the az CLI so that each step is visibleTerraform course Lesson 3; official Bicep templates see module 2 links

How to use this courseware

10 pages per module
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · narration · video. Read “Principles” and “Animations” first, then do the “Lab”; cloud labs incur costs, so clean up using the module 8 checklist.
Learning progress
A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress, saved in this browser (cleared on refresh if local storage is blocked).
Chinese narration
The “Narration” page uses the browser's built-in Web Speech API (en-US) to read the narration script aloud; without a Chinese voice pack, the script can still be read or passed to a TTS tool.
Version and fact notes All Azure details in this lesson were checked against learn.microsoft.com on 2026-11-15: enablement parameters --enable-azure-monitor-metrics / --azure-monitor-workspace-resource-id / --grafana-resource-id / --enable-control-plane-metrics; custom scrape ConfigMap ama-metrics-prometheus-config (and -node,-node-windows) and the settings ConfigMap ama-metrics-settings-configmap (schema v2); PodMonitor/ServiceMonitor API groups azmonitoring.coreos.com/v1; rule group API 2023-03-01; new Managed Grafana instances can only use Standard (Essential can no longer be created; full deprecation on 2027-03-31). Prices come from the Azure Retail Prices API (canadacentral, USD). For the Grafana major versions currently selectable in Managed Grafana, please refer to az grafana show the official documentation, which prevails (the docs already describe the Grafana 13 data source migration). Lessons 1, 2 and this lesson were written in parallel; cross-lesson references follow the course-wide convention (myapp port 5000, metric name myapp_*).

Module 0 · Warm-up and AKS preparation (complete before class)

Move Lesson 1's myapp (Flask + gunicorn + Redis, port 5000, with /metrics) onto AKS, so there is a target with metrics to scrape for managed collection
Before class ≈ 15 min (AKS creation takes about 5–8 min)canadacentralIncurs costs
Prerequisites
  • Completed Lesson 1 and Lesson 2: locally, ~/promlab contains the myapp source (exposing myapp_http_requests_total{method,route,status},myapp_http_request_duration_seconds, and myapp_redis_up) and the alert rules written in Lesson 2 prometheus/rules/*.yml.
  • Tools: Azure CLI (az version, latest recommended; az grafana is part of the amg extension,az alerts-management is part of the alertsmanagement extension; first use prompts automatic installation), kubectl, jq. The Docker and K8s courses have already installed these tools.
  • Azure permissions: on the subscription or resource group, rg-prom-lab have the Owner, or Contributor + User Access Administrator (linking Grafana requires assigning a role to its managed identity). Viewing data requires Monitoring Reader / Monitoring Contributor.
  • If Docker is not installed locally, you can use az acr build to build the image in the cloud (this lesson does this by default).

Step 1: variables and resource providers

All commands in this lesson reference the variable set below. Managed Grafana and ACR names must be globally unique, so a random suffix is added; write the suffix down, and re-export these variables when you open a new terminal.

# ~/promlab/azure/env.sh — source this file first in every new terminal
export SUFFIX=${SUFFIX:-$RANDOM}          # after the first run, hard-code the value here
export RG=rg-prom-lab
export LOC=canadacentral
export AKS=aks-prom-lab
export AMW=amw-prom-lab
export AMG=amg-prom-lab-$SUFFIX           # globally unique (course naming: amg-prom-lab + suffix)
export ACR=acrpromlab$SUFFIX              # lowercase letters and digits only
export LAW=law-prom-lab                   # Log Analytics workspace (module 6)
export AG=ag-prom-lab                     # Action Group (module 5)
export ALERT_EMAIL=you@example.com        # change to your own email address
mkdir -p ~/promlab/azure && cd ~/promlab/azure
source ./env.sh
az login
az account show --query "{sub:name,id:id,user:user.name}" -o table

# Resource providers required by managed Prometheus / Grafana / alerts (official prerequisites)
for p in Microsoft.ContainerService Microsoft.Insights Microsoft.AlertsManagement \
         Microsoft.Monitor Microsoft.Dashboard Microsoft.OperationalInsights Microsoft.ContainerRegistry; do
  az provider register --namespace $p
done
az provider list --query "[?namespace=='Microsoft.Monitor' || namespace=='Microsoft.Dashboard'].{ns:namespace,state:registrationState}" -o table
Namespace           State
------------------  ----------
Microsoft.Dashboard Registered
Microsoft.Monitor   Registered
Note Official documentation requires: in environments where managed Prometheus is enabled,do not install the aks-preview extension (if it was installed: az extension remove --name aks-preview), the cluster must use managed identity (default since CLI 2.49.0).

Step 2: resource group, ACR and AKS (no monitoring enabled yet)

Deliberately create a “bare” cluster first; module 2 will then use az aks update to enable managed Prometheus, so you can see for yourself what is added before and after enabling kube-system to it.

az group create -n $RG -l $LOC
az acr create -g $RG -n $ACR --sku Basic

az aks create -g $RG -n $AKS -l $LOC \
  --node-count 2 --node-vm-size Standard_D2s_v5 \
  --enable-managed-identity --generate-ssh-keys \
  --attach-acr $ACR --tier free
az aks get-credentials -g $RG -n $AKS --overwrite-existing
kubectl get nodes -o wide
NAME                                STATUS   ROLES    AGE   VERSION
aks-nodepool1-31718369-vmss000000   Ready    <none>   3m    v1.3x.x
aks-nodepool1-31718369-vmss000001   Ready    <none>   3m    v1.3x.x

If not specified, --kubernetes-version the regional default version is used; check version numbers against az aks get-versions -l $LOC -o table (the K8s course Lesson 6 verified that AKS 1.37 reached GA in 2026-10).

Step 3: build the myapp image and push it to ACR

If Lesson 1's ~/promlab/myapp already exists, build it directly; otherwise use the minimal version below (metric names match the course-wide convention exactly). Because gunicorn multi-process workers each have their own memory, you must use PROMETHEUS_MULTIPROC_DIR to let prometheus_client write samples to a shared directory and merge them.

import os, time
from flask import Flask, Response, request, g
import redis
from prometheus_client import (Counter, Histogram, Gauge, CollectorRegistry,
                               generate_latest, CONTENT_TYPE_LATEST, multiprocess)

app = Flask(__name__)
r = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, socket_timeout=0.5)

REQS = Counter("myapp_http_requests_total", "HTTP requests", ["method", "route", "status"])
LAT = Histogram("myapp_http_request_duration_seconds", "Request latency", ["route"],
                buckets=(0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5))
REDIS_UP = Gauge("myapp_redis_up", "1 if Redis is reachable", multiprocess_mode="max")

@app.before_request
def _start():
    g.t0 = time.perf_counter()

@app.after_request
def _record(resp):
    route = request.url_rule.rule if request.url_rule else "unmatched"
    if route != "/metrics":
        REQS.labels(request.method, route, str(resp.status_code)).inc()
        LAT.labels(route).observe(time.perf_counter() - g.t0)
    return resp

@app.get("/")
def index():
    n = r.incr("hits")
    return f"Hello from myapp! hits={n}\n"

@app.get("/healthz")
def healthz():
    return "ok\n"

@app.get("/error")
def error():
    return "boom\n", 500

@app.get("/metrics")
def metrics():
    try:
        r.ping(); REDIS_UP.set(1)
    except Exception:
        REDIS_UP.set(0)
    reg = CollectorRegistry()
    multiprocess.MultiProcessCollector(reg)
    return Response(generate_latest(reg), mimetype=CONTENT_TYPE_LATEST)
FROM python:3.13-slim
WORKDIR /app
RUN pip install --no-cache-dir flask gunicorn redis prometheus_client
COPY app.py .
ENV PROMETHEUS_MULTIPROC_DIR=/tmp/prom
RUN useradd -r -u 10001 app && mkdir -p /tmp/prom && chown app /tmp/prom
USER 10001
EXPOSE 5000
# Clear the multi-process directory on every start to avoid leftover files from old workers
CMD ["sh", "-c", "rm -rf /tmp/prom/* && exec gunicorn -w 2 -b 0.0.0.0:5000 app:app"]
cd ~/promlab/myapp
az acr build -r $ACR -t myapp:1.0 .
az acr repository show-tags -n $ACR --repository myapp -o table
Result
--------
1.0

Step 4: in the namespace myapp deploy myapp + Redis

Two points to note, both needed in module 3: ① the container port named as http (PodMonitor/ServiceMonitor require a “named port”); ② both the Pod and the Service carry the label app: myapp.

apiVersion: v1
kind: Namespace
metadata: { name: myapp }
---
apiVersion: apps/v1
kind: Deployment
metadata: { name: redis, namespace: myapp }
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 }] }
---
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_NAME.azurecr.io/myapp:1.0
        env: [{ name: REDIS_HOST, value: redis }]
        ports: [{ name: http, containerPort: 5000 }]
        readinessProbe: { httpGet: { path: /healthz, port: http }, periodSeconds: 5 }
        resources: { requests: { cpu: 100m, memory: 128Mi }, limits: { memory: 256Mi } }
---
apiVersion: v1
kind: Service
metadata: { name: myapp, namespace: myapp, labels: { app: myapp } }
spec:
  selector: { app: myapp }
  ports: [{ name: http, port: 5000, targetPort: http }]
cd ~/promlab/azure
sed "s/ACR_NAME/$ACR/" myapp.yaml | kubectl apply -f -
kubectl -n myapp rollout status deploy/myapp
kubectl -n myapp port-forward svc/myapp 5000:5000 &
sleep 2; curl -s localhost:5000/; curl -s localhost:5000/error; curl -s localhost:5000/metrics | grep -E '^myapp_(http_requests_total|redis_up)'
kill %1
Hello from myapp! hits=1
boom
myapp_http_requests_total{method="GET",route="/",status="200"} 1.0
myapp_http_requests_total{method="GET",route="/error",status="500"} 1.0
myapp_redis_up 1.0

Step 5: give myapp a continuous traffic generator

Managed-service data has an end-to-end delay of 1–2 minutes, so continuous traffic lets you see live curves in every module. About 10% of requests go to /error, preparing for the module 5 alerts.

kubectl -n myapp run loadgen --image=curlimages/curl:8.11.1 --restart=Always -- \
  sh -c 'while true; do for i in 1 2 3 4 5 6 7 8 9; do curl -s -o /dev/null http://myapp:5000/; done; curl -s -o /dev/null http://myapp:5000/error; sleep 1; done'
kubectl -n myapp get pods

Warm-up: answer from memory (30 seconds)

In Lesson 1, how does Prometheus know where myapp is?

through scrape_configs (in Compose it is static_configs 's myapp:5000 On K8s this is replaced by kubernetes_sd_configs or the Operator's ServiceMonitor/PodMonitor; the managed version in this lesson uses the same concepts, only with the API group changed to azmonitoring.coreos.com.

In Lesson 2, which components does an alert pass through from firing to email?

Prometheus rule evaluation (pending → firing) → sent to Alertmanager → routing-tree grouping / inhibition / silences → receiver (email / webhook). In the managed version, rule evaluation is done by the rule group, and “Alertmanager” is replaced by Azure Monitor alerts + Action Groups (module 5).

Prometheus stores its own data; where does the managed service store it?

Stored in an Azure Monitor workspace (resource type Microsoft.Monitor/accounts), the cluster only runs agent-mode collectors and keeps no local TSDB (detailed in module 2).

Environment self-check list
Cost reminder Billing starts at this step: 2 × Standard_D2s_v5 (canadacentral Linux pay-as-you-go 0.107 USD/hour per node; retail price API 2026-11-15) + load balancer and disks + ACR Basic. When you pause, you can az aks stop -g $RG -n $AKS (stopped clusters incur no node compute charges, but disks and other resources still incur charges; see official docs); run the module 8 cleanup right after finishing this lesson.

Module 1 · Monitoring architecture choices on Azure

00:00 – 05:00 · “Prometheus + Grafana” comes in four patterns on Azure; first decide who owns storage, who owns identity, and who owns alerting
5 minManaged Prometheus GAManaged Grafana Standard★★★★
Learning goals
  • List the four common AKS monitoring architectures on Azure, and state who is responsible for collection / storage / query / alerting / identity in each.
  • Understand the division of labour among the Azure Monitor workspace, the Log Analytics workspace and Managed Grafana, and why they are three independent resources.
  • Given requirements such as retention, team skills, multiple clusters, compliance and cost, make a justified recommendation.
Prerequisites: Lesson 1's Prometheus architecture (scraping, TSDB, rules, Alertmanager). Importance:★★★★ (choosing the wrong architecture means reworking everything later)

What: four patterns on Azure

ArchitectureCollectionStorageQuery / visualizationAlerting
A. Self-managed: kube-prometheus-stack running in AKSPrometheus (Operator)In-cluster TSDB + PV (Thanos/Mimir can be added)Self-managed GrafanaSelf-managed Alertmanager
B. Fully managed (this lesson's main track)AKS add-on ama-metrics (the containerized Azure Monitor agent; runs Prometheus scraping in agent mode)Azure Monitor workspace (Microsoft.Monitor/accounts)Azure Managed Grafana (Microsoft.Dashboard/grafana) or the built-in Grafana view in the portalPrometheus rule group → Azure Monitor alerts → Action Group
C. Hybrid: self-managed Prometheus + remote_writeSelf-managed Prometheusshort local retention + remote_write to the Azure Monitor workspaceManaged Grafana / self-managed both workEither works
D. Container Insights only (logs-first)ama-logsLog Analytics workspace (KQL tables)Portal Insights views, workbooksLog search alerts / platform metric alerts

The officially recommended complete AKS monitoring is the combination of B + D: metrics via managed Prometheus, logs and events via Container Insights, and Container Insights' cost presets include a “Logs and Events” group, noted as “recommended when managed Prometheus is enabled”: performance metrics go to Prometheus, and Log Analytics receives only logs and events, avoiding paying twice for the same metrics.

Why: why go managed

  • Outsourcing storage operations: no need to manage TSDB disks, compaction, WAL, remote storage and long-term retention; the workspace is billed by ingested samples + queried samples, not by disks and nodes.
  • Unified identity: the collector writes with the cluster's managed identity, Grafana reads with its own managed identity, and people sign in to Grafana with Entra ID — no more basic-auth passwords or long-lived API keys.
  • Alerts enter the Azure Monitor system: shares Action Groups, alert processing rules (maintenance-window silencing) and ITSM integration with platform metric alerts and log alerts.
  • Trade-offs: reduced customizability (for example, metric renaming is not supported, the ConfigMap does not support global external_labels, and queries must include __name__ matchers, and the system is case-insensitive), plus workspace quota limits (active time series, events per minute).

How: resources and responsibility boundaries

ResourceTypeName in this lessonWhat it contains
Azure Monitor workspaceMicrosoft.Monitor/accountsamw-prom-labPrometheus time series; creating it automatically generates a DCR and DCE of the same name, placed in a managed resource group MA_amw-prom-lab_canadacentral_managed
Log Analytics workspaceMicrosoft.OperationalInsights/workspaceslaw-prom-labKQL tables such as ContainerLogV2, KubeEvents, KubePodInventory
Azure Managed GrafanaMicrosoft.Dashboard/grafanaamg-prom-lab-<suffix>dashboards, data sources, Grafana alerts (Standard); system-assigned managed identity
Prometheus rule groupsMicrosoft.AlertsManagement/prometheusRuleGroupsmyapp-rules etc.record / alert rules, scope = workspace (+ optional cluster)
Action GroupMicrosoft.Insights/actionGroupsag-prom-labreceivers such as email, SMS, webhooks, Logic Apps, ITSM

When: how to choose

  • If the team already has mature self-managed Prometheus operations, needs Thanos/Mimir multi-tenancy or a global view, or must run offline/private → A or C.
  • Multiple AKS clusters, a wish for unified identity and alerting, limited platform-team staff, and willingness to accept managed-service limits → B (+ D for logs).
  • During migration: keep existing Prometheus rules and dashboards, first remote_write to the workspace → C, then gradually move to B.
  • If you only care that the Pod started and what errors appear in the logs → start with D, but metric dashboards and PromQL alerts are ultimately still recommended with B.

Comparison with similar technologies

Azure managed (this lesson)AWS managed (Lesson 4)Self-managed kps (Lesson 5)
CollectorAKS add-on ama-metrics (DaemonSet + replicas + target allocator)AMP managed scraper, or ADOT / self-managed Prometheus remote_writePrometheus managed by the Prometheus Operator
StorageAzure Monitor workspaceAMP workspaceLocal TSDB + PV
Write identityCluster managed identity (Entra token)IAM role + SigV4None (local)
VisualizationManaged Grafana (Entra sign-in)AMG (IAM Identity Center)Self-managed Grafana
AlertingRule group → Azure Monitor alerts → Action GroupAMP rules + AMP Alertmanager → SNSPrometheusRule → Alertmanager
Common misconceptions① “Managed Prometheus means Azure runs a Prometheus server for me” — no. The cluster runs agent-mode collectors with no local TSDB to query; queries go to the workspace's query endpoint. ② “Enabling Container Insights gives you Prometheus metrics” — the two are independent features with separate workspaces and billing; you can enable either one alone. ③ “Managed Grafana stores metrics” — Grafana never stores time series; it only uses its managed identity to query the workspace.

Architecture diagram: this lesson's target architecture (B + D)

AKS cluster aks-prom-lab myapp (ns myapp):5000/metricsmyapp_http_requests_total etc. ama-metrics (kube-system) replicas + node DaemonSet + ksm+ operator-targets (target allocator)agent-mode scraping, no local TSDB ama-logs (kube-system)DaemonSet + ama-logs-rsstdout/stderr, events, manifests Azure Monitor workspaceamw-prom-labDCE ingestion → DCR → time-series storagePromQL query endpoint Log Analytics workspacelaw-prom-lab · KQLContainerLogV2 / KubeEvents cluster MI token Managed Grafanaamg-prom-lab-xxxx · Standardsystem-assigned managed identityPeople: Entra ID sign-in PromQL KQL rule groups + alertsprometheusRuleGroups→ Azure Monitor alerts→ Action Group ag-prom-lab→ email / webhook evaluation
Figure 1-1: metrics go to the Azure Monitor workspace, logs go to Log Analytics; Grafana reads both with its managed identity; alerts are evaluated by rule groups on the workspace side

Comparison diagram: local Compose (Lessons 1 and 2) → Azure managed (this lesson)

~/promlab (Docker Compose)Azure managed prometheus.yml scrape_configs Prometheus TSDB (9090) rules/*.yml Alertmanager (9093) receiver Grafana (3000) admin password PodMonitor / ama-metrics-prometheus-config Azure Monitor workspace Prometheus rule groups (ARM resources) Azure Monitor alerts + Action Groups Managed Grafana + Entra ID + Grafana roles CRD group changed to azmonitoring.coreos.com az-prom-rules-converter converts to ARM routing tree → per-rule actionGroupId
Figure 1-2: the counterpart of each local component on the managed path (same concepts; the management plane is now Azure resources and RBAC)

Interactive: requirements → architecture recommender

Tick your team's requirements; the recommender scores each architecture by “who is responsible for storage, identity and alerting”. The note under each requirement explains why it adds or subtracts points for an architecture — this is the reasoning to present at an architecture review.

Tick at least one requirement.
Waiting for selection…

Reconnaissance commands for this module

Before choosing, check the current state: which workspaces, Grafana instances and rule groups already exist in the subscription, and whether the cluster already has monitoring enabled.

CommandPurposeKey parameters / notes
az monitor account listList Azure Monitor workspaces-g filter by resource group; note DefaultAzureMonitorWorkspace-* is created automatically when no workspace is specified
az monitor log-analytics workspace listList Log Analytics workspacesDefaultWorkspace-* same as above
az grafana listList Managed Grafanarequires amg extension
az aks show --query azureMonitorProfileWhether the cluster has managed Prometheus enabledmetrics.enabled
az aks show --query addonProfiles.omsagentWhether Container Insights (monitoring add-on) is enabledconfig.logAnalyticsWorkspaceResourceID
az resource list --resource-type Microsoft.AlertsManagement/prometheusRuleGroupsList Prometheus rule groupsCommonly used during cleanup
source ~/promlab/azure/env.sh
az monitor account list -o table
az monitor log-analytics workspace list --query "[].{name:name,rg:resourceGroup,loc:location}" -o table
az grafana list --query "[].{name:name,rg:resourceGroup,sku:sku.name}" -o table
az aks show -g $RG -n $AKS --query "{metrics:azureMonitorProfile.metrics.enabled, ci:addonProfiles.omsagent.enabled}" -o json
{
  "ci": null,
  "metrics": null
}

How to verify: Both should be null/false means the cluster is 'bare'. Common error: When a colleague enables monitoring from the portal with “one-click enable” and does not choose a workspace, a default workspace is created in DefaultRG-<region> — costs and data end up there, which is easy to miss during audits. Production use: Put these commands into the platform inspection script, and raise an alert when a cluster has no monitoring or a default workspace is found.

View available regions and SKUs

az provider show -n Microsoft.Monitor --query "resourceTypes[?resourceType=='accounts'].locations" -o tsv | tr '\t' '\n' | grep -i canada
az provider show -n Microsoft.Dashboard --query "resourceTypes[?resourceType=='grafana'].locations" -o tsv | tr '\t' '\n' | grep -i canada

both should appear Canada Central If your region does not support Managed Grafana, place Grafana in a nearby region; it is only the query side, and cross-region queries add a little latency and egress traffic.

Lab 1: draw your target architecture and list resources (about 4 min)

Confirm the current state: run the reconnaissance commands on the “Commands” page and note the existing workspaces and Grafana. If the organization already has a shared Azure Monitor workspace, confirm with the platform team whether to reuse it — this lesson creates a new one for isolation amw-prom-lab.
Evaluate with the recommender: on the “Animation” page, tick the requirements that match your team, and note the two highest-scoring architectures and the reasons.
Write the resource list (save as ~/promlab/azure/ARCHITECTURE.md, then tick off each item in later modules):
Target: architecture B (managed Prometheus + Managed Grafana) + D (Container Insights: logs and events only)
- [ ] Azure Monitor workspace amw-prom-lab (canadacentral)           module 2
- [ ] AKS aks-prom-lab with azureMonitorProfile.metrics enabled             module 2
- [ ] myapp scrape: PodMonitor azmonitoring.coreos.com/v1           module 3
- [ ] Managed Grafana amg-prom-lab-<suffix> (Standard X1)         module 4
- [ ] Grafana MI → Monitoring Data Reader @ amw-prom-lab         module 4
- [ ] rule group myapp-rules + Action Group ag-prom-lab               module 5
- [ ] Log Analytics law-prom-lab + monitoring add-on (Logs and Events) module 6
- [ ] Cleanup: az group delete + check MA_*_managed / DefaultRG-*      module 8
Estimate the order of magnitude: 2 nodes, 2 myapp replicas, default targets with minimal ingestion — enter these into the module 8 cost calculator first to get an intuition for the monthly upper bound.
Cleanup: this lab creates no resources, so there is nothing to clean up.

Case 1: a platform team with 30 AKS clusters migrates from self-managed to managed

Problem: Each cluster ran its own kube-prometheus-stack; Prometheus memory grew with node count, Thanos sidecars and object storage were costly to maintain, and Grafana accounts were distributed by hand. Approach: Create 4 Azure Monitor workspaces by “environment × region”, and enable --enable-azure-monitor-metrics for all clusters, pointing them at the matching workspace; one Managed Grafana Standard instance connects to the 4 workspaces; Grafana roles are bound to Entra groups (Grafana Admin to the platform group, Viewer to application teams). Configuration: Azure Policy enforces enabling the metrics add-on on new clusters (the official policy template is provided). Limitations: The original PrometheusRule has to be converted with az-prom-rules-converter into rule groups; custom recording-rule names that differ only in case must be unified (workspaces are case-insensitive).

Case 2: a financial customer requires 13-month retention and private network access

Problem: Audit requires metric retention beyond one year, and all access must go over the private network. Approach: Use architecture B; enable private endpoints on both the workspace and Grafana (Grafana private endpoints are supported only in Standard), and have the cluster write through an Azure Monitor Private Link Scope. Limitations: The official troubleshooting documentation notes that if a private AKS cluster is also linked to another service's AMPLS, “No configuration present for the AKS resource” appears — review the network design against the official Private Link documentation first. Retention and quotas follow the Azure Monitor service limits page.

Case 3: a hybrid architecture during migration

Problem: A business team has over a hundred Grafana dashboards bound to a self-managed Prometheus data source and cannot switch overnight. Approach: Architecture C: self-managed Prometheus keeps 15 days of local data while remote_write-ing to the Azure Monitor workspace; add a “managed Prometheus” data source in Managed Grafana and use az grafana backup/restore --remap-data-sources to migrate the dashboards. Limitations: During dual writes, costs stack up; if the same cluster enables both the add-on and remote_write, duplicate series can occur (possibly returning 422), so you must distinguish cluster labels or keep only one write path.

Common pitfalls during selection

After enabling, data went into DefaultAzureMonitorWorkspace-canadacentral (DefaultRG-canadacentral)

Cause: Not specifying --azure-monitor-workspace-resource-id the workspace at enablement: official behaviour is to use the resource group's default workspace; if none exists, one is DefaultRG-<cluster_region> created in DefaultAzureMonitorWorkspace-<mapped_region>.

az monitor account list --query "[?starts_with(name,'DefaultAzureMonitorWorkspace')].{name:name,rg:resourceGroup}" -o table
az aks show -g $RG -n $AKS --query azureMonitorProfile -o json

Fix: First az aks update --disable-azure-monitor-metrics, then re-enable with the correct workspace ID (module 2); once you confirm no other cluster uses it, delete the default workspace.

Portal message: You can't create new Essential workspaces

Cause: Managed Grafana's Essential tier can no longer be created; existing instances are scheduled for full deprecation on 2027-03-31.

Fix: Always create Standard for new instances (in the CLI the --sku-tier default is Standard); migrate existing Essential instances per the official migration guide.

Resource 'amw-prom-lab' was disallowed by policy

Cause: The organization's naming/tagging policy blocked the workspace, or blocked the DCR/DCE created automatically with it (the names are fixed and located in the MA_<workspace name>_<region>_managed resource group; the names cannot be changed).

az policy assignment list --query "[].{name:displayName,scope:scope}" -o table

Fix: Official guidance is to set a policy exemption for the managed resource group and the DCR/DCE.

The cluster also runs a self-managed kube-prometheus-stack; worried about CRD conflicts

Analysis: The add-on's CRDs are in the azmonitoring.coreos.com group, which does not conflict with the open-source monitoring.coreos.com ; the add-on does not read the open-source ServiceMonitor objects (officially described as deliberate isolation).

kubectl get crd | grep -E 'coreos.com'

Fix: no fix needed; but when migrating, copy one for each target that needs managed scraping, in the azmonitoring.coreos.com/v1 version of the Monitor.

Command-line tasks
1. With a single command, determine whether cluster aks-prom-lab has managed Prometheus and Container Insights enabled.
az aks show -g rg-prom-lab -n aks-prom-lab --query "{metrics:azureMonitorProfile.metrics.enabled, ci:addonProfiles.omsagent.enabled}" -o json
2. List all “default” Azure Monitor workspaces in the subscription, and find out who is paying for them unintentionally.
az monitor account list --query "[?starts_with(name,'DefaultAzureMonitorWorkspace')].{name:name,rg:resourceGroup,loc:location}" -o table
Scenario analysis
A five-person application team has one AKS cluster, no dedicated SRE, needs PromQL alerts and three dashboards, and only looks at errors in the logs. Which architecture do you recommend? What should you warn them about?

Recommend B + D (managed Prometheus + Managed Grafana Standard X1 + the Logs and Events preset of Container Insights): no storage operations burden, unified identity. Warnings: ① Grafana is billed per instance-hour plus active users, so even small teams have a fixed cost — check whether the built-in portal Grafana views are sufficient; ② the default minimal ingestion keeps only the metrics used by dashboards and recommended alerts, so custom metrics must be scraped with your own configuration; ③ logs are billed per GB, so use namespace filtering and ContainerLogV2; ④ rule groups and Action Groups are both ARM resources — include them in IaC.

Verified teaching videos

▶
Azure Monitor's cloud native offering with Kubernetes Monitoring — Microsoft Azure
English · official channel · explains the overall positioning of managed Prometheus + Managed Grafana + Container Insights (recorded around 2023; parameter details follow this lesson)
▶
Azure Kubernetes Services (AKS) Overview — John Savill's Technical Training
English · AKS fundamentals review, useful before choosing an architecture to revisit managed control-plane and node-pool concepts

Official documentation

Video storyboard (about 75 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–15s
Visual: on the left, five containers from the local Compose stack; on the right, five Azure portal resource icons, connected one-to-one by arrows in the middle.
Narration: the local Prometheus, Alertmanager and Grafana each have a managed counterpart on Azure.
Shot 2 · 15–40s
Visual: four cards — A self-managed, B fully managed, C hybrid, D logs only — flip over one at a time, each showing four boxes: collection, storage, alerting, identity.
Narration: the key to choosing is not the feature list but the responsibility boundary: who runs storage, who manages identity, who sends alerts.
Shot 3 · 40–60s
Visual: cards B and D merge; the Container Insights cost preset highlights “Logs and events”.
Narration: the official recommendation is to give metrics to managed Prometheus and logs to Container Insights, so performance data is not paid for twice.
Shot 4 · 60–75s
Visual: this lesson's resource list appears item by item: amw, amg, rule group, Action Group, law.
Narration: over the next fifty-five minutes we will turn this list into real resources one by one, and then clean everything up.
or score ≥ 70% on the quiz

Module 2 · Azure Monitor managed Prometheus and AKS integration

05:00 – 13:00 · one az aks update command adds four kinds of ama-metrics components to the cluster; data is written into the Azure Monitor workspace through the DCE/DCR, carrying the cluster managed identity's token
8 minGAControl-plane metrics must be explicitly enabled★★★★★
Learning goals
  • Create an Azure Monitor workspace and read the DCR / DCE and the managed resource group it generates automatically.
  • Use az aks update --enable-azure-monitor-metrics --azure-monitor-workspace-resource-id to enable managed collection, and explain the roles of ama-metrics (replicas),ama-metrics-node (DaemonSet),ama-metrics-ksm,ama-metrics-operator-targets .
  • Understand the “minimal ingestion profile” and default targets; know where cluster labels come from, and that control-plane metrics need to be added with --enable-control-plane-metrics.
  • Query the workspace directly with the PromQL query API (token audience https://prometheus.monitor.azure.com, role Monitoring Data Reader).
Prerequisites: The AKS cluster from module 0; Lesson 1's scrape interval. Importance:★★★★★ (the core pipeline of this lesson)

What: what managed Prometheus consists of

  • Azure Monitor workspace (Microsoft.Monitor/accounts): time-series storage and PromQL query endpoint (in the form https://amw-prom-lab-xxxx.canadacentral.prometheus.monitor.azure.com). Creating it automatically generates a same-named data collection rule (DCR) and data collection endpoint (DCE), placed in the managed resource group MA_<workspace name>_<region>_managed, whose name cannot be changed.
  • Metrics add-on (in-cluster kube-system, containerized Azure Monitor agent):
    • ama-metrics-* (ReplicaSet, cluster-level collection): scrapes kube-state-metrics,ama-metrics-prometheus-config custom jobs in the ConfigMap, and targets discovered by PodMonitor/ServiceMonitor.
    • ama-metrics-node-* (DaemonSet, one per node): scrapes this node's kubelet, cAdvisor, node-exporter, and ama-metrics-prometheus-config-node jobs in the ConfigMap.
    • ama-metrics-ksm-* the add-on's bundled kube-state-metrics.
    • ama-metrics-operator-targets-*: target allocator, reads the configuration and CRDs and distributes targets to the collector replicas (containers config-reader,targetallocator).
    Main containers in each collection Pod: prometheus-collector (a Prometheus receiver based on the OpenTelemetry Collector + MetricsExtension write component) and addon-token-adapter (exchanges the cluster managed identity for a write token). The Pod's port 9090 provides the “Prometheus Agent mode” UI, where you can view /config,/service-discovery,/targets.
  • Cluster-side data collection association: when enabling, the cluster also gets an association and rules that connect it to the workspace DCR/DCE (names and locations follow the actual az monitor data-collection rule list output).

Why: why “agent mode + remote storage”

No TSDB is kept in the cluster, so there are no PV capacity, WAL replay, compaction or retention issues (the operational problems covered in Lesson 7); collectors can restart and scale statelessly (the official docs provide HPA and high-scale guidance for collector replicas). The trade-off: queries must go to the workspace, with 1–2 minutes of end-to-end latency; during node upgrades, restarting the node that runs the cluster-level collector creates a 1–2 minute data gap (officially noted; recommended alerts are unaffected).

How: the journey of one sample

  1. The target allocator generates scrape jobs from default targets + ConfigMap + CRDs and assigns them to the collector replicas.
  2. prometheus-collector Per the scrape_interval (default targets: 30s), sends scrape requests to targets GET /metrics, applies relabeling and the minimal-ingestion keep list, and appends cluster label (by default the last segment of the cluster resource ID aks-prom-lab, can be overridden with cluster_alias ).
  3. addon-token-adapter Using the cluster managed identity, it obtains a token from Entra ID; MetricsExtension carries the token and POSTs samples in batches to the workspace DCE ingestion endpoint, and the DCR decides which workspace the data flows into.
  4. The workspace accepts data according to its active time series and events-per-minute quotas; exceeding them causes throttling (module 7).
  5. Queriers (Grafana, rule groups, the API) carry their own token (audience https://prometheus.monitor.azure.com) access the query endpoint; the RBAC role Monitoring Data Reader decides whether they can read.

What is collected by default

CategoryTargetNotes
Enabled by defaultcadvisor,nodeexporter,kubelet,kube-state-metrics,networkobservabilityRetinaevery 30 seconds; the minimal ingestion profile is on by default: keeps only the metrics used by the default dashboards, default recording rules and recommended alerts, and drops the rest in the relabel stage
Disabled by defaultcoredns,kubeproxy,apiserverin ama-metrics-settings-configmap enabled in
control plane (requires --enable-control-plane-metrics)apiserver,etcd scheduler, controller-manager, cluster-autoscaler, etc. must be enabled separatelybelongs to the controlplane-metrics section of the settings ConfigMap
Automatically configureddefault recording rules (such as instance:node_cpu_utilisation:rate5m),ux:* visualization rulescreated as rule-group resources; after linking Grafana, dashboards such as “Kubernetes / Compute Resources / …” are provisioned automatically

When: when extra parameters are needed

  • want to see business labels in kube_pod_labels (such as app) → --ksm-metric-labels-allow-list "pods=[app]" (can also be overridden in the ksm-config of the settings ConfigMap).
  • Need API Server/etcd metrics → --enable-control-plane-metrics (requires it to be enabled, or managed Prometheus to be enabled at the same time).
  • Windows node dashboards → --enable-windows-recording-rules.
  • Link Grafana while enabling → --grafana-resource-id (the operator needs Owner, or Contributor + User Access Administrator; see module 4).

Comparison with similar technologies

Managed add-onSelf-managed Prometheus (Lesson 1)Prometheus agent mode + remote_write
Local storageNone (send buffer only)TSDB (head + WAL + block)WAL only
Rule evaluationWorkspace-side rule groupsLocalNot supported (remote required)
Write authenticationCluster managed identity, automatic—Self-configured (managed identity sidecar available on Azure)
UpgradesManaged by Microsoft with AKSSelf-managedby you
Common misconceptions① “After enabling, all node-exporter metrics are present” — the minimal ingestion profile keeps only the metrics in its list, for example node_memory_MemAvailable_bytes is present, whereas many node_* are not; add a keep list when needed, or turn off minimal ingestion (this significantly increases cost). ② “My application metrics are discovered automatically” — no: by default only the Pod-annotation scrape switch exists, and the namespace regex is empty; custom targets must be configured (module 3). ③ “Managed Prometheus is case-sensitive” — the workspace is case-insensitive, so series that differ only in case are treated as the same series.

Architecture diagram: ama-metrics components in the cluster

kube-system (AKS managed add-on) ama-metrics-operator-targetsconfig-reader: merges defaults + ConfigMaptargetallocator: watches PodMonitor/SM ama-metrics (ReplicaSet)prometheus-collector + addon-token-adapterksm, custom jobs, CRD targets · UI :9090 assigns ama-metrics-node (DaemonSet)this node's kubelet / cAdvisor / node-exporter+ ama-metrics-prometheus-config-node ama-metrics-ksmkube-state-metrics (bundled with the add-on)labels/annotations allow list ConfigMap: ama-metrics-settings-configmap · ama-metrics-prometheus-config(-node/-node-windows)CRDs: podmonitors / servicemonitors.azmonitoring.coreos.com DCE ingestion endpoint+ DCR (data flow → workspace)MA_amw-prom-lab_canadacentral_managed Azure Monitor workspaceamw-prom-labtime-series storage + query endpointquota: active series / events per minute
Figure 2-1: the target allocator decides “whom to scrape”; the collector replicas and node DaemonSet do the scraping; the DCE/DCR decide “where to write”

Data and identity flow: writing and reading are two different identities

Write path prometheus-collectorSample batches addon-token-adapterCluster managed identity Entra IDIssues access token DCE + DCRValidation and routing Workspace storageamw-prom-lab Read path Grafana / rule groups / APIPromQL Caller's identityGrafana MI / users / apps Entra IDaud=prometheus.monitor… Azure RBACMonitoring Data Reader Query endpoint/api/v1/query… For write failures, check the addon-token-adapter logs; for 403 on reads, check the caller's role assignment on the workspace
Figure 2-2: writes use the cluster managed identity (configured automatically); reads use the caller's own identity (explicit role assignment required)

Core animation: data and identity flow from managed collection → Azure Monitor workspace → Managed Grafana

Step through one myapp sample from /metrics to a Grafana panel. Each step highlights the real component; the terminal shows the commands, logs or HTTP requests you would see at that point. You can switch on a “fault” to see where the chain breaks.

myapp:5000/metrics target allocatoroperator-targets ama-metricsprometheus-collector token-adaptercluster managed identity Entra IDtoken DCE → DCR → workspaceamw-prom-lab time-series storage query endpoint + RBACMonitoring Data Reader Managed Grafanasystem-assigned managed identity obtains token you (browser)Entra sign-in Ready
Inject fault:
Click “Play” or “Next step”.
$ az aks update -g rg-prom-lab -n aks-prom-lab --enable-azure-monitor-metrics --azure-monitor-workspace-resource-id $AMW_ID

Core commands and parameters

CommandPurposeKey parameters / notes
az monitor account createCreate an Azure Monitor workspace (core CLI)-n -g -l; optional --public-network-access
az monitor account showView ID, query endpoint, default DCR/DCE--query metrics.prometheusQueryEndpoint
az aks update --enable-azure-monitor-metricsEnable managed Prometheus on an existing cluster--azure-monitor-workspace-resource-id,--grafana-resource-id,--ksm-metric-labels-allow-list,--ksm-metric-annotations-allow-list
az aks update --enable-control-plane-metricsCollect API Server / etcd metricsRequires managed Prometheus to be enabled (or enabled in the same command)
az aks update --disable-azure-monitor-metricsDisable the add-onWorkspace and existing data are retained
kubectl get pods -n kube-system | grep ama-metricsCheck componentsThe four kinds of Pods should be Running
source ~/promlab/azure/env.sh
az monitor account create -n $AMW -g $RG -l $LOC
export AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
export PROM_QUERY=$(az monitor account show -n $AMW -g $RG --query metrics.prometheusQueryEndpoint -o tsv)
echo $AMW_ID; echo $PROM_QUERY
az monitor account show -n $AMW -g $RG --query defaultIngestionSettings -o json
/subscriptions/0000…/resourceGroups/rg-prom-lab/providers/Microsoft.Monitor/accounts/amw-prom-lab
https://amw-prom-lab-a1b2.canadacentral.prometheus.monitor.azure.com
{
  "dataCollectionEndpointResourceId": "/subscriptions/0000…/resourceGroups/MA_amw-prom-lab_canadacentral_managed/providers/Microsoft.Insights/dataCollectionEndpoints/amw-prom-lab",
  "dataCollectionRuleResourceId": "/subscriptions/0000…/resourceGroups/MA_amw-prom-lab_canadacentral_managed/providers/Microsoft.Insights/dataCollectionRules/amw-prom-lab"
}
kubectl get pods -n kube-system | grep ama-metrics || echo "(before enabling: no ama-metrics)"
az aks update -g $RG -n $AKS \
  --enable-azure-monitor-metrics \
  --azure-monitor-workspace-resource-id $AMW_ID \
  --ksm-metric-labels-allow-list "pods=[app]"
az aks show -g $RG -n $AKS --query azureMonitorProfile -o json
kubectl get pods -n kube-system -o wide | grep ama-metrics
{
  "metrics": {
    "enabled": true,
    "kubeStateMetrics": { "metricAnnotationsAllowList": "", "metricLabelsAllowlist": "pods=[app]" }
  }
}
ama-metrics-7c9d6b8f5d-x8kq2                 2/2   Running   0   3m   10.244.1.12   aks-nodepool1-…-vmss000001
ama-metrics-ksm-6f7d9c7b48-l2jzw             1/1   Running   0   3m   10.244.0.15   aks-nodepool1-…-vmss000000
ama-metrics-node-5qv7n                       2/2   Running   0   3m   10.244.0.14   aks-nodepool1-…-vmss000000
ama-metrics-node-tm2hd                       2/2   Running   0   3m   10.244.1.11   aks-nodepool1-…-vmss000001
ama-metrics-operator-targets-5d4c8f8b6-9mwcz 2/2   Running   1   3m   10.244.1.13   aks-nodepool1-…-vmss000001

How to verify: All four kinds of Pods are Running; operator-targets one extra restart at the start is normal (officially noted). Common error: The number and names of containers may change with the add-on version; follow kubectl get pod … -o jsonpath='{.spec.containers[*].name}' . Production use: Enable it when the cluster is created, using Azure Policy or IaC, and specify the workspace explicitly so it does not fall into a default workspace.

Query the workspace directly with the PromQL API

# Grant yourself read access (data-plane role; it may take a few minutes to take effect)
ME=$(az ad signed-in-user show --query id -o tsv)
az role assignment create --assignee-object-id $ME --assignee-principal-type User \
  --role "Monitoring Data Reader" --scope $AMW_ID

TOKEN=$(az account get-access-token --resource https://prometheus.monitor.azure.com --query accessToken -o tsv)
curl -s -H "Authorization: Bearer $TOKEN" \
  --data-urlencode 'query=count by (job) (up{cluster="aks-prom-lab"})' \
  "$PROM_QUERY/api/v1/query" | jq -r '.data.result[] | "\(.metric.job)\t\(.value[1])"'
cadvisor	2
kube-state-metrics	1
kubelet	2
node	2
networkobservabilityRetina	2

The official API documentation example obtains a token with “app registration + client credentials” (resource=https://prometheus.monitor.azure.com); the command above uses az account get-access-token to get the current user's token, which uses the same audience, provided you have Monitoring Data Reader on the workspace. API limits: each query must include exactly one __name__ matcher,/query_range query_range spans at most 32 days,/series series queries at most 12 hours, and only /api/v1/label/__name__/values is supported. Job names follow your actual output.

Optional: control-plane metrics

az aks update -g $RG -n $AKS --enable-control-plane-metrics
# Later, query in Grafana Explore:
#   sum by (code) (rate(apiserver_request_total{cluster="aks-prom-lab"}[5m]))

Lab 2: create the workspace, enable managed collection, verify default targets (about 7 min)

Environment and costs: the workspace itself has no fixed fee; it is billed by ingested samples and queried samples (module 8). Required permission: Contributor on the resource group. Risk: enabling deploys add-ons in kube-system , which consume a small amount of node resources.
Create the workspace and record its endpoint: run the first block on the “Commands” page and confirm that MA_amw-prom-lab_canadacentral_managed resource group:
az group list --query "[?starts_with(name,'MA_amw-prom-lab')].name" -o tsv
az resource list -g MA_amw-prom-lab_canadacentral_managed --query "[].{type:type,name:name}" -o table
MA_amw-prom-lab_canadacentral_managed
Type                                       Name
-----------------------------------------  ------------
Microsoft.Insights/dataCollectionEndpoints amw-prom-lab
Microsoft.Insights/dataCollectionRules     amw-prom-lab
Enable managed collection (the second command block), and in another terminal watch the order in which the Pods appear:
kubectl get pods -n kube-system -w | grep --line-buffered ama-metrics
See targets as the collector sees them: port-forward to port 9090 of a node DaemonSet Pod (Prometheus Agent mode UI):
NODEPOD=$(kubectl get pods -n kube-system -l dsName=ama-metrics-node -o name | head -1)
[ -z "$NODEPOD" ] && NODEPOD=$(kubectl get pods -n kube-system -o name | grep ama-metrics-node | head -1)
kubectl port-forward -n kube-system $NODEPOD 9090 &
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | "\(.labels.job)\t\(.health)\t\(.scrapeUrl)"' | head
kill %1
cadvisor	up	https://10.224.0.4:10250/metrics/cadvisor
kubelet	up	https://10.224.0.4:10250/metrics
node	up	http://10.224.0.4:9100/metrics

Pod label selectors follow the actual output; if /api/v1/targets is unavailable, open 127.0.0.1:9090/targets in the browser (the UI path given by the official troubleshooting documentation).

Query the workspace: after granting yourself Monitoring Data Reader with the commands on the “Commands” page, run count by (job) (up{cluster="aks-prom-lab"}); then query one metric outside the minimal-ingestion list to see it being dropped by the keep list:
for q in 'node_memory_MemAvailable_bytes{cluster="aks-prom-lab"}' 'node_memory_Active_bytes{cluster="aks-prom-lab"}'; do
  echo "== $q"; curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode "query=$q" "$PROM_QUERY/api/v1/query" | jq '.data.result | length'
done
== node_memory_MemAvailable_bytes{cluster="aks-prom-lab"}
2
== node_memory_Active_bytes{cluster="aks-prom-lab"}
0
myapp has not been scraped yet: querying myapp_http_requests_total returns an empty result — this is the problem module 3 will solve.
Cleanup: keep all resources for later modules. To roll back this module: az aks update -g $RG -n $AKS --disable-azure-monitor-metrics; to delete the workspace, use az monitor account delete -n $AMW -g $RG.

Case 1: use Azure Policy to ensure every cluster has metrics

Problem: New clusters are created by different teams from different templates; some forget to enable monitoring. Approach: Use the official “Prometheus Metrics addon” policy definition (DeployIfNotExists), specifying the workspace per region; for existing clusters, use a remediation task. Limitations: The policy only enables the add-on; it does not manage the application's PodMonitor and rule groups, which still need GitOps management.

Case 2: cluster label conflicts when multiple clusters share one workspace

Problem: Two clusters, each named aks-prod in different resource groups, write to the same workspace; occasional 422 errors occur, and the dashboard mixes the data from both clusters. Approach: In each one's ama-metrics-settings-configmap set cluster_alias (only alphanumerics allowed; other characters are replaced with underscores), and change the rule group's clusterName to the alias at the same time. Limitations: After changing the alias, historical data keeps the old label values, so dashboard variables must stay compatible for a while.

Case 3: collector replicas OOMKilled in a large cluster

Problem: A 500-node cluster enabled many ServiceMonitors,ama-metrics replicas were repeatedly OOMKilled and data was intermittent. Approach: Split per the official high-scale guidance: move node-level targets to ama-metrics-prometheus-config-node (shared by the DaemonSet), enable the collector replica HPA, and use a keep list to drop unused high-cardinality metrics. Limitations: A DaemonSet custom job can only scrape targets on its own node ($NODE_IP), and must not use service discovery; otherwise every node scrapes all targets and overloads the API Server.

Common errors and fixes

No configuration present for the AKS resource (prometheus-collector log, every 5 minutes; Pod restarts every 15 minutes)

Cause: The add-on cannot find the DCR/DCE configuration associated with the cluster: the DCR/DCE or workspace was deleted or the association is missing, or a private cluster combined with AMPLS is unsupported (the three cases listed in the official troubleshooting documentation).

kubectl logs -n kube-system deploy/ama-metrics -c prometheus-collector --tail=50
az monitor account show -n $AMW -g $RG --query defaultIngestionSettings
az monitor data-collection rule list -g $RG -o table

Fix: confirm the workspace and DCR/DCE exist; --disable-azure-monitor-metrics then re-enable to rebuild the association.

(AuthorizationFailed) … does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write'

Cause: When enabling with --grafana-resource-id , the CLI must assign a role to Grafana's managed identity, but the operator only has Contributor.

Fix: have an Owner / User Access Administrator run it, or enable first without the Grafana parameter and have an authorized person assign the role separately (module 4).

ama-metrics-node Pod CrashLoopBackOff; describe shows OOMKilled

Cause: Too much scraping on the node (minimal ingestion turned off, high-cardinality cAdvisor metrics, too many node-level custom jobs).

kubectl describe pod -n kube-system POD | grep -A5 "Last State"
kubectl top pod -n kube-system | grep ama-metrics

Fix: restore minimal-ingestion-profile enabled = true and add a keep list for the metrics you really need; see the official high-scale guidance.

ERROR: … aks-preview … / unrecognized arguments: --enable-azure-monitor-metrics

Cause: The Azure CLI version is too old, or an unexpected aks-preview extension is installed.

az version; az extension list -o table

Fix:az upgrade; az extension remove --name aks-preview.

Query API returns 403 Forbidden / 401

Cause: The caller has no Monitoring Data Reader on the workspace (Contributor is a management-plane role and does not include data reads), or the token audience is not https://prometheus.monitor.azure.com.

az role assignment list --scope $AMW_ID --query "[].{who:principalName,role:roleDefinitionName}" -o table

Fix: assign the role and wait for it to take effect; re-acquire the token.

Command-line tasks
1. Enable managed Prometheus on the existing cluster aks-prom-lab, write to workspace amw-prom-lab, and expose the Pod's app label to kube_pod_labels.
AMW_ID=$(az monitor account show -n amw-prom-lab -g rg-prom-lab --query id -o tsv)
az aks update -g rg-prom-lab -n aks-prom-lab --enable-azure-monitor-metrics \
  --azure-monitor-workspace-resource-id $AMW_ID --ksm-metric-labels-allow-list "pods=[app]"
2. Retrieve the workspace's PromQL query endpoint and count the series of up.
EP=$(az monitor account show -n amw-prom-lab -g rg-prom-lab --query metrics.prometheusQueryEndpoint -o tsv)
TOKEN=$(az account get-access-token --resource https://prometheus.monitor.azure.com --query accessToken -o tsv)
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode 'query=count(up)' "$EP/api/v1/query" | jq '.data.result[0].value[1]'
Scenario analysis
Ten minutes after enabling, the “Kubernetes / Compute Resources / Cluster” dashboard in Grafana has data, but your query for node_disk_io_now returns nothing, and a colleague says “managed Prometheus is broken”. How do you explain and handle this?

minimal ingestion is on by default, so node-exporter keeps only the metrics in the list (such as node_disk_io_time_seconds_total), and node_disk_io_now is not in the list, so it is dropped in the relabel stage. This is not a fault. Handle it by assessing whether it is really needed; if so, add it in the ama-metrics-settings-configmap section of the cluster-metrics → default-targets-metrics-keep-list settings ConfigMap by adding it to the keep list nodeexporter = "node_disk_io_now" (keeping minimal ingestion). The ama-metrics Pod restarts after 2–3 minutes to apply the change. Do not simply turn off minimal ingestion, which significantly increases ingestion volume and cost.

Verified teaching videos

▶
AKS Labs: Observability with Managed Prometheus and Managed Grafana — Azure Kubernetes Service (AKS)
English · hands-on lab from the official AKS channel covering enabling managed Prometheus and linking Grafana (the interface and parameters follow this lesson's verified content)
▶
Microsoft Azure Monitor Agent (AMA) and Data Collection Rule (DCR) Overview — John Savill's Technical Training
English · a general model of ama-* agents and DCR/DCE, very helpful for this module's “where data is written”

Official documentation

Video storyboard (about 100 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: the terminal runs az aks update; on the right, four kinds of ama-metrics Pods pop up one after another in kube-system.
Narration: one command, and four kinds of components appear in the cluster: the target allocator, cluster-level collector replicas, a per-node DaemonSet, and the bundled kube-state-metrics.
Shot 2 · 20–45s
Visual: an orange sample point leaves myapp's /metrics and passes through the collector, with a key icon labelled “cluster managed identity → Entra token” pops up beside it.
Narration: the collector works in agent mode and does not store data in the cluster. It exchanges the cluster managed identity for a token and writes samples to the data collection endpoint.
Shot 3 · 45–70s
Visual: the DCE, DCR and workspace light up in turn, with the managed resource group name MA_amw-prom-lab_canadacentral_managed beside them.
Narration: the data collection rule decides which Azure Monitor workspace the data goes to; the workspace provides storage and the PromQL query endpoint.
Shot 4 · 70–100s
Visual: the Grafana icon carries another key to the query endpoint; the gate is labelled Monitoring Data Reader; when the role is removed, the gate shows 403.
Narration: reading is a separate identity chain. Without the data-read role, Grafana sees a 403 even when the data has been written.
or score ≥ 70% on the quiz

Module 3 · Scrape configuration: ConfigMap, PodMonitor and ServiceMonitor

13:00 – 21:00 · get the managed collector to scrape myapp: four entry points, one settings ConfigMap, one validation tool, and the hard limit of 63 labels
8 minazmonitoring.coreos.com/v1K8s 1.37+ Secret access is authorized per namespace★★★★★
Learning goals
  • Distinguish the four scrape entry points: PodMonitor,ServiceMonitor (CRD),ama-metrics-prometheus-config (ConfigMap custom jobs),Pod annotations (enabled per namespace in the settings ConfigMap), and know which Pod executes each one.
  • Write a working PodMonitor for myapp (API group azmonitoring.coreos.com/v1, a named port http,labelLimit and the three limit fields).
  • Will change ama-metrics-settings-configmap (schema v2: cluster-metrics / controlplane-metrics / prometheus-collector-settings), promconfigvalidator and pre-check the ConfigMap with
  • Confirm via the 9090 UI of a collection Pod and its config-reader/targetallocator logs that targets are discovered and scraped.
Prerequisites: Lesson 1 scrape_configs and relabeling; the component roles from module 2. Importance:★★★★★

First meet two objects: PodMonitor and ServiceMonitor (concept overview)

In Lesson 1, Prometheus knew “where to scrape” through prometheus.yml in scrape_configs In Kubernetes, Pods and Services are constantly changing, so hand-written scrape jobs go stale quickly. The Prometheus Operator project therefore defines several CRDs (custom resources) that let you declare “what to scrape” as Kubernetes objects, and a controller translates them into scrape configuration:

ObjectWhat it selects by labelWhat is finally scraped
ServiceMonitorService (selector.matchLabels + namespaceSelector)each ready Pod endpoint behind the Service (via EndpointSlice); ports matched by the endpoints[].port of the port name on the Service.
PodMonitorPod (also selected by labels)each selected Pod's container port (podMetricsEndpoints[].port), no Service needed
# Minimal PodMonitor: scrape the http port (5000) of Pods labelled app=myapp in namespace myapp
apiVersion: azmonitoring.coreos.com/v1   # the managed API group; the open-source Operator uses monitoring.coreos.com/v1
kind: PodMonitor
metadata: { name: myapp, namespace: myapp }
spec:
  selector: { matchLabels: { app: myapp } }
  podMetricsEndpoints:
  - port: http           # the name of the container port, not a number
    path: /metrics
    interval: 30s
# The managed version also needs the three extra fields such as labelLimit; see the Why section below

You can think of it as: label selector → set of targets → an automatically generated scrape_config. This lesson only uses these two objects from the managed add-on; the open-source Prometheus Operator, its Prometheus CRs, and serviceMonitorSelector how to choose Monitors are covered in Lesson 5 Module 1 and module 2 in depth.

The three most common pitfalls:① port a port name written as a number or misspelled; ② selector labels that do not match the labels on the Pod/Service (case, key names); ③ the Service selected by the ServiceMonitor has no ready endpoints. All three look like “the target is not in the target list at all”, rather than up=0.

What: four scrape entry points

Entry pointWhere it is writtenWho runs itSuited for
PodMonitorany namespace,apiVersion: azmonitoring.coreos.com/v1ama-metrics replicas (assigned by the target allocator)No Service, or you want to scrape each Pod (myapp in this lesson)
ServiceMonitorany namespace, same as abovesame as aboveServices already exist; scrape by Endpoints
ConfigMap custom jobskube-system/ama-metrics-prometheus-config, key prometheus-configama-metrics replicasstandard Prometheus syntax,static_configs,kubernetes_sd_configs, for migrating an existing prometheus.yml
ConfigMap (node-level)ama-metrics-prometheus-config-node / -node-windowsthe DaemonSet Pod on each nodescrapes only targets on this node ($NODE_IP); service discovery must not be used
Pod annotationson the Pod prometheus.io/scrape|path|port + in settings podannotationnamespaceregexama-metrics replicasquick trials; the volume gets large with many namespaces

Official note: the PodMonitor/ServiceMonitor CRDs deployed by the add-on differ from the open-source versions only in the API group name, open-source monitoring.coreos.com objects will not be read by the add-on (deliberate isolation), so the two sets of CRDs do not conflict.

Why: why the labelLimit fields exist

Managed ingestion has hard limits on labels: per-series label count ≤ 63, label name length ≤ 511, label value length ≤ 1023; when exceeded,the entire scrape job fails (the target shows up=0); metric name length ≤ 511; if exceeded, only that series is dropped. The official template writes in the CRD labelLimit: 63,labelNameLengthLimit: 511,labelValueLengthLimit: 1023, so that over-limit cases are handled at the scrape stage rather than dropped at the processing stage — copy them as shown.

How: structure of the settings ConfigMap (schema v2)

kind: ConfigMap
apiVersion: v1
metadata: { name: ama-metrics-settings-configmap, namespace: kube-system }
data:
  schema-version: v2
  config-version: ver1
  cluster-metrics: |-
    default-targets-scrape-enabled: |-
      kubelet = true
      coredns = false
      …
    pod-annotation-based-scraping: |-
      podannotationnamespaceregex = ""
    default-targets-metrics-keep-list: |-
      nodeexporter = ""
      …
    minimal-ingestion-profile: |-
      enabled = true
    default-targets-scrape-interval-settings: |-
      kubelet = "30s"
      …
  controlplane-metrics: |-
    default-targets-scrape-enabled: |-
      apiserver = true
      etcd = true
      …
  prometheus-collector-settings: |-
    cluster_alias = ""
    debug-mode = false
    secrets_access_namespaces = ""
    deny_fs_access_through_sms = false
  • This ConfigMap does not exist by default, download it from the official template (https://aka.ms/azureprometheus-addon-settings-configmap) and modify it before applying; the ama-metrics Pods will within 2–3 minutes read it and restart.
  • Migrating from v1: default-scrape-settings-enabled → default-targets-scrape-enabled; remove controlplane- prefixes from control-plane targets; minimalingestionprofile = true becomes a separate minimal-ingestion-profile section.
  • Note: boolean values in the official template file are “example values” and do not fully match the defaults when no ConfigMap exists (for example, the docs list coredns and kubeproxy as disabled by default). Check each switch you want against the template before applying it.

When: which entry point to choose

  • If the team is already used to the Prometheus Operator → PodMonitor/ServiceMonitor (change monitoring.coreos.com to azmonitoring.coreos.com,release: kps selection labels such as are not needed in the managed version).
  • Migrating Lesson 1's prometheus.yml jobs → ConfigMap custom jobs (global external_labels is not supported in the ConfigMap method; add labels with relabel in each job).
  • The same target should use only one entry point; otherwise it will be scraped twice, cost doubles, and duplicate series may even appear.

Comparison with similar technologies

Managed add-onkube-prometheus-stack (Lesson 5)
CRD groupazmonitoring.coreos.com/v1monitoring.coreos.com/v1
which Monitors are selectedall Monitors in all namespacesPrometheus CR's serviceMonitorSelector (such as release: kps)
Secret accessK8s 1.37+ requires secrets_access_namespaces + a Role/RoleBinding per namespaceOperator RBAC
Config validationpromconfigvalidator (built into the Pod)promtool check config
Metric renamingnot supportedsupported (relabel __name__)
Common misconceptions① “Writing port 5000 is enough” — PodMonitor's podMetricsEndpoints[].port requires a named port (official template comment: Port requires a named port), so give the port a name in the Deployment http. ② “The ConfigMap goes in the myapp namespace” — the three custom-scrape ConfigMaps must be in kube-system, and the data key must be named prometheus-config. ③ “Changing the settings ConfigMap takes effect immediately” — you must wait for the ama-metrics Pods to restart (2–3 minutes); the number of restarts should equal the number of times you applied the ConfigMap.

Architecture diagram: where the configuration comes from, and who scrapes the targets

PodMonitor / ServiceMonitorazmonitoring.coreos.com/v1 · any ns ama-metrics-prometheus-configkube-system · key prometheus-config ama-metrics-settings-configmapdefault targets / keep list / annotation ns / alias ama-metrics-prometheus-config-nodescrapes only targets on $NODE_IP ama-metrics-operator-targetsconfig-reader: parse + merge + validatetargetallocator: watches CRDs, service discoveryassigns targets to collector replicaslog prefix prometheus-config-merger ama-metrics replicasscrapes myapp Pod :5000/metricsUI :9090 /config /targets ama-metrics-node (per node)kubelet / cAdvisor / node / node-level jobs settings ConfigMap affects both the replicas and the DaemonSet (default target switches and keep list)
Figure 3-1: all four entry points ultimately feed into the target allocator or the DaemonSet; when troubleshooting, first determine “who scrapes this target”

Flow diagram: a PodMonitor from apply to up=1

kubectl applyPodMonitor myapp API ServerCRD validates apiVersion targetallocatorwatch → generate jobs service discoveryselector app=myappport name http GET /metricsevery 30s label limits≤63 labels→ up=1 Each hop that fails has a fixed observation point: apply errors / TA logs / :9090/service-discovery / :9090/targets / up metric
Figure 3-2: the PodMonitor effective path and the observation point for each step

Interactive simulator: scrape configuration diagnosis

Choose a scrape entry point and toggle common error switches, then click “Apply configuration”. The simulator advances in the real processing order (API Server validation → config-reader → targetallocator → scraping → ingestion limits) and shows in the terminal the output you would see at each point.

Entry point:
After choosing an entry point and fault switches, click “Apply configuration”.
$ kubectl apply -f myapp-podmonitor.yaml

Core commands and configuration

CommandPurposeKey parameters / notes
kubectl get crd | grep azmonitoringConfirm the add-on CRDs are installedpodmonitors.azmonitoring.coreos.com,servicemonitors.azmonitoring.coreos.com
kubectl get podmonitors.azmonitoring.coreos.com -AList managed PodMonitorsuse the full name to avoid confusion with the short names of open-source CRDs
kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-systemCreate a custom jobthe file name must be prometheus-config (no extension)
kubectl apply -f ama-metrics-settings-configmap.yamlchange default targets, keep list, annotation namespaces, aliasPods restart and take effect after 2–3 minutes
kubectl port-forward <ama-metrics pod> -n kube-system 9090Agent mode UI/config,/service-discovery,/targets
kubectl logs <operator-targets pod> -c config-reader|targetallocatorconfiguration parsing and target discovery logslook at the prometheus-config-merger section

① PodMonitor (the main choice in this lesson)

apiVersion: azmonitoring.coreos.com/v1   # not monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: myapp
  namespace: myapp
spec:
  labelLimit: 63
  labelNameLengthLimit: 511
  labelValueLengthLimit: 1023
  selector:
    matchLabels:
      app: myapp
  podTargetLabels: [app]             # add the Pod label app to every series
  podMetricsEndpoints:
  - port: http                       # must be a named port
    path: /metrics
    interval: 30s
    metricRelabelings:               # after scraping, before ingestion: keep only application metrics and up
    - sourceLabels: [__name__]
      action: keep
      regex: 'myapp_.*'
kubectl get crd | grep azmonitoring
kubectl apply -f ~/promlab/azure/myapp-podmonitor.yaml
kubectl get podmonitors.azmonitoring.coreos.com -n myapp
podmonitors.azmonitoring.coreos.com       2026-11-15T09:12:41Z
servicemonitors.azmonitoring.coreos.com   2026-11-15T09:12:41Z
podmonitor.azmonitoring.coreos.com/myapp created
NAME    AGE
myapp   5s

Notes:up is a metric synthesized by the scraper and does not pass through metricRelabelings, so keep rules will not drop it. By the Prometheus Operator convention, series produced by a PodMonitor carry labels such as namespace,pod,container,endpoint etc.,job usually <namespace>/<PodMonitor name>— check against what the /targets page actually shows; in rules, prefer stable labels like namespace="myapp" rather than job.

② ServiceMonitor (choose one; do not use it together with ①)

apiVersion: azmonitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: myapp, namespace: myapp }
spec:
  labelLimit: 63
  labelNameLengthLimit: 511
  labelValueLengthLimit: 1023
  selector: { matchLabels: { app: myapp } }   # matches the Service's labels
  endpoints:
  - port: http                                 # Service port name
    path: /metrics
    interval: 30s

③ ConfigMap custom jobs (used when migrating prometheus.yml)

global:
  scrape_interval: 30s
scrape_configs:
- job_name: myapp-cm
  kubernetes_sd_configs:
  - role: pod
    namespaces: { names: [myapp] }
  relabel_configs:
  - source_labels: [__meta_kubernetes_pod_label_app]
    action: keep
    regex: myapp
  - source_labels: [__meta_kubernetes_pod_container_port_name]
    action: keep
    regex: http
  - source_labels: [__meta_kubernetes_pod_name]
    target_label: pod
  - source_labels: [__meta_kubernetes_namespace]
    target_label: namespace
# First validate with the promconfigvalidator built into the Pod (official method; needs jq)
cd ~/promlab/azure
for podname in $(kubectl get pods -l rsName=ama-metrics -n=kube-system -o json | jq -r '.items[].metadata.name'); do
  kubectl cp -n=kube-system "${podname}":/opt/promconfigvalidator ./promconfigvalidator
  kubectl cp -n=kube-system "${podname}":/opt/microsoft/otelcollector/collector-config-template.yml ./collector-config-template.yml
  chmod 500 promconfigvalidator
done
./promconfigvalidator --config ./prometheus-config --otelTemplate ./collector-config-template.yml
# Note: the official documentation example path is ./promconfigvalidator/promconfigvalidator; it depends on whether kubectl cp produces a file or a directory
kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system
prom-config-validator::Config file provided - ./prometheus-config
prom-config-validator::Successfully generated otel config
prom-config-validator::Loading otel config
prom-config-validator::Successfully loaded and validated prometheus config
configmap/ama-metrics-prometheus-config created

The merged-otel-config.yaml generated by the validator is for debugging only; do not apply it. Common error: using kubectl create configmap … --from-file=myapp.yml, the key name becomes myapp.yml, so the collector cannot find the prometheus-config key and silently ignores it.

④ Pod annotations + settings ConfigMap

curl -sL https://aka.ms/azureprometheus-addon-settings-configmap -o ama-metrics-settings-configmap.yaml
# Edit: under cluster-metrics → pod-annotation-based-scraping
#   podannotationnamespaceregex = "myapp"
# and check that each switch under default-targets-scrape-enabled matches what you expect
kubectl apply -f ama-metrics-settings-configmap.yaml
kubectl -n myapp patch deploy myapp --type merge -p \
 '{"spec":{"template":{"metadata":{"annotations":{"prometheus.io/scrape":"true","prometheus.io/path":"/metrics","prometheus.io/port":"5000"}}}}}'
choose only one This lesson's lab uses ① PodMonitor. If you tried ③ or ④, delete them after comparing (the kubectl delete cm ama-metrics-prometheus-config -n kube-system; set the annotation namespace regex back to ""), otherwise myapp will be scraped twice.

Lab 3: scrape myapp with a PodMonitor and query data in the workspace (about 7 min)

Apply the PodMonitor (“Commands” page ①), then check whether the target allocator has discovered the targets:
TA=$(kubectl get pods -n kube-system -o name | grep ama-metrics-operator-targets | head -1)
kubectl logs -n kube-system $TA -c targetallocator --tail=30 | grep -i -E 'podmonitor|myapp|error'
confirm up in the collector replica UI:
RS=$(kubectl get pods -n kube-system -l rsName=ama-metrics -o name | head -1)
kubectl port-forward -n kube-system $RS 9090 &
sleep 2
curl -s localhost:9090/api/v1/targets | jq -r '.data.activeTargets[] | select(.labels.namespace=="myapp") | "\(.labels.job)\t\(.labels.pod)\t\(.health)\t\(.lastError)"'
kill %1
myapp/myapp	myapp-6c9f8d7b9-2xk4p	up
myapp/myapp	myapp-6c9f8d7b9-qq7rz	up	

If the jq filter is empty, open 127.0.0.1:9090/targets and /service-discovery in the browser (the UI path given by the official docs).

Query in the workspace (wait 1–3 minutes):
source ~/promlab/azure/env.sh
PROM_QUERY=$(az monitor account show -n $AMW -g $RG --query metrics.prometheusQueryEndpoint -o tsv)
TOKEN=$(az account get-access-token --resource https://prometheus.monitor.azure.com --query accessToken -o tsv)
q='sum by (status) (rate(myapp_http_requests_total{cluster="aks-prom-lab",namespace="myapp"}[5m]))'
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode "query=$q" "$PROM_QUERY/api/v1/query" | jq -r '.data.result[] | "\(.metric.status)\t\(.value[1])"'
200	8.93
500	0.98
Verify the keep rules work: query count({__name__=~"python_.*",namespace="myapp"}) should be empty (multi-process mode does not export python_gc_*/process_* anyway, but the keep rule is insurance against what metrics the application may add).
(Optional) compare with the ConfigMap method: use the “Commands” page ③ to validate and create the ConfigMap,/targets will then have an extra myapp-cm job; after confirming, delete the ConfigMap to avoid duplicate scraping.
Acceptance: up{namespace="myapp"} 2 entries with value 1; myapp_http_requests_total queryable in the workspace; kubectl get pods -n kube-system | grep ama-metrics 's restart count equals the number of times you applied the settings ConfigMap.
Cleanup: keep the PodMonitor (needed by later modules); delete the test ConfigMap / annotations.

Case 1: migrating 200 ServiceMonitors from kube-prometheus-stack

Problem: The cluster had open-source ServiceMonitors; after enabling the managed add-on, none of them were scraped. Approach: Write a conversion script: kubectl get servicemonitors.monitoring.coreos.com -A -o yaml | yq '.items[].apiVersion = "azmonitoring.coreos.com/v1"', add the three limit fields, and remove the release: kps selector label dependencies that only make sense for self-managed Prometheus, and apply per namespace as a canary. Limitations: Monitors with basicAuth/Secret need configuration on K8s 1.37+ secrets_access_namespaces and a Role/RoleBinding in each namespace (official steps); a Monitor that uses bearerTokenFile with deny_fs_access_through_sms = true enabled is dropped.

Case 2: the security team requires that Monitors cannot read local files of the collector

Problem: Anyone who can create a PodMonitor can reference the service account token in the collector container through bearerTokenFile and send it to an untrusted endpoint (the official docs explicitly warn of this risk). Approach: in the settings ConfigMap's prometheus-collector-settings set deny_fs_access_through_sms = true; also use RBAC to restrict who can create azmonitoring.coreos.com resources. Limitations: This setting defaults to false; once it is enabled, Monitors that use local TLS files also stop scraping, so review them first.

Case 3: a high-cardinality label causes the whole job to be up=0

Problem: A service uses user_agent original text as a label; some values exceed 1023 characters, so the whole job fails. Approach: In the Monitor, use metricRelabelings of labeldrop to drop that label, or change the application to a bounded enumeration; keep labelValueLengthLimit: 1023 so the problem is exposed explicitly at the scrape stage. Limitations: Managed side does not support metric renaming; you can only drop the metric or change it at the source.

Common errors and fixes

error: resource mapping not found for name: "myapp" … no matches for kind "PodMonitor" in version "monitoring.coreos.com/v1"

Cause: There are no open-source Prometheus Operator CRDs in the cluster, but the YAML uses the open-source API group (or the reverse: open-source CRDs exist, objects are created successfully, but the add-on does not read them).

kubectl get crd | grep coreos.com
kubectl api-resources | grep -i monitor

Fix: change to apiVersion: azmonitoring.coreos.com/v1.

myapp is not visible in /targets, and the targetallocator logs show no errors

Cause: The selector does not match (the Pod label is not app: myapp), the port is unnamed or the name is inconsistent, or the PodMonitor is not in the same namespace as the Pod and the namespace is not specified namespaceSelector.

kubectl -n myapp get pods --show-labels
kubectl -n myapp get pod -l app=myapp -o jsonpath='{.items[0].spec.containers[0].ports}'

Fix: align labels and port names; for cross-namespace cases add namespaceSelector: { matchNames: [myapp] }.

Target shows up=0, cause: label value exceeds the limit / too many labels

Cause: A series exceeds 63 labels or a label value exceeds 1023 characters — managed ingestion will make the whole job fail.

kubectl -n myapp port-forward deploy/myapp 5000:5000 &
curl -s localhost:5000/metrics | awk '{print length($0)}' | sort -n | tail -3; kill %1

Fix:metricRelabelings in action: labeldrop drop the problematic label, or change the application.

Custom ConfigMap has no effect; the config-reader logs have no “custom prometheus config” line

Cause: Wrong ConfigMap name/namespace/key (it must be kube-system/ama-metrics-prometheus-config, key prometheus-config), or the configuration failed validation and was rejected.

kubectl get cm ama-metrics-prometheus-config -n kube-system -o jsonpath='{.data}' | head -c 300
kubectl logs -n kube-system $(kubectl get pods -n kube-system -o name | grep ama-metrics-operator-targets | head -1) -c config-reader | grep -i -A3 merg

Fix: Pre-check with promconfigvalidator ; only static_configs and kubernetes_sd_configs discovery modes are supported.

forbidden: User "system:serviceaccount:kube-system:ama-metrics-serviceaccount" cannot list resource "secrets"

Cause: On K8s 1.37+ the add-on no longer has cluster-wide Secret read permission, and the Monitor references a basicAuth Secret.

Fix: In the settings ConfigMap, set secrets_access_namespaces = "kube-system,myapp", and create a Role in each namespace (secrets get/list/watch) and bind it to kube-system/ama-metrics-serviceaccount with a RoleBinding; after restarting ama-metrics, confirm SecretsAccessNamespaces from configmap: [kube-system myapp] in the TA logs.

Command-line tasks
1. Turn this machine's prometheus-config file into a ConfigMap that the add-on can read.
kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system
2. List all PodMonitors and ServiceMonitors read by the managed add-on across all namespaces.
kubectl get podmonitors.azmonitoring.coreos.com,servicemonitors.azmonitoring.coreos.com -A
Scenario analysis
A colleague wrote both a PodMonitor and a ServiceMonitor for myapp, and also enabled annotation-based scraping for the myapp namespace. The request rate on the dashboard is 3 times the actual value. What is the cause? How do you fix it?

Each of the three entry points generates a scrape job, so the same set of Pods is scraped 3 times,sum(rate(myapp_http_requests_total[5m])) and the three sets of series are added together (the job/endpoint labels differ, so they are three distinct series groups rather than “duplicate series”). Fix: keep only one entry point (PodMonitor recommended), delete the ServiceMonitor, and change podannotationnamespaceregex back to ""; in the short term, the dashboard can filter by job . Also check costs: ingested samples are 3 times as well.

Verified teaching videos

▶
Azure Managed Prometheus and Grafana for AKS monitoring — Houssem Dellai
English · community demo: enabling managed Prometheus and scraping application metrics (check CRD group names and ConfigMap schema against this lesson's 2026-11 verification)

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: four entry-point cards — PodMonitor, ServiceMonitor, ConfigMap, Pod annotation — flow into a funnel labelled target allocator.
Narration: managed collection has four entry points, but they all hand off to the target allocator, and the collector replicas do the scraping.
Shot 2 · 20–45s
Visual: in the YAML, the apiVersion line flickers, and monitoring is struck through and changed to azmonitoring.
Narration: the only syntax difference is the API group: azmonitoring dot coreos dot com. The managed collector does not read objects from the open-source group.
Shot 3 · 45–70s
Visual: the labels of one series stack up one by one; at the sixty-fourth the whole column turns red, and the target status up becomes 0.
Narration: each series may have at most sixty-three labels, and label values at most one thousand and twenty-three characters. If exceeded, the whole job fails, so the three limit fields in the template must be copied exactly.
Shot 4 · 70–90s
Visual: the terminal port-forwards to 9090, and the browser shows the targets page with two green up entries.
Narration: always verify in three places: the target allocator logs, the collector's targets page, and the up metric in the workspace.
or score ≥ 70% on the quiz

Module 4 · Azure Managed Grafana: identity, permissions and data sources

21:00 – 29:00 · two identity chains: people sign in with Entra ID and get Grafana roles; Grafana uses its own managed identity and the Monitoring Data Reader role to read the workspace
8 minStandard (X1 default / X2)Essential cannot be newly created★★★★★
Learning goals
  • Use az grafana create to create a Standard-tier instance, and understand the meaning of --sku-tier,--grafana-major-version,--principal-ids,--skip-role-assignments,--zone-redundancy .
  • Describe the differences among the four built-in Grafana roles (Admin / Editor / Viewer / Limited Viewer), and use az role assignment create to grant access to Entra users or groups.
  • Link amw-prom-lab to Grafana (three ways), and explain why Monitoring Data Reader is needed and why Contributor is not enough.
  • Import a dashboard for myapp (request rate, 5xx ratio, P95 latency, Redis status), using az grafana dashboard import and backup/restore.
Prerequisites: Lesson 1 Grafana data sources and panels; Entra ID and Azure RBAC basics. Importance:★★★★★

What: what Managed Grafana is

A Grafana service operated by Microsoft (resource type Microsoft.Dashboard/grafana), with built-in Azure Monitor and Azure Data Explorer data sources; users sign in through Microsoft Entra ID single sign-on, access control uses Azure RBAC; it provides high availability, an SLA and automatic upgrades.

TierStatusKey points
EssentialCannot be newly created; existing instances are scheduled for full deprecation on 2027-03-31No SLA, no alerting, only Azure Monitor / Prometheus / TestData data sources
Standard (recommended, CLI default)GAInstance size X1 (default) and X2 (more memory; 1000 alert rules per organization, X1 is 500); zone redundancy, deterministic outbound IP, private endpoints, Grafana alerting, SMTP, reporting/rendering, all core plugins; Grafana Enterprise optional (license fee applies). Can upgrade from X1 to X2,but cannot downgrade.

Why: why permissions are split into two chains

  • People → Grafana: who can open Grafana and whether they can edit dashboards is determined by Azure roles on the Grafana instance.
  • Grafana → data: the Grafana backend acts on its own behalf itself (system-assigned managed identity, enabled by default) to query the workspace; access is determined by data-plane roles on the workspace. So people viewing dashboards need no permissions on the workspace — this is why “shared dashboards” work — and it also means Grafana Viewers can see all data that the Grafana managed identity can read; use folder/data source permissions for isolation.

How: role list

ScopeRoleWhat it can do
Grafana instanceGrafana AdminFull control: data sources, dashboards, teams and permission management
Grafana EditorView and edit dashboards and alerts
Grafana ViewerView dashboards and alerts
Grafana Limited ViewerCan only see the home page (corresponds to Grafana's “No Basic Role”); Admin then grants access per folder/dashboard; not applicable to Grafana v9 instances
Azure Monitor workspaceMonitoring Data ReaderRead Prometheus data in the workspace (needed by the Grafana managed identity, your users, and rule automation)
Subscription / resource groupMonitoring ReaderRead the Azure Monitor management plane and platform metrics (needed when the Azure Monitor data source browses resources)

Note the wording difference between two official docs: the “Enable AKS monitoring” doc says to assign Monitoring Reader to the Grafana managed identity when linking (and requires the operator to be Owner), while the Managed Grafana “Add an Azure Monitor workspace” doc requires assigning Monitoring Data Reader. Permission to read Prometheus data follows Monitoring Data Reader ; after linking, use az role assignment list --scope $AMW_ID to check which roles were actually assigned.

Three ways to link a workspace

  1. Link at enablement time:: az aks update --enable-azure-monitor-metrics --azure-monitor-workspace-resource-id … --grafana-resource-id … (automatically assigns roles and writes the workspace into Grafana's azureMonitorWorkspaceIntegrations, requires Owner or Contributor + User Access Administrator).
  2. CLI integration command (preview): az grafana integration monitor add -g … -n … --monitor-rg-name … --monitor-name …, by default assigns a read role to Grafana on the workspace (can be --skip-role-assignments).
  3. Manually in the portal: in the workspace IAM, assign Monitoring Data Reader to the Grafana managed identity → Grafana resource Integrations → Azure Monitor workspaces → Add.

After linking succeeds, a “managed Prometheus” data source appears in Grafana (the docs state that from Grafana 13 the Azure authentication is provided by the Azure Monitor Managed Service for Prometheus plugin, and existing data sources are migrated automatically), and a set of Kubernetes dashboards is provisioned in the Dashboards → Managed Prometheus folder.

When: Managed Grafana or the built-in portal view

  • custom dashboards, cross-data-source correlation, Grafana alerting, sharing with many users → Managed Grafana Standard.
  • Just want to look at cluster curves in the AKS portal → the Grafana views in the Azure portal (the official blog says the native Grafana dashboards in the portal carry no extra charge; for feature scope follow the official FAQ “Difference between Managed Grafana and Grafana in Azure Monitor”).

Comparison with similar technologies

Managed GrafanaSelf-managed Grafana (Lesson 1)AWS AMG (Lesson 4)
Sign-inEntra ID SSOLocal admin/password or self-configured OAuthIAM Identity Center / SAML
AuthorizationAzure RBAC's four Grafana rolesGrafana internal organization rolesAMG user/group assignments
Data source authenticationManaged identity (system-assigned by default)Basic/Token stored in the Grafana DBWorkspace IAM roles
UpgradesMicrosoft-managed; major version selectable (--grafana-major-version)SelfAWS-managed
Common misconceptions① “I'm a subscription Owner, so I can get into Grafana” — the quickstart does say resource-group Owner is the minimum for UI access, because the CLI/portal grants the creator Grafana Admin; but other Owners do not automatically get Grafana roles and must be assigned explicitly. ② “Giving the Grafana managed identity Contributor lets it query data” — Contributor is a management-plane role and does not include reading Prometheus data. ③ “Viewers only see data they have permission for” — a Viewer sees what the Grafana managed identity can read, regardless of the viewer's own Azure permissions.

Architecture diagram: two identity chains

Users / Entra groupsalice@contoso Microsoft Entra IDSSO sign-in Roles on the Grafana instanceAdmin / Editor / Viewer/ Limited Viewer Managed Grafana amg-prom-labRefinement by folder / dashboard / data source permissions Chain ①: people → Grafana Chain ②: Grafana → data Grafana backendsystem-assigned managed identity Entra IDaud=prometheus.monitor… roles on the workspaceMonitoring Data Reader amw-prom-labquery endpoint /api/v1/query A viewer with no permissions at all on the workspace can still see the charts — data access boundary = the scope of the Grafana managed identity's roles
Figure 4-1: chain ① determines “who can view/edit”; chain ② determines “what Grafana can read”

Flow diagram: one panel refresh

Browser/api/ds/query Grafana session checkViewer and above data source pluginvariable substitution $__rate_interval managed identity tokenIMDS → Entra query_rangeRBAC + billing renderingtime series Each refresh is billed by “query-processed samples”: dashboard refresh interval, time range and number of panels all affect query cost
Figure 4-2: panel refresh path (query billing happens on the workspace side)

Interactive animation: step-by-step check of the two identity chains (you can “unplug” roles)

Remove a role assignment, then play through “open the myapp dashboard”. The animation checks each hop in the real order and shows the matching HTTP exchanges or errors in the terminal (error text is an example of a common form; the exact wording varies by version).

Adjust the switches above, then play.
GET https://amg-prom-lab-xxxx-…grafana.azure.com/d/myapp

Core commands and parameters

CommandPurposeKey parameters / notes
az grafana createCreate a workspace (idempotent)--sku-tier (default Standard),--grafana-major-version,--principal-ids (specify Grafana Admin; once specified, the current account is no longer assigned automatically),--skip-role-assignments,--zone-redundancy,--public-network-access
az grafana showendpoint, managed identity, version--query properties.endpoint,identity.principalId
az grafana integration monitor addLink workspace (preview)--monitor-rg-name --monitor-name; by default assigns the read role
az role assignment creategrants the Grafana role / data-read role--scope are the Grafana instance ID / workspace ID respectively
az grafana data-source listView data sourcesConfirm the managed Prometheus data source exists
az grafana dashboard importImport dashboard--definition can be a JSON string, gallery ID, file path (@file.json) or URL; --folder,--overwrite
az grafana backup / restoreBackup / migrate content--components dashboards folders datasources,--remap-data-sources
az grafana update --major-versionUpgrade Grafana major versionfollow the official upgrade guide; upgrades are usually irreversible
source ~/promlab/azure/env.sh
az grafana create -n $AMG -g $RG -l $LOC --sku-tier Standard
export AMG_ID=$(az grafana show -n $AMG -g $RG --query id -o tsv)
export AMG_MI=$(az grafana show -n $AMG -g $RG --query identity.principalId -o tsv)
az grafana show -n $AMG -g $RG --query "{endpoint:properties.endpoint,version:properties.grafanaVersion,sku:sku.name,mi:identity.type}" -o json
{
  "endpoint": "https://amg-prom-lab-12345-abcdefgh.ccan.grafana.azure.com",
  "mi": "SystemAssigned",
  "sku": "Standard",
  "version": "12.x.x"
}

How to verify: Open the endpoint in a browser; signing in with SSO as the creator should get you in (the creator receives Grafana Admin by default). Common errors: Names are globally unique, so a duplicate name causes a conflict; version numbers follow the actual output.

Link the workspace (choose one way)

# Method A: re-run az aks update with Grafana (requires Owner, or Contributor + UAA)
AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
az aks update -g $RG -n $AKS --enable-azure-monitor-metrics \
  --azure-monitor-workspace-resource-id $AMW_ID --grafana-resource-id $AMG_ID

# Method B: CLI integration command (preview)
az grafana integration monitor add -g $RG -n $AMG --monitor-rg-name $RG --monitor-name $AMW

# Method C: manual role assignment + portal Integrations → Azure Monitor workspaces → Add
az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal \
  --role "Monitoring Data Reader" --scope $AMW_ID

# Check the result
az role assignment list --scope $AMW_ID --query "[].{principal:principalId,role:roleDefinitionName}" -o table
az grafana data-source list -n $AMG -g $RG --query "[].{name:name,type:type,url:url}" -o table
Principal                             Role
------------------------------------  ----------------------
9f1c… (Grafana managed identity)              Monitoring Data Reader
Name                         Type                                   Url
---------------------------  -------------------------------------  ---------------------------------------------------------------
Azure Monitor                grafana-azure-monitor-datasource
Managed_Prometheus_amw-prom-lab  prometheus                         https://amw-prom-lab-a1b2.canadacentral.prometheus.monitor.azure.com

Data source names and types vary by Grafana version (dedicated plugin from Grafana 13); follow the actual list.

Grant access to colleagues

az role assignment create --assignee "bob@contoso.com" --role "Grafana Viewer" --scope $AMG_ID
# Recommended: grant to an Entra group (object ID)
az role assignment create --assignee-object-id <group-object-id> --assignee-principal-type Group \
  --role "Grafana Editor" --scope $AMG_ID

Lab 4: create Grafana, link the workspace, import the myapp dashboard (about 7 min)

Costs and permissions: Standard is billed by instance running time + active users (canadacentral retail prices: Standard Node 0.04104 USD/hour, Standard User 6 USD/month; zone redundancy extra),billing starts as soon as it is created; creating it requires Contributor on the resource group, and linking requires the ability to assign roles.
Create and link: run the creation command and “Method B” (or A) from the “Commands” page, then sign in to Grafana and open Dashboards → Managed Prometheus → Kubernetes / Compute Resources / Cluster, and confirm there is data.
Import the myapp dashboard:
{
  "title": "myapp on AKS (managed Prometheus)",
  "uid": "myapp-aks",
  "schemaVersion": 39,
  "time": { "from": "now-1h", "to": "now" },
  "templating": { "list": [
    { "name": "datasource", "type": "datasource", "query": "prometheus", "label": "Prometheus" },
    { "name": "cluster", "type": "query", "datasource": { "type": "prometheus", "uid": "${datasource}" },
      "query": "label_values(myapp_http_requests_total, cluster)", "refresh": 2 }
  ]},
  "panels": [
    { "type": "timeseries", "title": "Request rate by status", "gridPos": { "x": 0, "y": 0, "w": 12, "h": 8 },
      "datasource": { "type": "prometheus", "uid": "${datasource}" },
      "targets": [{ "refId": "A", "legendFormat": "{{status}}",
        "expr": "sum by (status) (rate(myapp_http_requests_total{cluster=\"$cluster\",namespace=\"myapp\"}[$__rate_interval]))" }] },
    { "type": "stat", "title": "5xx ratio", "gridPos": { "x": 12, "y": 0, "w": 6, "h": 8 },
      "datasource": { "type": "prometheus", "uid": "${datasource}" }, "fieldConfig": { "defaults": { "unit": "percentunit" } },
      "targets": [{ "refId": "A",
        "expr": "sum(rate(myapp_http_requests_total{cluster=\"$cluster\",namespace=\"myapp\",status=~\"5..\"}[5m])) / sum(rate(myapp_http_requests_total{cluster=\"$cluster\",namespace=\"myapp\"}[5m]))" }] },
    { "type": "stat", "title": "Redis up", "gridPos": { "x": 18, "y": 0, "w": 6, "h": 8 },
      "datasource": { "type": "prometheus", "uid": "${datasource}" },
      "targets": [{ "refId": "A", "expr": "min(myapp_redis_up{cluster=\"$cluster\",namespace=\"myapp\"})" }] },
    { "type": "timeseries", "title": "P95 latency by route", "gridPos": { "x": 0, "y": 8, "w": 24, "h": 8 },
      "datasource": { "type": "prometheus", "uid": "${datasource}" }, "fieldConfig": { "defaults": { "unit": "s" } },
      "targets": [{ "refId": "A", "legendFormat": "{{route}}",
        "expr": "histogram_quantile(0.95, sum by (le, route) (rate(myapp_http_request_duration_seconds_bucket{cluster=\"$cluster\",namespace=\"myapp\"}[$__rate_interval])))" }] }
  ]
}
az grafana folder create -n $AMG -g $RG --title "myapp"
az grafana dashboard import -n $AMG -g $RG --folder "myapp" --overwrite true \
  --definition @$HOME/promlab/azure/myapp-dashboard.json
az grafana dashboard list -n $AMG -g $RG --query "[?folderTitle=='myapp'].{title:title,uid:uid}" -o table
Title                               Uid
----------------------------------  ---------
myapp on AKS (managed Prometheus)   myapp-aks

If the CLI version has different wrapping requirements for --definition (some versions require an outer {"dashboard": {...}} wrapper), adjust according to az grafana dashboard import -h , or paste the JSON directly in the UI Dashboards → New → Import .

Verify the two identity chains: use another test account (or ask a colleague) to access the endpoint — it should be rejected when unauthorized; after assigning Grafana Viewer , they can view the dashboard but cannot save changes.
Try “unplugging” the data role (optional; restore immediately afterwards):
az role assignment delete --assignee $AMG_MI --role "Monitoring Data Reader" --scope $AMW_ID
# After a few minutes, refresh the panel: a 403 / permission error appears
az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal --role "Monitoring Data Reader" --scope $AMW_ID
Back up the dashboard (migration / disaster-recovery drill):
mkdir -p ~/promlab/azure/grafana-backup
az grafana backup -n $AMG -g $RG -d ~/promlab/azure/grafana-backup --folders-to-include myapp --components dashboards folders datasources
Cleanup: keep Grafana for later modules; when no longer needed, az grafana delete -n $AMG -g $RG --yes (cleaned up uniformly in module 8).

Case 1: authorization by Entra group and “Limited Viewer + folder permissions”

Problem: One Grafana service for 20 application teams; team A should not see team B's dashboards. Approach: Everyone defaults to Grafana Limited Viewer; Grafana Admin creates folders per team and, in Settings → Permissions grants View/Edit to the matching Grafana Team (synced with the Entra group). Limitations: Component permissions cannot restrict Grafana Admin; the effective permission is the highest among all sources, and a lower permission does not override an inherited higher one. At the data source level it is still the same managed identity, so sensitive data must go to a separate workspace with its own data source.

Case 2: dashboards as code

Problem: Manual dashboard edits cause inconsistencies between environments. Approach: Store dashboard JSON in Git and publish it in CI using az grafana dashboard import --overwrite true ; for cross-instance migration use az grafana dashboard sync (preview) or backup/restore --remap-data-sources. The CI identity uses a service principal granted Grafana Editor. Limitations: Dashboards in the “Provisioned” state are skipped during sync (read-only).

Case 3: private network access and deterministic outbound IP

Problem: Grafana must query an external data source that only allows a fixed IP, and the company requires that Grafana not be exposed to the public internet. Approach: Enable --deterministic-outbound-ip Enabled on Standard, add the outbound IP to the other side's allowlist; create a private endpoint and --public-network-access Disabled. Limitations: These are all Standard-only features; once public access is closed, CLI data-plane commands (dashboard/data-source) must also be run from a network that can reach the private endpoint.

Common errors and fixes

Signing in to Grafana shows: You don't have permission / No role assigned

Cause: The user has no Grafana role on the Grafana instance (a subscription Owner does not automatically get one either).

az role assignment list --scope $AMG_ID --query "[].{who:principalName,role:roleDefinitionName}" -o table

Fix: Assign Grafana Viewer/Editor/Admin; sign in again after role changes.

Panel error: 403 / "Forbidden" / authorization failed when querying Prometheus

Cause: The Grafana managed identity lacks Monitoring Data Reader on the workspace, or the system-assigned managed identity was turned off or replaced with a user-assigned identity that was not granted access.

az grafana show -n $AMG -g $RG --query identity
az role assignment list --scope $AMW_ID --assignee $AMG_MI -o table

Fix: Complete the role assignment; on the Identity page of the Grafana resource Identity confirm that the system-assigned identity is On.

CLI error: (AuthorizationFailed) … Microsoft.Authorization/roleAssignments/write (when running --grafana-resource-id or integration monitor add)

Cause: The operator has no permission to assign roles.

Fix: Ask an Owner / User Access Administrator to run it; or use --skip-role-assignments to link only, and let an admin assign roles separately.

No pre-provisioned dashboards in the managed Prometheus folder

Cause: The data source was not added through the “link workspace” flow (for example, a Prometheus data source was created by hand), or the linking has not completed.

az grafana show -n $AMG -g $RG --query properties.grafanaIntegrations
az grafana integration monitor list -g $RG -n $AMG

Fix: Complete the link using method A, B or C; the provisioned dashboards can also be imported manually from the official GitHub repository.

Charts keep loading (Charts are stuck in a loading state)

Cause: Browser-side blocking of the monitor.azure.com traffic (ad-blocking extension or corporate proxy) — a known cause listed in the official troubleshooting documentation.

Fix: Disable the blocking extension or add monitor.azure.com to the allowlist, then refresh.

Command-line tasks
1. Grant the managed identity of Grafana amg-prom-lab-12345 permission to read data from amw-prom-lab.
MI=$(az grafana show -n amg-prom-lab-12345 -g rg-prom-lab --query identity.principalId -o tsv)
AMW_ID=$(az monitor account show -n amw-prom-lab -g rg-prom-lab --query id -o tsv)
az role assignment create --assignee-object-id $MI --assignee-principal-type ServicePrincipal --role "Monitoring Data Reader" --scope $AMW_ID
2. Set the Entra group (object ID 1111…) as read-only users.
az role assignment create --assignee-object-id 1111aaaa-0000-0000-0000-000000000000 --assignee-principal-type Group \
  --role "Grafana Viewer" --scope $(az grafana show -n amg-prom-lab-12345 -g rg-prom-lab --query id -o tsv)
Scenario analysis
A security audit found that an outsourced staff member with only Grafana Viewer can query metrics for all namespaces of the production cluster in Explore. Why? How do you tighten it?

Grafana queries the workspace with its own managed identity, so a viewer can see all data that the managed identity can read; in most versions the Viewer role can still use Explore (depending on Grafana configuration). Tightening: ① give outsourced staff Grafana Limited Viewer, granting access only to specific folders/dashboards; ② for sensitive environments, use a separate workspace and separate data source, and restrict who can query via data source permissions; ③ where necessary, split Grafana instances for different audiences; ④ audit regularly az role assignment list --scope $AMG_ID.

Verified teaching videos

▶
How to Deploy Azure Managed Grafana — Travis Roberts
English · deployment and access-control demo (the Essential tier may still have been present when recorded, and it can no longer be newly created)
▶
Azure Managed Grafana: Latest Updates — Azure Power Lunch
English · feature update review, to understand how Standard-tier capabilities have evolved

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: terminal runs az grafana create and outputs the endpoint; after opening it in the browser, it redirects to Microsoft sign-in.
Narration: Managed Grafana signs in with Entra ID single sign-on; there is no local admin password to keep.
Shot 2 · 20–45s
Visual: one chain at the top, “user → Entra → Grafana Viewer → Grafana”; one chain at the bottom, “Grafana managed identity → Entra → Monitoring Data Reader → workspace”.
Narration: permissions form two chains: whether a person can enter Grafana depends on the Grafana role on the instance; whether Grafana can read data depends on the data-read role on the workspace.
Shot 3 · 45–70s
Visual: the Monitoring Data Reader link in the bottom chain is cut, and the panel turns red showing 403.
Narration: if the second chain is cut, every viewer sees a permission error, regardless of their own permissions.
Shot 4 · 70–90s
Visual: the four myapp dashboard panels appear in turn: request rate, 5xx ratio, Redis status, P95 latency.
Narration: after linking, dashboards become code; the same JSON can be reused between test and production Grafana.
or score ≥ 70% on the quiz

Module 5 · Managed alert rule groups and Action Groups

29:00 – 37:00 · the rules/*.yml from Lesson 2 become ARM resources on the managed path: rule groups evaluate on the workspace side, alerts enter Azure Monitor, and Action Groups handle notification
8 minprometheusRuleGroups API 2023-03-01alertsmanagement extension★★★★★
Learning goals
  • Understand the scope (workspace + optional cluster ID + clusterName), evaluation interval interval (default PT1M) and rule execution order.
  • Map Prometheus rule fields to managed fields: for (ISO 8601, such as PT5M),severity (0–4, default 3),resolveConfiguration.autoResolved/timeToResolve (default true / PT5M),actions[].actionGroupId.
  • Create an Action Group (email, common alert schema), connect myapp's 5xx, missing-target and Redis-down alerts to notifications, and complete the closed loop of “trigger → email → auto-resolve”.
  • Learn how to enable recommended alerts (community rules + platform metric rules) and the purpose of az-prom-rules-converter .
Prerequisites: Lesson 2's alerting rules and the Alertmanager lifecycle. Importance:★★★★★

What: rule groups and Action Groups

Prometheus rule group (Microsoft.AlertsManagement/prometheusRuleGroups) is a set of recording and alert rules evaluated together, existing as an Azure resource (with subscription, resource group, region and tags). The rule syntax follows open-source Prometheus (name, expression, labels, annotations); alerting rules add Azure-specific properties: severity, Action Group association, and auto-resolve configuration.

Open-source Prometheus (Lesson 2)Managed rule groupNotes
groups[].nameRule group resource nameunique within the resource group; cannot be changed after creation
interval: 1minterval: PT1MISO 8601 duration, default PT1M
Implicit scope of the Prometheus instancescopes: workspace ID (required) + optionally one cluster ID; clusterNameif no cluster is specified, rules query data from all clusters in the workspace
record / expr / labelsrecord / expression / labelsresults are written back to the workspace as new series (this incurs ingestion)
alert / expr / for: 5malert / expression / for: PT5Malso has a pending stage
labels.severity: criticalseverity: 0–40 is most severe, default 3
Alertmanager routing → receiveractions[].actionGroupId (specified directly on each rule)no routing tree; cross-rule silences / inhibition use alert processing rules
send_resolved: trueresolveConfiguration.autoResolved: true,timeToResolve: PT10Mthe condition must remain false for this period before it auto-resolves

Action Group (Microsoft.Insights/actionGroups) is a set of notification/automation receivers: email, SMS, voice, Azure app push, webhooks (can carry Entra authentication), Logic Apps (can post to Teams), Azure Functions, Automation runbooks, Event Hub, ITSM, ARM roles. All types of Azure Monitor alerts can reuse the same Action Group.

Why: why rules live on the workspace side

  • The collector is a stateless agent and does not evaluate rules; workspace-side evaluation can span clusters (when cluster is not restricted) and is managed uniformly by Azure Monitor alerts (state, history, acknowledgement, processing rules).
  • Rule groups are ARM resources → they can be governed uniformly with Bicep/ARM/Terraform, Azure Policy and RBAC (Monitoring Contributor is enough to create them).
  • Rule groups have a resource health (Available / Degraded / Unavailable / Unknown); a query that is throttled or misconfigured shows Degraded — observability that self-managed Prometheus does not have.

How: the lifecycle of one alert

  1. Each interval, the rule group uses PromQL to query the workspace (on the data scoped by clusterName ).
  2. An expression result → enters pending; once the condition has held for the for duration → fired, generating an Azure Monitor alert (with severity, labels and annotations).
  3. When the alert fires, it triggers each Action Group configured on the rule; alert processing rules can suppress or add notifications before this step (such as maintenance windows).
  4. Once the condition no longer holds for timeToResolve → auto-resolved (Resolved); receivers using the common alert schema receive the “resolved” notification.

Rules available out of the box

  • Default recording rules: created automatically when metrics are enabled (node/namespace/workload CPU and memory aggregations), for use by the pre-provisioned dashboards.
  • Recommended alerts: cluster Alerts → Set up recommendations, enabling Prometheus community rules at the cluster / node / Pod level (such as KubePodCrashLooping,KubeContainerOOMKilledCount,KubeNodeUnreachable,KubePVUsageHigh,KubeDeploymentReplicasMismatch) and platform metric rules (node CPU > 95%, node working-set memory > 100%); the official ARM/Bicep templates can also be used. It is also recommended to enable the recommended workspace ingestion-quota alert.
  • The legacy Container insights custom metric alerts were retired on 2024-05-31; migrate to recommended alerts.

When: choose Prometheus rule groups or other alerts

  • PromQL-based application/cluster alerts → rule groups (this module).
  • Based on log content (a specific error log appears) → log search alerts (Log Analytics, module 6).
  • Only AKS platform metrics (node CPU) → platform metric alerts.
  • If the team heavily uses Grafana alerting and handles alerts only inside Grafana → Grafana Alerting on Managed Grafana Standard (X1: 500 rules per organization, X2: 1000). But do not configure the same condition in two places.

Comparison with similar technologies

Azure managed rule groupsPrometheus + Alertmanager (Lesson 2)AMP rules + Alertmanager (Lesson 4)
Rule formatARM/Bicep JSON (convertible from YAML)YAMLYAML (upload)
Routing / groupingNo routing tree; each rule binds an Action GroupRouting tree, group_byAlertmanager configuration
SilencesAlert processing rules (by scope / time)silencesilence
Notification channelsAction Group (email / SMS / webhook / ITSM…)receiverSNS
Common misconceptions① “for: 5m ① “It can be copied as-is” — managed rules require ISO 8601 (PT5M). ② “The rule group automatically queries only my cluster” — without a cluster scope and clusterName clusterName, the query covers all clusters in the workspace; if you have changed cluster_alias cluster_alias,clusterName then clusterName must be the alias. ③ “A preview with no data means the expression is wrong” — alert expressions usually return only the series that meet the condition, so an empty preview when nothing is firing is normal (officially noted).

Architecture diagram: rule groups, alerts and notifications

amw-prom-labmyapp_http_requests_totalcluster="aks-prom-lab" Rule group myapp-rulesscopes: AMW + AKSclusterName: aks-prom-labinterval: PT1Mrecord myapp:http_requests:rate5malert MyAppHigh5xxRatio (for PT5M)alert MyAppPodsMissing / RedisDown PromQL recording results written back Azure Monitor alertsSev2 · Fired / Resolvedlabels + annotationsresource healthAlert processing rule (silence) Action Groupag-prom-lab Email (common alert schema) Webhook / Logic App→Teams
Figure 5-1: rule groups evaluate on the workspace side; alerts become Azure Monitor alert objects, which are then notified by Action Groups

Timeline: 5xx ratio alert

Normal 2% Pending: ratio 10% > 5%, for PT5M timing Fired → Action Group After recovery, timeToResolve PT10M t0 first mett0+5m firesCondition clearsResolved Adding 1–2 minutes of ingestion delay and the PT1M evaluation interval: from failure to receiving the email takes about 6–8 minutes
Figure 5-2: for and timeToResolve determine the “stable period” before firing and before resolving, respectively

Interactive simulator: managed alert timeline

Drag the “5xx ratio” slider to simulate a fault and recovery, and click “Run” to advance by the evaluation interval (PT1M). The simulator shows each evaluation result of the rule group, the alert state (Inactive → Pending → Fired → Resolved), the Action Group notifications and the corresponding Azure-side events. The timeline is compressed (1 second = 1 minute).

Current 5xx ratio: 10% (threshold 5%)
for: timeToResolve:
Alert state:Inactive t = 0 min
Ready: loadgen sends 1 in 10 requests to /error, so the 5xx ratio is about 10%.
Rule group myapp-rules · interval PT1M · scopes [amw-prom-lab, aks-prom-lab]

Core commands and parameters

CommandPurposeKey parameters / notes
az monitor action-group createCreate an Action Group--short-name (shown in SMS),--action email NAME ADDRESS [usecommonalertschema],--action webhook NAME URI …
az monitor action-group test-notifications createSend a test notificationVerify the email is received
az alerts-management prometheus-rule-group createCreate a rule group--scopes (workspace ID [+ cluster ID]),--cluster-name,--interval PT1M,--rules (JSON array; can use @file),--enabled
az alerts-management prometheus-rule-group show/list/update/deleteManage rule groupsupdate --enabled false Disable the whole group
az graph queryQuery fired alertstable alertsmanagementresources (requires the resource-graph extension)

① Action Group

source ~/promlab/azure/env.sh
az monitor action-group create -g $RG -n $AG --short-name promlab \
  --action email oncall $ALERT_EMAIL usecommonalertschema
export AG_ID=$(az monitor action-group show -g $RG -n $AG --query id -o tsv)
az monitor action-group show -g $RG -n $AG --query "emailReceivers[].{name:name,addr:emailAddress,status:status,common:useCommonAlertSchema}" -o table
Name    Addr              Status   Common
------  ----------------  -------  --------
oncall  you@example.com   Enabled  True

The Action Group's default location is Global. Recipients receive a notification email saying they were added to the Action Group; if a recipient unsubscribes, use az monitor action-group enable-receiver to re-enable.

② Rule JSON (hand-converted from the Lesson 2 YAML)

[
  {
    "record": "myapp:http_requests:rate5m",
    "expression": "sum by (namespace, status) (rate(myapp_http_requests_total{namespace=\"myapp\"}[5m]))",
    "enabled": true
  },
  {
    "alert": "MyAppHigh5xxRatio",
    "expression": "sum(rate(myapp_http_requests_total{namespace=\"myapp\",status=~\"5..\"}[5m])) / sum(rate(myapp_http_requests_total{namespace=\"myapp\"}[5m])) > 0.05",
    "for": "PT5M",
    "severity": 2,
    "labels": { "team": "myapp" },
    "annotations": {
      "summary": "myapp 5xx ratio exceeds 5%",
      "description": "Current 5xx ratio {{ $value | humanizePercentage }}; see the myapp dashboard and ContainerLogV2"
    },
    "enabled": true,
    "resolveConfiguration": { "autoResolved": true, "timeToResolve": "PT10M" },
    "actions": [ { "actionGroupId": "AG_ID_PLACEHOLDER" } ]
  },
  {
    "alert": "MyAppPodsMissing",
    "expression": "(sum(up{namespace=\"myapp\",pod=~\"myapp-.*\"}) or vector(0)) < 2",
    "for": "PT3M",
    "severity": 1,
    "labels": { "team": "myapp" },
    "annotations": { "summary": "fewer than 2 myapp replicas can be scraped" },
    "enabled": true,
    "resolveConfiguration": { "autoResolved": true, "timeToResolve": "PT5M" },
    "actions": [ { "actionGroupId": "AG_ID_PLACEHOLDER" } ]
  },
  {
    "alert": "MyAppRedisDown",
    "expression": "min(myapp_redis_up{namespace=\"myapp\"}) == 0",
    "for": "PT2M",
    "severity": 1,
    "labels": { "team": "myapp" },
    "annotations": { "summary": "myapp cannot connect to Redis" },
    "enabled": true,
    "resolveConfiguration": { "autoResolved": true, "timeToResolve": "PT5M" },
    "actions": [ { "actionGroupId": "AG_ID_PLACEHOLDER" } ]
  }
]

Notes: MyAppPodsMissing use or vector(0) to handle the case where “all targets have disappeared,up series do not exist” (Lesson 2 covered a similar problem with absent() ). The annotation {{ $value }} template rendering in managed rules should be confirmed against real alerts.

③ Create the rule group

cd ~/promlab/azure
export AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
export AKS_ID=$(az aks show -g $RG -n $AKS --query id -o tsv)
sed "s#AG_ID_PLACEHOLDER#$AG_ID#g" myapp-rules.json > myapp-rules.rendered.json
az alerts-management prometheus-rule-group create -n myapp-rules -g $RG -l $LOC \
  --enabled --description "myapp SLO rules (lesson 3)" --interval PT1M \
  --scopes $AMW_ID $AKS_ID --cluster-name $AKS \
  --rules @myapp-rules.rendered.json
az alerts-management prometheus-rule-group show -n myapp-rules -g $RG \
  --query "{enabled:enabled,cluster:clusterName,interval:interval,rules:length(rules)}" -o json
{
  "cluster": "aks-prom-lab",
  "enabled": true,
  "interval": "PT1M",
  "rules": 4
}

Common errors: Inlining JSON directly in the shell is very error-prone for quote escaping; prefer @file; if your CLI version does not accept @file, use --rules "$(cat myapp-rules.rendered.json)" or an ARM/Bicep template (rule group API version 2023-03-01). Production use: Store the rule YAML in Git and use az-prom-rules-converter to generate an ARM template in CI and deploy it.

④ View fired alerts

az extension add --name resource-graph --upgrade
az graph query -q "alertsmanagementresources
 | where type =~ 'microsoft.alertsmanagement/alerts'
 | where properties.essentials.startDateTime > ago(2h)
 | project name, sev=properties.essentials.severity, state=properties.essentials.monitorCondition, start=properties.essentials.startDateTime
 | order by tostring(start) desc" -o table
Name               Sev   State   Start
-----------------  ----  ------  --------------------------
MyAppHigh5xxRatio  Sev2  Fired   2026-11-15T10:21:03.000Z

Lab 5: 5xx alert → email → auto-resolve (about 10 min, including waiting)

Costs and permissions: creating a rule group requires Monitoring Contributor; managed Prometheus rule evaluation is billed by query-processed samples (very small volume); email notifications are billed per message (after the free allowance, about 0.00002 USD per email in the retail prices API; see the pricing page).
Create an Action Group and send a test notification: run “Commands” ①; on the portal's Action Group page click Test action group (or az monitor action-group test-notifications create, parameters follow -h ), and confirm the test email is received.
Create the rule group: run ② and ③. In the portal Monitor → Alerts → Prometheus rule groups you can see myapp-rules, the resource health should be Available.
Wait for it to fire: loadgen keeps the 5xx ratio at about 10%. First verify that the recording rule has been written back:
TOKEN=$(az account get-access-token --resource https://prometheus.monitor.azure.com --query accessToken -o tsv)
PROM_QUERY=$(az monitor account show -n $AMW -g $RG --query metrics.prometheusQueryEndpoint -o tsv)
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode 'query=myapp:http_requests:rate5m' "$PROM_QUERY/api/v1/query" | jq -r '.data.result[] | "\(.metric.status)\t\(.value[1])"'
After about 6–8 minutes you should receive the Fired email MyAppHigh5xxRatio (Sev2).
Fix and observe auto-resolve: stop loadgen from accessing /error:
kubectl -n myapp delete pod loadgen
kubectl -n myapp run loadgen --image=curlimages/curl:8.11.1 --restart=Always -- \
  sh -c 'while true; do curl -s -o /dev/null http://myapp:5000/; sleep 0.1; done'
After the 5-minute window passes the ratio drops to 0; after another timeToResolve (PT10M) you receive the Resolved email.
(Optional) Redis down alert: kubectl -n myapp scale deploy redis --replicas=0, after about 3–5 minutes you receive MyAppRedisDown (Sev1); then --replicas=1 restore.
(Optional) enable recommended alerts: portal AKS cluster → Alerts → Set up recommendations, open the Pod-level rule groups, select Action Group ag-prom-lab, and save. Note this creates several rule groups; delete them together during cleanup.
Cleanup: keep the rule group for module 7; if you want to stop notifications: az alerts-management prometheus-rule-group update -n myapp-rules -g $RG --enabled false.

Case 1: migrating 80 PrometheusRules to rule groups

Problem: Rule YAML in the self-managed stack is spread across several charts. Approach: Export to standard Prometheus rule files and use the official az-prom-rules-converter to generate ARM templates (needs subscription, resource group, region, workspace, cluster ID/name, Action Group); one rule group per cluster (the same rule set copied per cluster, each scoped to one cluster), to avoid a single group querying all clusters and getting throttled. Limitations: Logic that relies on Alertmanager routing (dispatching by team label) must be changed to “each rule specifies an Action Group”, or use a webhook to a routing service of your own.

Case 2: maintenance-window silencing

Problem: During AKS node upgrades every Tuesday,KubeNodeUnreachable and application alerts flood the channels. Approach: Create an alert processing rule, scoped to that cluster / resource group, with the rule type “remove all Action Groups”, applied on a weekly schedule; alerts are still recorded, only notifications are suppressed. Limitations: Alert processing rules act at the Azure Monitor alert layer and do not change rule group evaluation; the official docs note that cluster-level collection has a 1–2 minute gap during node upgrades, but recommended alerts already account for this.

Case 3: alerts to Teams and tickets

Problem: The on-call team uses Teams and ServiceNow. Approach: Add a Logic App (the official approach for “send a Teams message”) and an ITSM receiver to the Action Group; enable the common alert schema for all receivers to make downstream parsing easier. Limitations: SMS/voice are priced by country and have rate limits; for webhooks, enabling Entra authentication is recommended (useaadauth).

Common errors and fixes

Rule group resource health Degraded: query throttled / rule evaluation failed

Cause: The expression queries too much data (no cluster restriction, too long a time window, high cardinality by), or the expression syntax is not accepted on the managed side.

Diagnosis: Portal rule group → Help → Resource health expand the status description (30 days of history retained); run the expression alone with the query API to measure its duration.

Fix: add a cluster scope / clusterName; pre-aggregate with a recording rule first and have the alert reference the aggregated result; split rule groups by cluster.

(BadRequest) … 'for' … is not a valid duration / Invalid value for 'interval'

Cause: The Prometheus syntax 5m was placed directly into managed rules.

Fix: change to ISO 8601: PT5M,PT1M,PT1H.

Rule shows Enabled, the expression returns > 0.05 in Grafana, but it never fires

Cause:① clusterName The cluster labels in the data do not match (the cluster alias was set cluster_alias); ② the rule group scope points to another workspace; ③ labels in the expression (such as job) differ from the values actually produced by managed collection.

az alerts-management prometheus-rule-group show -n myapp-rules -g $RG --query "{scopes:scopes,cluster:clusterName}"
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode 'query=count by (cluster) (up)' "$PROM_QUERY/api/v1/query" | jq '.data.result'

Fix: Align clusterName with the scope; prefer stable labels such as namespace/pod in expressions.

Alert is Fired but no email is received

Cause: The rule is not configured with actions; the Action Group is disabled; the recipient unsubscribed or the email went to spam; an alert processing rule removed the Action Group; email rate limits.

az alerts-management prometheus-rule-group show -n myapp-rules -g $RG --query "rules[?alert!=null].{alert:alert,ag:actions[0].actionGroupId}" -o table
az monitor action-group show -g $RG -n $AG --query "{enabled:enabled,receivers:emailReceivers[].status}"

Fix: add actionGroupId; enable-receiver check the alert processing rules.

(AuthorizationFailed) … Microsoft.AlertsManagement/prometheusRuleGroups/write

Cause: Lacking permission to create rule groups in the target resource group.

Fix: grant Monitoring Contributor (official prerequisite) or higher.

Command-line tasks
1. Create an Action Group named ag-prom-lab that notifies oncall@example.com and enables the common alert schema.
az monitor action-group create -g rg-prom-lab -n ag-prom-lab --short-name promlab \
  --action email oncall oncall@example.com usecommonalertschema
2. Temporarily disable the whole rule group myapp-rules (do not delete it).
az alerts-management prometheus-rule-group update -n myapp-rules -g rg-prom-lab --enabled false
Scenario analysis
You are moving the Lesson 2 rules (for: 5m, with Alertmanager routing by team labels to different mailboxes) to Azure. How should rule groups and Action Groups be designed?

① use az-prom-rules-converter to convert the YAML into ARM, and convert for to PT5M; ② the managed side has no routing tree, so split by team: one Action Group per team, and rules point to the matching team via actions[].actionGroupId directly (you can split into multiple rule groups per team for authorization and disabling); ③ one rule group per cluster (scope + clusterName) to avoid large cross-cluster queries; ④ use alert processing rules for maintenance windows and suppression; ⑤ when complex routing is needed, have the Action Group send to a webhook into your own routing service (or keep one Alertmanager).

Verified teaching videos

▶
Microsoft Azure Monitor - Alert Processing Rules — John Savill's Technical Training
English · explains alert processing rules (maintenance-window silencing, adding Action Groups), complementary to this module's “no Alertmanager silences on the managed side”
▶
Azure Master Class v2 - Module 10 - Monitoring & Security — John Savill's Technical Training
English · long-form video on the overall framework of Azure Monitor alerts and Action Groups

No verified video specifically covering “managed Prometheus rule groups” was found; the storyboard below can be used for a self-made video.

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: a rules.yml on the left and a JSON on the right, with fields connected one by one: for 5m becomes PT5M, and the severity label becomes the number 2.
Narration: managed rules keep the Prometheus syntax; only the time is written in ISO 8601, and severity is a number from zero to four.
Shot 2 · 20–45s
Visual: the rule group icon flashes at each timeline tick; once the 5xx curve crosses the 5% dashed line, the state changes from Pending to Fired.
Narration: the rule group evaluates once a minute on the workspace side; after the condition has held for five minutes, it fires an Azure Monitor alert.
Shot 3 · 45–70s
Visual: the alert card flies to the Action Group and splits into three icons: email, Teams, ticket.
Narration: notifications no longer have a routing tree; each rule specifies an Action Group directly, and maintenance windows are silenced with alert processing rules.
Shot 4 · 70–90s
Visual: the curve falls back; after a ten-minute grey interval the state changes to Resolved, and the mailbox receives a second email.
Narration: auto-resolve happens once the condition has cleared and stayed clear for ten minutes. Don't forget that from fault to email you also add one to two minutes of ingestion delay.
or score ≥ 70% on the quiz

Module 6 · Container Insights, correlating logs and metrics

37:00 – 45:00 · metrics tell you “when and how severe”, logs tell you “why”; line the two up using the same time window and the same Pod labels
8 minContainerLogV2 defaultbilled per GB★★★★
Learning goals
  • Name the components of Container Insights (ama-logs DaemonSet,ama-logs-rs) and the data flow (DCR stream → Log Analytics table), and how responsibilities are split with managed Prometheus.
  • Use az aks enable-addons --addon monitoring --data-collection-settings with the “Logs and Events” cost preset to collect only ContainerLogV2,KubeEvents,KubePodInventory.
  • Write KQL to find the access logs, Pod events and restarts corresponding to myapp's 5xx, and in Grafana place the PromQL panel and the KQL panel side by side.
Prerequisites: Module 2's DCR concept; KQL basics (where / summarize / bin). Importance:★★★★

What: what Container Insights collects

Container Insights (AKS monitoring add-on,az aks show shown in the portal as addonProfiles.omsagent) is likewise based on the containerized Azure Monitor agent: ama-logs the DaemonSet reads container stdout/stderr and so on, on each node,ama-logs-rs replicas collect cluster-level manifests and events; data is written according to the streams (stream) into tables of the Log Analytics workspace.

StreamTableContents
Microsoft-ContainerLogV2ContainerLogV2Container stdout/stderr (new architecture: columns such as PodName, PodNamespace, ContainerName, LogMessage, LogLevel)
Microsoft-KubeEventsKubeEventsKubernetes events (image pull failures, OOMKilled, scheduling failures…)
Microsoft-KubePodInventoryKubePodInventoryPod manifests and status, restart counts
Microsoft-Perf / Microsoft-InsightsMetricsPerf / InsightsMetricsperformance metrics (usually not needed when managed Prometheus is enabled)
Microsoft-ContainerInsights-Group-DefaultAll of the aboveDefault stream set

Cost presets (optional when enabling in the portal)

PresetFrequencyNamespace filteringData collected
Logs and Events (default)1mNoneContainerLogV2, KubeEvents, KubePodInventory — officially noted as “recommended when managed Prometheus is enabled”
Standard1mNoneAll standard tables
Cost-optimized5mExcludes kube-system, gatekeeper-system, azure-arcAll standard tables
Syslog1mNoneAll standard tables + Syslog

The CLI uses --data-collection-settings to pass JSON: interval (1m–30m),namespaceFilteringMode (Include/Exclude/Off, applies to manifests and performance data),namespaces,enableContainerLogV2 (default true),streams.

Why: why metrics and logs are separated yet correlated

  • Different cost models: metrics are billed per sample, which is extremely cheap and suited to aggregation and alerting; logs are billed per GB and suited to keeping raw context. With managed Prometheus handling performance data, you no longer pay log costs for Perf/InsightsMetrics.
  • Troubleshooting needs both: alerts come from metrics (5xx ratio), while root causes are often in logs (exception stacks, upstream timeouts) and events (OOMKilled, image pull failures).
  • Correlation keys: namespace / pod (Prometheus labels) ↔ PodNamespace / PodName (ContainerLogV2 columns), plus the time window. Managed Prometheus does not support exemplars (the API docs state this experimental feature is not supported), so the “jump from a metric point to a trace” approach does not apply here; use the time window + Pod association instead.

How: the logging approach for this lesson

  1. Create a Log Analytics workspace law-prom-lab.
  2. Enable the monitoring add-on and collect only the three Logs and Events streams.
  3. Upgrade myapp to myapp:1.1: gunicorn adds --access-logfile -, sending access logs to stdout (the version 1.0 from Lesson 1 does not emit access logs by default).
  4. Grant the managed identity the Log Analytics Reader role in Grafana, query Logs (KQL) through the Azure Monitor data source, and place it on the same dashboard as the PromQL panels, sharing the time range.

When: which streams to enable

  • Managed Prometheus enabled → Logs and Events.
  • Need all default views of portal Insights (node / controller / container performance pages) → Standard (officially noted that the “All” group is required for default visualizations), but this duplicates payments with Prometheus metrics.
  • High log volume → namespace exclusion, ContainerLogV2 with cheaper table plans (Basic/Auxiliary; check the official table-plan documentation for applicability), or enable high-scale mode (the stream changes to Microsoft-ContainerLogV2-HighScale, which cannot be used together with the regular ContainerLogV2 stream).

Comparison with similar technologies

Container InsightsLoki (self-managed)CloudWatch Container Insights (Lesson 4)
Query languageKQLLogQLLogs Insights query language
Indexingall columns queryable (billed by GB ingested)indexes labels onlyper GB
Correlation with metricsGrafana side-by-side panels / portal workbooksGrafana native (same labels)CloudWatch dashboards
Common misconceptions① “Container Insights is Prometheus metrics” — it is mainly logs and manifests; metrics should go to managed Prometheus. ② “namespaceFilteringMode can filter container logs” — the official description says it applies to manifests and performance data; namespace exclusion for container logs is configured through the Container Insights agent ConfigMap (container-azm-ms-agentconfig), and the exact keys follow the official documentation. ③ “If Grafana Viewers cannot see logs, it's a Grafana problem” — the Grafana managed identity needs read permission on the Log Analytics workspace.

Architecture diagram: log path and metric path run in parallel

myapp Podstdout: access logs/metrics: counters ama-logs (DaemonSet)reads /var/log/containers+ ama-logs-rs: events, manifests ama-metricsPodMonitor scrapes :5000(modules 2–3) DCR streamContainerLogV2 / KubeEvents/ KubePodInventory amw-prom-labPromQL law-prom-labKQL · billed per GB Managed GrafanaPanel A: PromQL 5xxPanel B: KQL logsshared time rangeMI: two read roles
Figure 6-1: the same Pod's data takes two paths into two workspaces, and Grafana correlates them by time and Pod

Correlation key comparison

Prometheus series (managed) cluster="aks-prom-lab"namespace="myapp"pod="myapp-6c9f8d7b9-2xk4p"timestamp: scrape moment (30s granularity) ContainerLogV2 row _ResourceId (AKS cluster resource ID)PodNamespace == "myapp"PodName == "myapp-6c9f8d7b9-2xk4p"TimeGenerated: log collection moment
Figure 6-2: match metric points and log rows using namespace/pod and a time window (column names follow the ContainerLogV2 schema)

Interactive: jump from a metric spike to logs for the same time window

The chart below shows myapp's 5xx rate (simulated data). Click any bar, and the simulator generates the KQL for the matching time window and Pod, and shows ContainerLogV2,KubeEvents sample results — this is the standard on-call move from alert to root cause.

← 1 hour ago · 2 minutes per bar · click a bar →
Click a bar.
// KQL will be displayed here

Core commands and parameters

CommandPurposeKey parameters / notes
az monitor log-analytics workspace createCreate a Log Analytics workspace-g -n -l; --retention-time
az aks enable-addons --addon monitoringEnable Container Insights (official documentation example)--workspace-resource-id,--data-collection-settings dcs.json
az aks update --enable-azure-monitor-logsnewer enablement method (appears in the CLI reference)configured through the Azure Monitor profile; cannot be used together with --enable-addons monitoring ; this lesson mainly follows enable-addons from the official how-to documentation
az aks disable-addons --addon monitoringDisableworkspace data retention
az monitor log-analytics queryRun KQL in the CLI-w is the workspace customerId (GUID), not the resource ID
source ~/promlab/azure/env.sh
az monitor log-analytics workspace create -g $RG -n $LAW -l $LOC
export LAW_ID=$(az monitor log-analytics workspace show -g $RG -n $LAW --query id -o tsv)
export LAW_GUID=$(az monitor log-analytics workspace show -g $RG -n $LAW --query customerId -o tsv)

cat > ~/promlab/azure/dcs.json <<'EOF'
{
  "interval": "1m",
  "namespaceFilteringMode": "Off",
  "enableContainerLogV2": true,
  "streams": ["Microsoft-ContainerLogV2", "Microsoft-KubeEvents", "Microsoft-KubePodInventory"]
}
EOF
az aks enable-addons --addon monitoring -g $RG -n $AKS \
  --workspace-resource-id $LAW_ID --data-collection-settings ~/promlab/azure/dcs.json
az aks show -g $RG -n $AKS --query addonProfiles.omsagent -o json
kubectl get ds ama-logs -n kube-system; kubectl get deploy ama-logs-rs -n kube-system
{
  "config": {
    "logAnalyticsWorkspaceResourceID": "/subscriptions/0000…/resourcegroups/rg-prom-lab/providers/microsoft.operationalinsights/workspaces/law-prom-lab",
    "useAADAuth": "true"
  },
  "enabled": true,
  "identity": null
}
NAME       DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR   AGE
ama-logs   2         2         2       2            2           <none>          3m
NAME          READY   UP-TO-DATE   AVAILABLE   AGE
ama-logs-rs   1/1     1            1           3m

How to verify:useAADAuth: "true" indicates managed identity authentication (the official default). Common error: Writing dcs.json 's streams as table names (ContainerLogV2) instead of stream names (Microsoft-ContainerLogV2). Production use: Set collection policies per team namespace separately; evaluate high-volume namespaces individually.

myapp:1.1: send access logs to stdout

cd ~/promlab/myapp
sed -i 's#gunicorn -w 2 -b 0.0.0.0:5000 app:app#gunicorn -w 2 -b 0.0.0.0:5000 --access-logfile - app:app#' Dockerfile
grep gunicorn Dockerfile
az acr build -r $ACR -t myapp:1.1 .
kubectl -n myapp set image deploy/myapp myapp=$ACR.azurecr.io/myapp:1.1
kubectl -n myapp rollout status deploy/myapp
kubectl -n myapp logs deploy/myapp --tail=3
10.244.1.20 - - [15/Nov/2026:10:40:12 +0000] "GET / HTTP/1.1" 200 26 "-" "curl/8.11.1"
10.244.1.20 - - [15/Nov/2026:10:40:12 +0000] "GET /error HTTP/1.1" 500 5 "-" "curl/8.11.1"
10.244.1.20 - - [15/Nov/2026:10:40:12 +0000] "GET / HTTP/1.1" 200 26 "-" "curl/8.11.1"

KQL query

az monitor log-analytics query -w $LAW_GUID -o table --analytics-query '
ContainerLogV2
| where TimeGenerated > ago(30m)
| where PodNamespace == "myapp" and ContainerName == "myapp"
| where LogMessage has "\" 500 "
| summarize errors = count() by bin(TimeGenerated, 1m), PodName
| order by TimeGenerated desc
| take 10'
TimeGenerated                 PodName                     errors
----------------------------  --------------------------  ------
2026-11-15T10:44:00Z          myapp-7f6d5c8b9-4tq2m       31
2026-11-15T10:44:00Z          myapp-7f6d5c8b9-zz8kd       29
// Pod events
KubeEvents
| where TimeGenerated > ago(1h) and Namespace == "myapp"
| project TimeGenerated, Name, Reason, Message, Count
| order by TimeGenerated desc

// latest status and restart count per Pod
KubePodInventory
| where TimeGenerated > ago(15m) and Namespace == "myapp"
| summarize arg_max(TimeGenerated, PodStatus, PodRestartCount) by Name

LogMessage For non-JSON logs it is a string; if the application outputs JSON, ContainerLogV2 treats it as a dynamic type and it can be accessed directly LogMessage.level (follow the official ContainerLogV2 schema documentation). Logs typically take several minutes from generation to being queryable.

Lab 6: log and event collection + side-by-side metrics/logs dashboard (about 7 min)

Costs and permissions: Log Analytics is billed by ingested GB (canadacentral Analytics Logs 2.76 USD/GB, retail price API 2026-11-15; includes a certain free retention period, then 0.12 USD/GB/month; follow the pricing page). In this lab, loadgen produces about 10 access-log lines per second, which is tens of MB per day. Requires Contributor on the resource group.
Enable Container Insights: run the first block on the “Commands” page and confirm ama-logs and ama-logs-rs Running.
Release myapp:1.1: run the second block,kubectl logs should show the access logs; change loadgen back to a version containing /error (module 0 step 5) to produce 5xx errors.
KQL verification: after about 5 minutes, run the KQL query and you should see 500-log-line counts per Pod; then query KubeEvents to see events at the time 1.1 was released. Pulling/Started/Killing events.
Side-by-side correlation in Grafana: give the Grafana managed identity log-read permission, then add an Azure Monitor (Logs) panel to the myapp dashboard:
AMG_MI=$(az grafana show -n $AMG -g $RG --query identity.principalId -o tsv)
az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal \
  --role "Log Analytics Reader" --scope $LAW_ID
ContainerLogV2
| where $__timeFilter(TimeGenerated)
| where PodNamespace == "myapp" and LogMessage has "\" 500 "
| summarize errors = count() by bin(TimeGenerated, 1m), PodName
| order by TimeGenerated asc
Place it below the “request rate by status” panel; the two share the dashboard time range; when you zoom into a 5xx spike, the log panel shows the error-line counts and Pods for the same time window.
Acceptance: the 5xx rate in the PromQL panel and the per-minute error-line trend in the KQL panel should agree (the numbers may differ: one is a per-second rate, the other is lines per minute).
Cleanup: keep; if you only want to stop log costs: az aks disable-addons --addon monitoring -g $RG -n $AKS.

Case 1: log costs triple in one month

Problem: The Standard preset was chosen at enablement, and managed Prometheus was also on, so Perf/InsightsMetrics duplicated Prometheus metrics; a debug-level sidecar output thousands of lines per second. Approach: Switch to the Logs and Events preset; use Usage | where TimeGenerated > ago(7d) | summarize GB=sum(Quantity)/1024 by DataType to find the top consumers; exclude logs for noisy namespaces; lower the sidecar's log level. Limitations: After exclusion, that namespace has no logs during troubleshooting, so agree on this with the team.

Case 2: one click from the alert email to the logs

Problem: On-call receives MyAppHigh5xxRatio and has to hand-build KQL. Approach: Put a Grafana dashboard link (with var-cluster parameters) in the rule annotation; on the dashboard the PromQL and KQL panels sit side by side with time ranges aligned automatically. Limitations: Annotations are static text; the time range is approximated through Grafana link parameters (such as from=now-30m).

Case 3: the evidence chain for OOMKilled

Problem:KubeContainerOOMKilledCount A recommended alert fired; the developers say “the application is fine”. Approach: Use PromQL to view the curve approaching the limit; container_memory_working_set_bytes use KQL to check restart-count changes for KubePodInventory and related events in KubeEvents ; ContainerLogV2 look at the last few log lines before the kill. With the three aligned in time, the evidence is complete. Limitations: A kernel OOM does not necessarily leave a record in container logs; rely on events and metrics.

Common errors and fixes

KQL query on ContainerLogV2 returns 0 rows (but ContainerLog has data)

Cause:enableContainerLogV2 is false, or streams contains only Microsoft-ContainerLog; or it was just enabled and the data has not arrived yet.

az monitor log-analytics query -w $LAW_GUID --analytics-query 'union withsource=T ContainerLog, ContainerLogV2 | where TimeGenerated > ago(1h) | summarize count() by T' -o table

Fix: Enable ContainerLogV2 in the data collection settings and include Microsoft-ContainerLogV2 stream; do not use the regular stream and the HighScale stream at the same time.

enable-addons error: … monitoring addon … cannot be combined / already enabled

Cause: The cluster was already enabled another way (--enable-azure-monitor-logs or the portal), and the two methods are mutually exclusive.

Fix: Disable it using the same method first, then enable as needed; keep the team on one method (fixed in IaC).

ama-logs Pod CrashLoopBackOff / OOMKilled

Cause: Node log volume is extremely large or node resources are tight.

kubectl -n kube-system describe pod -l component=ama-logs-agent | grep -A5 "Last State"
kubectl -n kube-system logs ds/ama-logs --tail=50

Fix: Evaluate high-scale mode; exclude noisy namespaces; label selectors follow the actual Pod labels.

Grafana Azure Monitor Logs panel: The user or service principal does not have access to the workspace

Cause: The Grafana managed identity has no read permission on law-prom-lab .

Fix: grant Log Analytics Reader (or Monitoring Reader), then refresh the data source.

Portal Insights page says performance data needs to be enabled

Cause: With the Logs and Events preset there is no Perf/InsightsMetrics, so some older log-based views have no data.

Fix: Switch performance views to those driven by managed Prometheus and the pre-provisioned Grafana dashboards; if the old views are truly needed, switch to the Standard preset and evaluate the cost.

Command-line tasks
1. Enable Container Insights for aks-prom-lab, collecting only ContainerLogV2 and KubeEvents, writing to law-prom-lab.
echo '{"interval":"1m","enableContainerLogV2":true,"streams":["Microsoft-ContainerLogV2","Microsoft-KubeEvents"]}' > dcs.json
az aks enable-addons --addon monitoring -g rg-prom-lab -n aks-prom-lab \
  --workspace-resource-id $(az monitor log-analytics workspace show -g rg-prom-lab -n law-prom-lab --query id -o tsv) \
  --data-collection-settings dcs.json
2. Use KQL to count ingestion (GB) per table over the last 7 days.
Usage
| where TimeGenerated > ago(7d)
| summarize GB = sum(Quantity) / 1024 by DataType
| order by GB desc
Scenario analysis
A team wants to “put everything into Log Analytics for one-stop KQL queries”, including application metrics every 30 seconds. How do you assess this?

Not recommended. Metrics billed per sample are extremely cheap in managed Prometheus (about 0.16 USD per 10 million samples), whereas writing them to Log Analytics is billed per GB (2.76 USD/GB in canadacentral), and high-frequency numeric data is amplified into many rows; PromQL's rate/histogram_quantile is also better suited to metrics. Recommendation: metrics → managed Prometheus; logs, events, manifests → Log Analytics (Logs and Events preset); correlate side by side in Grafana; when you need joint KQL analysis, export or use workbooks on a small set of aggregated results.

Verified teaching videos

▶
Azure Monitor Logs Log Types — John Savill's Technical Training
English · Log Analytics table plans (Analytics / Basic / Auxiliary) and costs, to help decide where ContainerLogV2 should be stored
▶
Azure Kubernetes Services Insights | AKS Container Insights Using Azure Log Analytics Workspace — Cloud Quick Labs
English · community demo of the portal enablement flow (the cost preset UI may have been updated)

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: one Pod emits two lines: the green /metrics line goes to the Azure Monitor workspace, and the orange stdout line goes to Log Analytics.
Narration: the same Pod's data takes two paths: metrics go to managed Prometheus, logs go to Log Analytics.
Shot 2 · 20–40s
Visual: four cost-preset cards; the “Logs and events” card lights up with the note “recommended when managed Prometheus is enabled”.
Narration: performance data goes to Prometheus; Container Insights collects only logs, events and Pod manifests, avoiding duplicate payment.
Shot 3 · 40–65s
Visual: a spike appears on the 5xx curve in Grafana; the mouse box-selects the spike, and the KQL panel below zooms in sync to show 500 log lines.
Narration: place the PromQL and KQL panels side by side on the same dashboard with matching time ranges, going directly from “when” to “why”.
Shot 4 · 65–80s
Visual: a bar chart of Usage table query results, with ContainerLogV2 the largest share.
Narration: finally, use the Usage table to regularly check who is generating log costs.
or score ≥ 70% on the quiz

Module 7 · Cloud troubleshooting in practice

45:00 – 54:00 · “Grafana has no data” may break at any of the seven hops: add-on, configuration, discovery, scraping, writing, quota, reading; rule them out in order, each hop has a fixed observation point
9 minOfficial troubleshooting script availableCase-insensitive · 422 duplicate series★★★★★
Learning goals
  • Master the seven-hop troubleshooting method, knowing which command / log / metric to check at each hop.
  • Recognize problems specific to the managed service: missing DCR/DCE, write token failures, active-series / events-per-minute quota throttling, query 403, series merging caused by case-insensitivity, duplicate series 422, queries must include __name__.
  • Use debug mode (port 9091) to see the metrics the collector actually scraped, and use the official troubleshooting script to collect a diagnostics bundle.
Prerequisites: Modules 2–6. Importance:★★★★★

What: the seven-hop model

#HopObservation pointTypical symptom
1Add-on runningkubectl get pods -n kube-system | grep ama-metrics; describe check the restart reasonPod missing / CrashLoop / OOMKilled
2Configuration processingoperator-targets of the config-reader logs (prometheus-config-merger section)custom jobs do not appear, ConfigMap rejected
3Target discoverytargetallocator logs; collector Pod :9090/service-discoveryMonitor exists but has no targets
4Scraping:9090/targets (lastError),up; debug mode :9091/metricsup=0, label limit exceeded, TLS/authentication failures
5Writingprometheus-collector and addon-token-adapter logs“No configuration present for the AKS resource”, token errors
6Workspace quotaworkspace metrics Active Time Series % Utilization,Events Per Minute Received % Utilizationpartial data missing, throttling
7Readingthe caller's role on the workspace; query semantics403, query errors, results that “merge strangely”

Why: the pitfalls specific to the managed service

  • Case-insensitivity: the workspace treats metric names / label names / label values that differ only in case as the same series; when written with the same timestamp, one is kept at random, and the case returned by queries is unpredictable; two labels in the same sample that differ only in case (such as ExampleLabel and examplelabel) are treated as duplicate labels and dropped.
  • Duplicate series return 422: for example, same-named clusters in two different resource groups writing to the same workspace with identical timestamps and values. Officially recommended: add a unique label (cluster_alias or relabel).
  • Query API limits: a time-series query must have exactly one __name__ matcher; /series does not support regex filtering, at most 12 hours; /query_range at most 32 days (including the range selector).
  • Collection gaps: during node upgrades, the node hosting the cluster-level collector is recreated, which causes a 1–2 minute gap (expected behaviour).
  • Quota: each workspace has default limits on active time series and events per minute, which can be raised with a support request; officially recommended to set alerts on quota utilization.

How: troubleshooting order

Always work from the data source downstream (1 → 7), reaching a yes/no conclusion at each hop before moving on; do not start by changing Grafana. For “partial data missing”, first check hop 6 (quota) and the keep list of minimal ingestion; for “all data missing”, first check hops 1 and 5.

When: when to use debug mode and the troubleshooting script

  • target up=1 but a metric cannot be queried → turn on debug mode (settings ConfigMap debug-mode of the enabled = true), in :9091/metrics view the data the collector actually received, and confirm whether it was dropped by relabel/keep list or during ingestion. Debug mode affects performance; enable it only briefly.
  • Failure at the enablement stage, or you need to open a support ticket → run the official troubleshooting PowerShell script on GitHub and attach the generated files.

Comparison with self-managed Prometheus troubleshooting

QuestionSelf-managed (Lessons 1–2)Managed (this lesson)
Check targetsPrometheus /targetsthe collector Pod's :9090/targets (agent-mode UI)
Check configuration/config,promtool:9090/config,promconfigvalidator, config-reader logs
Storage problemsDisk full, WAL corruptionQuota throttling, missing DCR/DCE
Query permissionsusually noneMonitoring Data Reader
Common misconceptions① “No data in Grafana = Grafana has a problem” — among the seven hops, only hop 7 is on the Grafana side. ② “up=1 means all metrics made it in” — minimal-ingestion keep lists, metricRelabelings, label limits and quotas can all drop data after up=1. ③ “Restarting ama-metrics fixes everything” — a restart only helps when configuration failed to load; it does not fix RBAC, DCR or quota problems.

Seven-hop troubleshooting diagram

1 add-onget podsdescribe 2 configurationconfig-readervalidator 3 discoverytargetallocator/service-discovery 4 scrape/targets · updebug :9091 5 writecollector logstoken-adapter 6 quota% Utilizationworkspace metrics 7 readRBAC · query semantics403 / 422 In-cluster (visible via kubectl)Hops 1–5: Pods in kube-system, logs, 9090/9091 UIsPermission: cluster user is enough Azure side (visible via az / portal)Hops 5–7: DCR/DCE, workspace metrics, role assignments, rule group healthPermission: Monitoring Reader / Data Reader
Figure 7-1: rule out hop by hop from left to right; hop 5 spans both the cluster and Azure sides

Symptom → most likely hop

Nothing at all (including kubelet)→ 1 / 5 Default metrics present, myapp missing→ 2 / 3 / 4 up=1, but a metric is missing→ 4 (keep list) / 6 Intermittent data gaps→ 6 / node-upgrade gap API/Grafana 403→ 7 (RBAC) Two series “merged” into one→ 7 (case-insensitivity) Write 422→ 5/7 (duplicate series) Data is all there, rule does not fire→ rule group scope / clusterName
Figure 7-2: first locate the possible hop from the symptom, then confirm with observation points

Fault injection game: which hop broke?

Click “Next question”; the simulator injects a real fault at random and gives you the symptom and log snippet you would see on call. Click the hop you think is broken, then see the explanation and fix commands. Answer 5 in a row correctly to clear the game.

Score 0 / 0
Click “Next question”.
// Symptoms and log snippet

Troubleshooting command quick reference (by hop)

HopCommandWhat to look at
1kubectl get pods -n kube-system | grep ama-metricsRunning; restart count = number of times the ConfigMap was applied
2kubectl logs <operator-targets> -n kube-system -c config-readerParse / merge / validation errors
3kubectl logs <operator-targets> -n kube-system -c targetallocatorWhether the Monitor is recognized; Secret permissions
4kubectl port-forward <ama-metrics pod> -n kube-system 9090/targets lastError,/service-discovery
5kubectl logs <ama-metrics pod> -n kube-system -c prometheus-collector / -c addon-token-adapterauthentication, DCR configuration, MetricsExtension errors
6az monitor metrics list --resource $AMW_ID --metric …Active series and events-per-minute utilization
7az role assignment list --scope $AMW_IDWhether the caller has Monitoring Data Reader
source ~/promlab/azure/env.sh
AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
# Hop 1
kubectl get pods -n kube-system | grep ama-metrics
# Hops 2–3
TA=$(kubectl get pods -n kube-system -o name | grep ama-metrics-operator-targets | head -1)
kubectl logs -n kube-system $TA -c config-reader --tail=40
kubectl logs -n kube-system $TA -c targetallocator --tail=40 | grep -i -E 'error|forbidden|monitor'
# Hop 5
RS=$(kubectl get pods -n kube-system -l rsName=ama-metrics -o name | head -1)
kubectl logs -n kube-system $RS -c prometheus-collector --tail=40 | grep -i -E 'error|No configuration|throttl'
kubectl logs -n kube-system $RS -c addon-token-adapter --tail=20
# Hop 6: workspace utilization metrics (names follow the output of az monitor metrics list-definitions)
az monitor metrics list-definitions --resource $AMW_ID --query "[].name.value" -o tsv
# Hop 7
az role assignment list --scope $AMW_ID --query "[].{who:principalName,type:principalType,role:roleDefinitionName}" -o table
ActiveTimeSeriesPercentUtilization
EventsPerMinuteIngestedPercentUtilization
…
Who                     Type              Role
----------------------  ----------------  ----------------------
                        ServicePrincipal  Monitoring Data Reader
you@example.com         User              Monitoring Data Reader

The metric display names listed in the official documentation in the portal are Active Time Series % Utilization and Events Per Minute Ingested/Received % Utilization; the internal names in the CLI follow the list-definitions actual output; the output above is an example.

Debug mode

# In debug-mode of ama-metrics-settings-configmap, set enabled to true (official: use briefly); after apply, wait for the Pods to restart
kubectl port-forward -n kube-system $RS 9091 &
curl -s localhost:9091/metrics | grep -c '^myapp_'
curl -s localhost:9091/metrics | grep '^myapp_redis_up'
kill %1
# When finished, set it back to false

Official troubleshooting script

# See https://github.com/Azure/prometheus-collector/tree/main/internal/scripts/troubleshoot
# Download per the README and run in PowerShell 7+; the generated diagnostic files can be attached to the support ticket

Lab 7: reproduce, diagnose and fix five faults (about 9 min)

Each fault is reversible in the lab environment. Restore after each one before doing the next. Cost: no extra resources.

Fault A: wrong API group (hop 3)
kubectl get podmonitor.azmonitoring.coreos.com myapp -n myapp -o yaml \
 | sed 's#azmonitoring.coreos.com/v1#monitoring.coreos.com/v1#' > /tmp/pm-bad.yaml
kubectl apply -f /tmp/pm-bad.yaml
error: resource mapping not found for name: "myapp" namespace: "myapp" from "/tmp/pm-bad.yaml": no matches for kind "PodMonitor" in version "monitoring.coreos.com/v1"
ensure CRDs are installed first

Diagnosis: the error points directly to the version. If the cluster has open-source CRDs installed, apply succeeds but the target does not appear — this is more subtle. Fix: use azmonitoring.coreos.com/v1.

Fault B: port name mismatch (hops 3/4)
kubectl patch podmonitor.azmonitoring.coreos.com myapp -n myapp --type json \
  -p '[{"op":"replace","path":"/spec/podMetricsEndpoints/0/port","value":"metrics"}]'
# After 2–3 minutes: up{namespace="myapp"} disappears in the workspace; myapp is not in :9090/targets
kubectl patch podmonitor.azmonitoring.coreos.com myapp -n myapp --type json \
  -p '[{"op":"replace","path":"/spec/podMetricsEndpoints/0/port","value":"http"}]'

Diagnosis: /service-discovery shows the Pod was discovered but dropped (port name mismatch). The module 5 MyAppPodsMissing alert will fire after 3 minutes — this is the value of alerts covering scrape configuration errors.

Fault C: Grafana read permission removed (hop 7)
AMG_MI=$(az grafana show -n $AMG -g $RG --query identity.principalId -o tsv)
az role assignment delete --assignee $AMG_MI --role "Monitoring Data Reader" --scope $AMW_ID
# Refresh the Grafana panel → permission error; meanwhile your curl query still works (different identity)
az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal --role "Monitoring Data Reader" --scope $AMW_ID
Fault D: cluster_alias inconsistent with the rule group clusterName (rule does not fire)
# Set cluster_alias = "akspromlab" in prometheus-collector-settings of the settings ConfigMap, then apply
# The cluster label of new data becomes akspromlab; the rule group clusterName is still aks-prom-lab → alerts no longer evaluate the new data
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode 'query=count by (cluster) (up)' "$PROM_QUERY/api/v1/query" | jq -c '.data.result[] | [.metric.cluster, .value[1]]'
# Choose one fix: change cluster_alias back to ""; or
az alerts-management prometheus-rule-group update -n myapp-rules -g $RG --cluster-name akspromlab

Note cluster_alias Only alphanumerics are allowed; other characters are replaced with underscores. After changing the alias, historical data keeps the old label, and the dashboard $cluster variable will show two values.

Fault E: case-insensitivity (hop 7, proof of concept)
# Construct two series that differ only in case (using a temporary static target):
kubectl -n myapp create configmap casing --from-literal=metrics='demo_metric{Env="Prod"} 1
demo_metric{Env="prod"} 2
'
# Think about it: after a ConfigMap custom job scrapes a static HTTP endpoint that returns the content above, how many demo_metric series are in the workspace?
# Answer: 1 series (treated as the same series; one value is kept at random, and the returned case is unpredictable).
kubectl -n myapp delete configmap casing

In the lab you do not actually have to deploy the endpoint; the key is to understand: in a managed workspace, label-value case cannot be used as a distinguishing dimension; normalize to lowercase on the application side.

Acceptance: you can state for all five faults “which hop broke, what was checked, how to fix it”; the environment is restored (up{namespace="myapp"} = 2, Grafana works normally, and the rule group clusterName matches the data).

Case 1: partial metrics missing on Monday morning

Problem: Before a big promotion, metrics with user_id labels were released; from Monday some dashboards had gaps. Approach: Workspace metrics show active time series utilization stuck at 100% (hop 6); use count by (__name__) ({__name__=~"shop_.*"}) to find the metrics that exploded; in the PodMonitor, labeldrop remove user_id, and file a quota increase request at the same time (with the workspace ID, internal ID and region). Limitations: Raising the quota is not the right way to solve cardinality problems; it only buys time. Lesson 7 covers cardinality governance in detail.

Case 2: private cluster has no data after enabling

Problem:prometheus-collector Printed “No configuration present for the AKS resource” every 5 minutes; the Pod restarted every 15 minutes. Approach: Followed the three official checks: DCR/DCE exists, the workspace exists, and the private cluster is not linked to another service's AMPLS; found that the network team had added the cluster to a log-dedicated AMPLS. Recovered after adjusting the Private Link design. Limitations: For private network scenarios, always read the official Private Link documentation before going live.

Case 3: test and production data “fighting”

Problem: Test and production clusters both named aks-app (in different resource groups) shared one workspace; occasional 422 write errors and jagged charts. Approach: Set cluster_alias = "aksappprod"/"aksapptest" on each side, and update the rule group clusterName simultaneously; filter dashboards by the new label. Limitations: The better practice is to use separate workspaces for production and test (permissions and costs can then also be separated).

Common errors and fixes

No configuration present for the AKS resource

Cause: Missing DCR/DCE/workspace or a lost association; an unsupported combination of private cluster + AMPLS.

Fix: confirm the resources exist; --disable-azure-monitor-metrics then re-enable; adjust per the official Private Link documentation.

ama-metrics Pod restarts far exceed the number of ConfigMap changes, Reason: OOMKilled

Cause: Ingestion volume exceeds the memory capacity of the collector.

kubectl describe pod -n kube-system $RS | grep -A4 "Last State"

Fix: Refer to the official “high-scale” and “collector replica HPA” documentation; reduce targets and metrics; push node-level jobs down to the DaemonSet.

422 Unprocessable Entity (duplicate time series)

Cause: Two sources produced series with identical labels (same-named clusters writing to the same workspace, or the add-on and remote_write both writing the same cluster).

Fix: add unique labels (cluster_alias, relabel injection), or keep only one write path.

Query error: query must contain a metric name matcher (or similar message)

Cause: The managed API requires each time-series query to include exactly one __name__ matcher, for example {namespace="myapp"} a bare selector like this is not accepted.

Fix: write it as {__name__=~"myapp_.*", namespace="myapp"} or specify the exact metric name.

myapp is up in /targets, but myapp_redis_up cannot be found in the workspace

Cause: The Monitor's metricRelabelings keep regex is wrong (for example myapp_http.*), or the application did not emit that metric at that moment (in multi-process mode a Gauge only has a value in the workers that have called /metrics it).

kubectl get podmonitor.azmonitoring.coreos.com myapp -n myapp -o jsonpath='{.spec.podMetricsEndpoints[0].metricRelabelings}'

Fix: correct the regex; use debug mode :9091/metrics to confirm what the collector received.

Command-line tasks
1. View the container logs in the collector replicas that handle write authentication.
RS=$(kubectl get pods -n kube-system -l rsName=ama-metrics -o name | head -1)
kubectl logs -n kube-system $RS -c addon-token-adapter --tail=50
2. Find out how many up series each cluster currently has in the workspace (to identify cluster label conflicts).
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode 'query=count by (cluster) (up)' "$PROM_QUERY/api/v1/query" | jq -c '.data.result[] | [.metric.cluster, .value[1]]'
Scenario analysis
On-call receives “the whole myapp dashboard in Grafana is blank”. The preset kubelet/cAdvisor dashboards are also blank, but your colleague's curl query returns data normally. Where is the most likely break? How do you confirm?

Data writing is normal (the colleague can query it); the problem is in the read identity on the hop 7 Grafana side: the Grafana managed identity lost Monitoring Data Reader, the system-assigned managed identity was turned off or replaced, or the data source URL was changed. Confirm: az grafana show --query identity; az role assignment list --scope $AMW_ID --assignee <MI>; click “Save & test” on the Grafana data source page. Refresh after fixing. If your colleague can't query either, go back to hops 1/5.

Verified teaching videos

▶
AKS Labs: Observability with Managed Prometheus and Managed Grafana — Microsoft Reactor
English · Reactor live-stream lab, including the on-site troubleshooting process
▶
Kubernetes on Azure series 6/10: AKS observability: Azure Monitor, Container Insights, … — multicloud architect
English · community video series, overview of AKS observability (details follow this lesson's verification)

Official documentation

Video storyboard (about 90 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: seven boxes in a row from “add-on” to “read”, with the blank Grafana panel flashing at the far right.
Narration: Grafana has no data — the problem could be at any of the seven hops. Always check from left to right.
Shot 2 · 20–45s
Visual: split terminal; the config-reader logs, targets page and collector logs are highlighted in turn.
Narration: the first five hops are inside the cluster, visible with kubectl: whether the configuration was accepted, whether targets were discovered, and whether scraping and writing reported errors.
Shot 3 · 45–70s
Visual: the workspace metrics chart, with active time series utilization climbing all the way to one hundred percent.
Narration: when data is partly missing, check the workspace quota first. High-cardinality labels are often the culprit.
Shot 4 · 70–90s
Visual: two labels, Prod and prod, merge into one, with “case-insensitive” written beside it.
Narration: finally, remember two managed-service traits: case-insensitivity, and queries must include a metric name.
or score ≥ 70% on the quiz

Module 8 · Cost, cleanup and self-test

54:00 – 60:00 · the bill for the managed service is determined by four metering items: ingested samples, queried samples, log GB, and Grafana instances and users; after finishing, delete the resources completely, including the ones that are “created automatically”
6 minRetail Prices API · canadacentral · USDConfirm before deleting★★★★
Learning goals
  • Name the billing units for managed Prometheus, Log Analytics, Managed Grafana and AKS, and estimate the monthly ingestion cost using “number of series × collection frequency”.
  • Master five cost-reduction measures: minimal ingestion + keep list, lower collection frequency, metricRelabelings to drop high-cardinality series, log presets and namespace exclusion, and dashboard refresh and time-range control.
  • List the least privileges used in this lesson, and clean up completely in order (including the managed resource groups, default workspace, node resource group, kubeconfig context and Entra role assignments).
Prerequisites: Modules 1–7. Importance:★★★★ (the most common “accident” in lab accounts is forgetting to delete resources)

What: metering items (canadacentral, retail prices API queried 2026-11-15, USD, for estimation only)

ServiceMetering itemUnit price (retail prices API)Cost driver
Azure Monitor managed PrometheusMetrics ingestion (ingested samples)0.16 / 10 million samplesActive series × collection frequency
Prometheus Metrics Queries (query-processed samples)0.001 / 10 million samplesDashboard refresh, rule evaluation, API queries
Log AnalyticsAnalytics Logs Data Ingestion2.76 / GB (a free-allowance row exists); retention 0.12 / GB / month (after the free retention period)Log rows and size
Managed Grafana StandardStandard Node0.04104 / hourInstance running time (the number of billed nodes per instance follows the pricing page)
Standard User6 / active user / monthUsers who signed in during the month
Standard Zone Redundancy0.04932 / hourWhen zone redundancy is enabled
AKS nodesStandard_D2s_v5 (Linux pay-as-you-go)0.107 / hour / nodeNumber of nodes × duration; the Free tier control plane is not charged
Azure Monitor alert notificationsEmails0.00002 / message after the free allowanceNumber of notifications

Note: the retail prices API also shows new metering items since 2026-10, such as “Metric Samples Ingested 0.11 / 10 million” and “Metric Samples Processed 0.05 / 10 million”; their correspondence with managed Prometheus could not be confirmed on the pricing page, so this lesson estimates with “Metrics ingestion / Prometheus Metrics Queries”; please refer to the Azure Monitor pricing page and the Managed Grafana pricing page as authoritative.

Why: where the money goes

Ingested samples = Σ (each active series × collections per minute). Example: 3,000 series, 30-second collection → per month 3,000 × 2 × 60 × 24 × 30 ≈ 259 million samples ≈ 4.15 USD. The same series at 60-second collection halves the cost; ten times the series (high-cardinality labels) multiplies the cost by ten. By comparison, logs can easily become the biggest item: 1 GB of access logs per day ≈ 83 USD per month.

How: five cost-reduction measures

  1. Keep minimal ingestion: add only the metrics you need via the keep list, and do not turn off minimal-ingestion-profile.
  2. Adjust frequency: default-targets-scrape-interval-settings and the Monitor's interval; non-critical targets 60s.
  3. Drop high cardinality: metricRelabelings of drop/labeldrop; keep only the histogram buckets you need.
  4. Logs: Logs and Events preset, namespace exclusion, lower application log levels, evaluate Basic/Auxiliary table plans.
  5. Queries: dashboard refresh interval ≥ 1m, default time range not too long, use recording rules to pre-aggregate for large panels.

When: when and how to delete

  • Delete the resource group immediately after the lab rg-prom-lab: AKS, ACR, workspace, Grafana, Log Analytics, rule groups and Action Groups within it are all deleted together.
  • Then check the automatically created resources: MC_rg-prom-lab_aks-prom-lab_canadacentral (node resource group, deleted with AKS),MA_amw-prom-lab_canadacentral_managed (the workspace's DCR/DCE),DefaultRG-*/DefaultAzureMonitorWorkspace-*/DefaultWorkspace-* (if enabled without specifying a workspace).
  • After a Log Analytics workspace is deleted it enters a soft-delete period (recoverable); to reuse the same name immediately, use --force permanent deletion (follow the official docs).

Least-privilege overview

OperationMinimum role (scope)
Create AKS / workspace / Grafana / Log AnalyticsContributor (resource group)
Link Grafana during enablement (roles assigned automatically)Owner, or Contributor + User Access Administrator
Create rule groupsMonitoring Contributor (resource group)
View monitoring data (portal)Monitoring Reader / Monitoring Contributor
PromQL reads of the workspaceMonitoring Data Reader (workspace)
Access the Grafana UIGrafana Viewer / Editor / Admin (Grafana instance)
Assign Grafana roles to othersRole Based Access Control Administrator / User Access Administrator / Owner
Common misconceptions① “Stopping AKS means no charges” — stopping stops node compute charges, but Grafana, retained Log Analytics data, disks, public IPs and so on can still incur charges. ② “Deleting AKS removes the monitoring resources too” — the workspace, Grafana, rule groups and Action Groups are independent resources. ③ “The default workspace is free” — it is billed by usage like any other workspace; only its name is different.

Cost composition diagram

Ingested samplesseries count × frequency0.16 / 10M Queried samplesdashboards / rules / API0.001 / 10M Log GBContainerLogV2 etc.2.76 / GB GrafanaInstance hours + active users0.04104/h · 6/user/month Cost levers Minimal ingestion · keep listlabeldrop · 60s collection Refresh ≥ 1m · recording ruleSplit rule groups by cluster Logs and Events presetNamespace exclusion · table plans Shared instance · group authorizationEvaluate the portal built-in views
Figure 8-1: the four metering items and their corresponding cost levers

Cleanup order diagram

① Export what you want to keepdashboard backup, rule JSON ② disable rule groupsto avoid false alerts during deletion ③ az group deleterg-prom-lab ④ check for leftoversMA_* · MC_* · Default* ⑤ local cleanupkubeconfig · role assignments The rule group / Action Group / workspace are all in rg-prom-lab and will be deleted with the resource group; automatically created resource groups must be checked separately
Figure 8-2: five cleanup steps

Cost calculator (estimated with the unit prices on this page; for order-of-magnitude reference only)

Adjust the parameters; the calculator computes ingested samples as “series count × collections per minute × minutes”, and gives each monthly cost and the largest item. Unit prices come from the retail prices API (canadacentral, 2026-11-15); actual figures follow the pricing page and your bill.

Active time series: 3000
Collection interval (seconds):
Queried samples per month (hundreds of millions): 20
Log GB/day: 0.1
Grafana active users: 1
Grafana billed nodes (follow the pricing page):
AKS nodes (D2s_v5): 2
Running hours/month: 730

Cost and cleanup commands

CommandPurposeNotes
curl prices.azure.com/api/retail/prices?$filter=…Query retail unit pricesPublic API, no sign-in required
az consumption usage list / portal cost analysisView actual spendFilter by resource group rg-prom-lab
az alerts-management prometheus-rule-group update --enabled falseDisable rules before deletingAvoid false alerts
az group delete -n rg-prom-lab --yesDelete all lab resourcesNot recoverable (except LAW soft delete)
az group list --query "[?starts_with(name,'MA_')…]"Check for managed / default resource group leftoversDelete after confirming
kubectl config delete-context aks-prom-labClean up the local kubeconfigAlso remove the cluster/user entries
# Query the unit prices used in this lesson (canadacentral)
curl -s "https://prices.azure.com/api/retail/prices?\$filter=armRegionName%20eq%20'canadacentral'%20and%20serviceName%20eq%20'Azure%20Monitor'" \
 | jq -r '.Items[] | select(.meterName|test("Metrics ingestion|Prometheus")) | "\(.meterName)\t\(.unitOfMeasure)\t\(.retailPrice)"'
curl -s "https://prices.azure.com/api/retail/prices?\$filter=armRegionName%20eq%20'canadacentral'%20and%20contains(productName,'Grafana')" \
 | jq -r '.Items[] | "\(.meterName)\t\(.unitOfMeasure)\t\(.retailPrice)"'
Prometheus Metrics Queries Metric samples	10M	0.001
Metrics ingestion Metric samples	10M	0.16
Standard User	1/Month	6
Standard Node	1/Hour	0.04104
Essential User	1/Month	6
Standard Zone Redundancy	1/Hour	0.04932

Estimate your own ingestion with PromQL

// Active series per job (run in Grafana Explore)
count by (job) ({__name__=~".+", cluster="aks-prom-lab"})
// Scraped samples (per scrape)
sum by (job) (scrape_samples_post_metric_relabeling{cluster="aks-prom-lab"})

Note that the first query itself scans a large number of samples (which incurs query cost), so run it only when needed; scrape_samples_post_metric_relabeling whether a series is collected depends on the minimal ingestion configuration; if the query returns nothing, use the workspace's “Active Time Series” metric instead.

Complete cleanup

source ~/promlab/azure/env.sh
# ① Export what needs to be kept
az grafana backup -n $AMG -g $RG -d ~/promlab/azure/grafana-backup --components dashboards folders || true
# ② Disable rule groups (including those created by recommended alerts)
for id in $(az resource list -g $RG --resource-type Microsoft.AlertsManagement/prometheusRuleGroups --query "[].id" -o tsv); do
  az resource update --ids $id --set properties.enabled=false -o none
done
# ③ Delete the resource group (AKS, ACR, workspace, Grafana, LAW, rule groups, Action Groups)
az group delete -n $RG --yes
# ④ Check for leftovers
az group list --query "[?starts_with(name,'MA_amw-prom-lab') || starts_with(name,'MC_rg-prom-lab') || starts_with(name,'DefaultRG')].name" -o tsv
az monitor account list --query "[?starts_with(name,'DefaultAzureMonitorWorkspace')].{name:name,rg:resourceGroup}" -o table
az resource list --resource-type Microsoft.AlertsManagement/prometheusRuleGroups --query "[?contains(name,'aks-prom-lab')].{name:name,rg:resourceGroup}" -o table
# ⑤ Local and identity
kubectl config delete-context $AKS 2>/dev/null; kubectl config delete-cluster $AKS 2>/dev/null
az role assignment list --all --query "[?principalName==''].{id:id,role:roleDefinitionName,scope:scope}" -o table   # orphaned role assignments (principal deleted)
(no output)
(no output)
(no output)

Common errors: Deleting a resource group takes several minutes; running the command again during this period reports that deletion is in progress; the managed resource group MA_* can be deleted separately if it remains and you have confirmed the workspace is gone. The query conditions for orphaned role assignments are a common pattern; results follow the actual output, so confirm each one before deleting.

Lab 8: estimate this lab's cost and clean up completely (about 5 min + waiting for deletion)

Calculate: on the “Animation” page, click “Load the 3-hour lab preset”, and record the total and the largest item (usually AKS nodes, then Grafana).
Reconcile: in the portal Cost Management → Cost analysis, by resource group rg-prom-lab filter (cost data usually lags by several hours).
Export and disable: run ① and ② from the “Commands” page.
Delete: run ③ and wait for it to finish (about 5–15 minutes).
Check for leftovers: run ④; all three queries should return no output. If “one-click enable” in the portal created DefaultRG-canadacentral, delete it after confirming that no other cluster uses it.
Local cleanup: run ⑤; ~/promlab/azure keep the YAML/JSON in the local folder so it can be reused in Lesson 6.
Self-test: complete the “Quiz” page and the capstone lab(rebuild it if needed).

Case 1: Prometheus ingestion spikes 8× on the monthly bill

Problem: A team temporarily turned off minimal ingestion for troubleshooting and forgot to restore it. Approach: Enable the workspace ingestion-utilization recommended alert; put the settings ConfigMap under GitOps so that changes require review; the platform audits it with Azure Policy. Limitations: Samples already ingested before the configuration is restored are still billed by volume.

Case 2: Grafana user costs

Problem: Everyone was granted Grafana Viewer, and the number of monthly active users fluctuates widely. Approach: Grant access to Entra groups as needed; non-on-call staff view through reports exported on a schedule (Standard supports reporting/rendering); evaluate whether the built-in portal Grafana views meet read-only needs. Limitations: Billing is by “active users”; users who have not signed in are not billed (follow the pricing page).

Case 3: zombie resources in a lab subscription

Problem: One month after a training session, the subscription still had 12 DefaultAzureMonitorWorkspace-* and several Grafana instances. Approach: Labs uniformly use resource groups with an expiry tag (--tags expires=2026-11-30), and a nightly script deletes expired resource groups and checks Default* and MA_* for leftovers. Limitations: A default workspace may be shared with production clusters, so before automatic deletion you must check the associated clusters.

Interactive troubleshooting decision tree (covers the whole lesson)

Start from the symptom and answer the questions step by step to reach the diagnosis and fix commands.

Cleanup and cost-related errors

az group delete hangs or fails: … is locked / ScopeLocked

Cause: The resource group or a resource has a delete lock (added by organization policy or manually).

az lock list -g $RG -o table

Fix: Have someone with permission remove the lock and retry; do not casually delete other people's locks in a shared environment.

Recreating a Log Analytics workspace with the same name after deletion fails / the data “comes back to life”

Cause: The workspace is in its soft-delete period, and creating one with the same name restores the old workspace.

Fix: When you need a brand-new workspace, use az monitor log-analytics workspace delete --force true (permanent deletion, follow the official docs) when deleting, or rename it.

The bill still shows Azure Monitor ingestion charges, but rg-prom-lab has been deleted

Cause: Another cluster is still writing to the default workspace or another workspace; or the charges were incurred before deletion and are posted with a delay.

az monitor account list -o table
az aks list --query "[?azureMonitorProfile.metrics.enabled].{name:name,rg:resourceGroup}" -o table

Fix: Locate and turn off unneeded add-ons, and delete unused workspaces.

Command-line tasks
1. Delete the entire lab environment with one command (without waiting for prompts).
az group delete -n rg-prom-lab --yes --no-wait
2. List the AKS clusters in the subscription that still have managed Prometheus enabled.
az aks list --query "[?azureMonitorProfile.metrics.enabled].{name:name,rg:resourceGroup}" -o table
Scenario analysis
A 40-node cluster has managed Prometheus enabled, with about 150,000 active series at 30-second collection. Finance asks “how much per month, and how can it be reduced?” How do you answer?

Ingestion: 150,000 × 2 × 60 × 24 × 30 ≈ 12.96 billion samples ≈ 1,296 × 0.16 ≈ 207 USD/month (at this lesson's unit prices). Query costs are usually far lower than ingestion (0.001 per 10 million samples). Cost reduction: ① confirm minimal ingestion remains on and review the keep list; ② use count by (__name__) to find the top 10 metrics, drop unused histogram buckets and high-cardinality labels; ③ change non-critical targets to 60s (halves the cost directly); ④ use the Logs and Events preset for logs; ⑤ control active users with group-based Grafana authorization. Final figures follow the pricing page and cost analysis.

Verified teaching videos

▶
Azure Master Class v2 - Module 10 - Monitoring & Security — John Savill's Technical Training
English · the Azure Monitor billing and data types section can serve as background for this module

No verified video specifically covering “managed Prometheus + Managed Grafana costs and cleanup” was found; please use the storyboard below.

Official documentation

Video storyboard (about 80 seconds)

This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.

Shot 1 · 0–20s
Visual: four coin piles: ingested samples, queried samples, log GB, Grafana; the ingestion pile grows taller as the “series count” slider moves.
Narration: the bill for managed monitoring has four items; ingestion equals the number of series multiplied by the collection frequency.
Shot 2 · 20–45s
Visual: calculator animation: 3,000 series at a 30-second collection gives about four dollars; 1 GB of logs per day gives about eighty dollars.
Narration: metrics are usually cheap, while logs can easily become the biggest item.
Shot 3 · 45–65s
Visual: five cost levers light up in turn: minimal ingestion, 60-second collection, dropping high-cardinality labels, log presets, dashboard refresh interval.
Narration: five levers; start with minimal ingestion and high-cardinality labels.
Shot 4 · 65–80s
Visual: the terminal runs az group delete, and then the three leftover-check commands return no output.
Narration: finally, delete the resource group, then check the managed resource groups and the default workspace, and confirm that nothing is left.
or score ≥ 70% on the quiz

Command cheat sheet

Azure Monitor managed Prometheus · Managed Grafana · rule groups · Container Insights — every code block can be copied with one click
After-class referenceVerified 2026-11-15

Variables and prerequisites

export RG=rg-prom-lab LOC=canadacentral AKS=aks-prom-lab AMW=amw-prom-lab
export AMG=amg-prom-lab-$SUFFIX LAW=law-prom-lab AG=ag-prom-lab
for p in Microsoft.ContainerService Microsoft.Insights Microsoft.AlertsManagement \
         Microsoft.Monitor Microsoft.Dashboard Microsoft.OperationalInsights; do
  az provider register --namespace $p; done
az extension remove --name aks-preview 2>/dev/null   # required by official documentation

Workspace and enablement

az monitor account create -n $AMW -g $RG -l $LOC
AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
az aks update -g $RG -n $AKS --enable-azure-monitor-metrics \
  --azure-monitor-workspace-resource-id $AMW_ID [--grafana-resource-id $AMG_ID] \
  [--ksm-metric-labels-allow-list "pods=[app]"]
az aks update -g $RG -n $AKS --enable-control-plane-metrics
az aks update -g $RG -n $AKS --disable-azure-monitor-metrics
kubectl get pods -n kube-system | grep ama-metrics

Scrape configuration

apiVersion: azmonitoring.coreos.com/v1
kind: PodMonitor            # or ServiceMonitor (endpoints:)
metadata: { name: myapp, namespace: myapp }
spec:
  labelLimit: 63
  labelNameLengthLimit: 511
  labelValueLengthLimit: 1023
  selector: { matchLabels: { app: myapp } }
  podMetricsEndpoints: [{ port: http, path: /metrics, interval: 30s }]
# ConfigMap custom jobs (kube-system, key prometheus-config):
#   kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system
# Settings: ama-metrics-settings-configmap (schema v2, template aka.ms/azureprometheus-addon-settings-configmap)

Query the workspace

EP=$(az monitor account show -n $AMW -g $RG --query metrics.prometheusQueryEndpoint -o tsv)
az role assignment create --assignee-object-id $(az ad signed-in-user show --query id -o tsv) \
  --assignee-principal-type User --role "Monitoring Data Reader" --scope $AMW_ID
TOKEN=$(az account get-access-token --resource https://prometheus.monitor.azure.com --query accessToken -o tsv)
curl -s -H "Authorization: Bearer $TOKEN" --data-urlencode 'query=up{namespace="myapp"}' "$EP/api/v1/query"
# Limits: must include a __name__ matcher; query_range ≤ 32 days; series ≤ 12 hours; case-insensitive

Managed Grafana

az grafana create -n $AMG -g $RG -l $LOC --sku-tier Standard
AMG_ID=$(az grafana show -n $AMG -g $RG --query id -o tsv)
AMG_MI=$(az grafana show -n $AMG -g $RG --query identity.principalId -o tsv)
az grafana integration monitor add -g $RG -n $AMG --monitor-rg-name $RG --monitor-name $AMW   # preview
az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal \
  --role "Monitoring Data Reader" --scope $AMW_ID
az role assignment create --assignee user@contoso.com --role "Grafana Viewer" --scope $AMG_ID
az grafana dashboard import -n $AMG -g $RG --definition @dash.json --folder myapp --overwrite true
az grafana backup -n $AMG -g $RG -d ./bak --components dashboards folders datasources

Rule groups and Action Groups

az monitor action-group create -g $RG -n $AG --short-name promlab \
  --action email oncall you@example.com usecommonalertschema
AG_ID=$(az monitor action-group show -g $RG -n $AG --query id -o tsv)
az alerts-management prometheus-rule-group create -n myapp-rules -g $RG -l $LOC \
  --enabled --interval PT1M --scopes $AMW_ID $AKS_ID --cluster-name $AKS \
  --rules @myapp-rules.rendered.json
az alerts-management prometheus-rule-group update -n myapp-rules -g $RG --enabled false
# Rule fields: record|alert, expression, for: PT5M, severity: 0-4,
#   resolveConfiguration: {autoResolved, timeToResolve}, actions: [{actionGroupId}]

Container Insights

az monitor log-analytics workspace create -g $RG -n $LAW -l $LOC
LAW_ID=$(az monitor log-analytics workspace show -g $RG -n $LAW --query id -o tsv)
echo '{"interval":"1m","enableContainerLogV2":true,"streams":["Microsoft-ContainerLogV2","Microsoft-KubeEvents","Microsoft-KubePodInventory"]}' > dcs.json
az aks enable-addons --addon monitoring -g $RG -n $AKS --workspace-resource-id $LAW_ID --data-collection-settings dcs.json
kubectl get ds ama-logs -n kube-system; kubectl get deploy ama-logs-rs -n kube-system
az monitor log-analytics query -w $(az monitor log-analytics workspace show -g $RG -n $LAW --query customerId -o tsv) \
  --analytics-query 'ContainerLogV2 | where PodNamespace=="myapp" | take 5' -o table

Troubleshooting (seven hops)

kubectl get pods -n kube-system | grep ama-metrics                       # 1
TA=$(kubectl get pods -n kube-system -o name | grep ama-metrics-operator-targets | head -1)
kubectl logs -n kube-system $TA -c config-reader                        # 2
kubectl logs -n kube-system $TA -c targetallocator                      # 3
RS=$(kubectl get pods -n kube-system -l rsName=ama-metrics -o name | head -1)
kubectl port-forward -n kube-system $RS 9090   # /config /service-discovery /targets  4
kubectl logs -n kube-system $RS -c prometheus-collector                 # 5
kubectl logs -n kube-system $RS -c addon-token-adapter                  # 5
# 6: workspace metrics Active Time Series % / Events Per Minute % Utilization
az role assignment list --scope $AMW_ID -o table                        # 7

Quick troubleshooting table

SymptomMost likely causeFirst command
Nothing at allAdd-on not running / DCR/DCE missingkubectl get pods -n kube-system | grep ama-metrics
myapp missing, default metrics presentWrong API group, unnamed port, selector mismatchkubectl get podmonitors.azmonitoring.coreos.com -A
up=1 but a metric is missingMinimal ingestion keep list / metricRelabelingsdebug mode :9091/metrics
Intermittent data gapsQuota throttling / node-upgrade gapWorkspace % Utilization metrics
Grafana 403Managed identity lacks Monitoring Data Readeraz role assignment list --scope $AMW_ID
Rule does not fireclusterName / scope inconsistent with dataaz alerts-management prometheus-rule-group show
Alert has no emailRule has no actions / recipient unsubscribed / alert processing ruleaz monitor action-group show
ContainerLogV2 is emptyV2 not enabled / stream name wrongaz aks show --query addonProfiles.omsagent
Write 422Duplicate series (same-named cluster / dual writes)count by (cluster) (up)

Recommended configuration snippets

settings ConfigMap: add only the metrics you need

  cluster-metrics: |-
    default-targets-metrics-keep-list: |-
      nodeexporter = "node_disk_io_now"
      kubelet = ""
    minimal-ingestion-profile: |-
      enabled = true
  prometheus-collector-settings: |-
    cluster_alias = ""
    deny_fs_access_through_sms = true

Monitor: drop high-cardinality labels

    metricRelabelings:
    - action: labeldrop
      regex: 'user_id|session_id'
    - sourceLabels: [__name__]
      action: keep
      regex: 'myapp_.*'

Capstone lab + final quiz

Build the complete Azure managed monitoring chain from scratch: AKS → managed Prometheus → PodMonitor → Managed Grafana → rule group + Action Group → Container Insights, then complete one end-to-end alerting drill and cleanup
About 45 minutes (including waits)Incurs costs (about 1–2 USD)
Scenario myapp is about to go live on Azure. The SRE review requires: ① metrics use managed Prometheus, written to a dedicated workspace (must not fall into the default workspace); ② myapp's requests, 5xx, latency and Redis status are viewable in Managed Grafana, with viewers authorized through Entra groups; ③ an email is sent when the 5xx ratio > 5% for 5 minutes, and it auto-resolves; ④ only Logs and Events are collected for logs; ⑤ cost estimates and cleanup records are kept.
Environment (module 0): resource group, ACR, AKS (2× D2s_v5), myapp:1.1 (with access logs) and Redis, loadgen.
source ~/promlab/azure/env.sh
az group create -n $RG -l $LOC --tags purpose=prom-lesson3 expires=$(date -d '+2 days' +%F)
az acr create -g $RG -n $ACR --sku Basic
az aks create -g $RG -n $AKS -l $LOC --node-count 2 --node-vm-size Standard_D2s_v5 \
  --enable-managed-identity --generate-ssh-keys --attach-acr $ACR --tier free
az aks get-credentials -g $RG -n $AKS --overwrite-existing
(cd ~/promlab/myapp && az acr build -r $ACR -t myapp:1.1 .)
sed "s/ACR_NAME/$ACR/; s/myapp:1.0/myapp:1.1/" ~/promlab/azure/myapp.yaml | kubectl apply -f -
Managed Prometheus (module 2):
az monitor account create -n $AMW -g $RG -l $LOC
AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
az grafana create -n $AMG -g $RG -l $LOC --sku-tier Standard
AMG_ID=$(az grafana show -n $AMG -g $RG --query id -o tsv)
az aks update -g $RG -n $AKS --enable-azure-monitor-metrics \
  --azure-monitor-workspace-resource-id $AMW_ID --grafana-resource-id $AMG_ID \
  --ksm-metric-labels-allow-list "pods=[app]"
Scrape myapp (module 3): kubectl apply -f ~/promlab/azure/myapp-podmonitor.yaml; in a collector replica :9090/targets shows 2 up targets.
Grafana (module 4): confirm the Grafana managed identity has Monitoring Data Reader on the workspace; import myapp-dashboard.json; grant one Entra group Grafana Viewer.
Alerts (module 5): create ag-prom-lab and myapp-rules; keep loadgen with /error, and after about 6–8 minutes receive MyAppHigh5xxRatio; after changing loadgen, receive Resolved.
Logs (module 6): create law-prom-lab, enable the monitoring add-on (three Logs and Events streams); give the Grafana managed identity Log Analytics Reader; add a KQL panel to the myapp dashboard.
Fault drill (module 7): change the PodMonitor port to metrics, confirm MyAppPodsMissing fires within 3–5 minutes; auto-resolves after recovery.
Cost and cleanup (module 8): use the cost calculator to estimate this lab's cost and record it; run the full cleanup and leftover checks.
Acceptance checklist

Open-ended self-test (answer first, then expand the reference answer)

1. In managed Prometheus, which components and identities does a sample pass through from myapp to a Grafana panel?

the target allocator (operator-targets) assigns PodMonitor targets to the ama-metrics replicas → prometheus-collector scrapes /metrics, relabels, adds the cluster label → addon-token-adapter exchanges the cluster managed identity for an Entra token → samples are written to the workspace DCE, and the DCR routes them to amw-prom-lab → Grafana uses its own system-assigned managed identity to obtain a token for the audience https://prometheus.monitor.azure.com token, uses Monitoring Data Reader on the workspace to call the query endpoint → users in the browser sign in with Entra and view with the Grafana role on the Grafana instance.

2. How do you choose among the four entry points: PodMonitor, ServiceMonitor, ConfigMap and Pod annotations?

Operator style with per-Pod scraping → PodMonitor; existing Service → ServiceMonitor; migrating an existing prometheus.yml or needing static_configs → ama-metrics-prometheus-config; quick trial → annotations + podannotationnamespaceregex. Use only one per target. For node-level targets use -node a ConfigMap, which scrapes only $NODE_IP.

3. Why can a Grafana Viewer see data that they personally have no Azure access to? How do you design isolation?

Grafana queries with its own managed identity, so the visible data is limited to that identity's role scope. Isolation: Limited Viewer + folder/dashboard permissions; sensitive data in separate workspaces and data sources, with data source permissions restricted; split Grafana instances where necessary.

4. In the managed path, how is the Lesson 2 Alertmanager routing tree implemented?

Managed rule groups have no routing tree: each alert rule specifies an Action Group directly through actions[].actionGroupId ; rule groups and Action Groups can be split by team; silences / maintenance windows use alert processing rules; complex routing can be handled by webhooks into your own service.

5. Where do metrics and logs go? Why not put everything into Log Analytics?

Metrics → Azure Monitor workspace (billed per sample, about 0.16 USD per 10 million samples; PromQL suits aggregation and alerting); logs, events, manifests → Log Analytics (billed per GB, 2.76 USD/GB). High-frequency numeric data written to log tables is amplified into many rows, making both cost and query efficiency worse. With managed Prometheus enabled, Container Insights uses the Logs and Events preset.

6. When cleaning up, besides deleting rg-prom-lab, what else should you check?

The node resource group MC_rg-prom-lab_aks-prom-lab_canadacentral (usually deleted with AKS), the workspace managed resource group MA_amw-prom-lab_canadacentral_managed, the default workspace and DefaultRG-*, the rule groups created by recommended alerts, orphaned role assignments, and the local kubeconfig context; Log Analytics soft delete.

Final quiz (12 questions, covering all modules)

Sources and version notes

Basis for verifying the Azure facts in this lesson (verified 2026-11-15; page dates are the ms.date / update time in learn.microsoft.com metadata)
TopicVerified conclusionSource
Enabling managed Prometheusaz aks create/update --enable-azure-monitor-metrics, optional --azure-monitor-workspace-resource-id,--grafana-resource-id,--ksm-metric-labels-allow-list,--ksm-metric-annotations-allow-list,--enable-control-plane-metrics,--enable-windows-recording-rules; requires a managed-identity cluster, the resource providers Microsoft.ContainerService/Insights/AlertsManagement/Monitor (Microsoft.Dashboard for Grafana subscriptions); aks-preview must be uninstalled; if no workspace is specified, the default workspace is used DefaultAzureMonitorWorkspace-<region> (DefaultRG-<region>); linking Grafana requires Owner, or Contributor + User Access AdministratorEnable monitoring for AKS(ms.date 2026-08-18, updated 2026-11-10)
Container Insightsaz aks enable-addons --addon monitoring --workspace-resource-id --data-collection-settings; JSON fields interval / namespaceFilteringMode / namespaces / enableContainerLogV2 (default true) / streams; cost presets Logs and Events (default) / Syslog / Standard / Cost-optimized; the “Logs and events” group notes it is recommended when managed Prometheus is enabled; list of stream names; verification ama-logs DS and ama-logs-rssame as above
new az aks parametersappears in the CLI reference --enable-azure-monitor-logs (configured through the Azure Monitor profile for Container Insights; cannot be used together with --enable-addons monitoring ), OTLP-related parametersaz aks CLI reference(accessed 2026-11-15)
Default targets and minimal ingestionEnabled by default: cadvisor, nodeexporter, kubelet, kube-state-metrics, networkobservabilityRetina; disabled by default: coredns, kubeproxy, apiserver; control plane apiserver/etcd; minimal ingestion enabled by default; default recording rules and ux rules; dashboards are provisioned automatically after linking GrafanaDefault Prometheus metrics configuration(2026-08-18)
settings ConfigMapama-metrics-settings-configmap (kube-system, does not exist by default), schema v2: cluster-metrics / controlplane-metrics / prometheus-collector-settings; default targets 30s; after applying, Pods restart within 2–3 minutes; cluster_alias alphanumerics only; debug mode; ksm-config; in the template secrets_access_namespaces,deny_fs_access_through_smsCustomize scraping using ConfigMap(updated 2026-10-13) · official template(retrieved 2026-11-15)
custom scrape ConfigMapama-metrics-prometheus-config (replicas, recommended),-node,-node-windows; data key prometheus-config; promconfigvalidator located in /opt/promconfigvalidator; supports only static_configs and kubernetes_sd_configs; the ConfigMap method does not support global external_labels; metric renaming is not supported; ama-metrics-mtls-secretCustom scrape jobs using ConfigMap(updated 2026-07-17)
PodMonitor / ServiceMonitorAPI group azmonitoring.coreos.com/v1; can be deployed in any namespace; does not conflict with open-source CRDs and does not read open-source objects; ports must be named; the template includes labelLimit 63 / labelNameLengthLimit 511 / labelValueLengthLimit 1023; on K8s 1.37+ Secret access is granted per namespace (secrets_access_namespaces + Role/RoleBinding to ama-metrics-serviceaccount)Custom scrape jobs using CRDs(2026-11-09)
TroubleshootingPods: ama-metrics-operator-targets-*, ama-metrics-ksm-*, ama-metrics-node-* (and the replicas ama-metrics-*); containers prometheus-collector, config-reader, targetallocator, addon-token-adapter; 9090 UI (/config /service-discovery /targets), debug 9091; “No configuration present for the AKS resource”; label limits; workspace utilization metrics; managed resource group MA_<amw>_<region>_managed; 1–2 minute gap during node upgradesTroubleshoot Prometheus metrics(updated 2025-06-19)
Query APItoken resource https://prometheus.monitor.azure.com; role Monitoring Data Reader; supports query / query_range / series / labels / label/__name__/values; must include __name__ matcher; query_range 32 days, series 12 hours; case-insensitive; duplicate series return 422; exemplars not supportedQuery Prometheus metrics using API and PromQL(updated 2025-10-01)
Rule groupsType Microsoft.AlertsManagement/prometheusRuleGroups, API 2023-03-01; scopes must include the workspace and may add one cluster; clusterName; interval default PT1M; severity 0–4, default 3; autoResolved default true, timeToResolve default PT5M; requires Monitoring Contributor; resource health; az-prom-rules-converter; CLI az alerts-management prometheus-rule-group create (alertsmanagement extension, parameters --scopes --rules --cluster-name --interval --enabled)Rule groups(2026-08-07) · CLI reference
Recommended alertsPortal Alerts → Set up recommendations; ARM/Bicep templates; community rule list (KubePodCrashLooping, KubeContainerOOMKilledCount, KubeNodeUnreachable, etc.) and platform metric rules; legacy Container insights metric alerts retired on 2024-05-31Recommended alert rules(2026-07-21)
Action Group CLI--action email NAME EMAIL_ADDRESS [usecommonalertschema], webhook/logicapp and other formats; --short-name; default location Global; enable-receiver,test-notifications createaz monitor action-group(2026-11-06)
Azure Monitor workspace CLIaz monitor account create/show/delete is the core CLI (GA)az monitor account(2026-11-06)
Managed Grafana tiersEssential cannot be newly created and is fully deprecated on 2027-03-31; Standard is recommended, X1 (default) / X2 (alert rules 500/1000 per organization), can be upgraded but not downgraded; zone redundancy, deterministic outbound IP, private endpoints, alerting, SMTP and reporting are Standard only; Grafana Enterprise optionalWhat is Azure Managed Grafana?(2026-06-24)
Grafana rolesGrafana Admin / Editor / Limited Viewer / Viewer (including role IDs); Limited Viewer corresponds to “No Basic Role”, not applicable to v9; assignment requires RBAC Administrator / UAA / OwnerGrant users and identities access(2026-09-22)
Link workspaceAssign Monitoring Data Reader to the Grafana managed identity on the workspace; requires a system-assigned managed identity; Integrations → Azure Monitor workspaces; from Grafana 13 authentication is provided by the Azure Monitor Managed Service for Prometheus plugin; list of pre-provisioned dashboardsAdd an Azure Monitor workspace(2026-07-03)
az grafana CLIamg extension; create parameters --sku-tier (default Standard), --grafana-major-version, --principal-ids, --skip-role-assignments, --skip-system-assigned-identity, --zone-redundancy, --deterministic-outbound-ip, --public-network-access; update --major-version; integration monitor add (preview, --monitor-rg-name --monitor-name); dashboard import --definition (JSON / gallery ID / path / URL); backup/restore/migrateaz grafana(2026-09-01) · CLI quickstart
Pricingcanadacentral (USD): Metrics ingestion 0.16/10M samples; Prometheus Metrics Queries 0.001/10M samples; Analytics Logs ingestion 2.76/GB, retention 0.12/GB/month; Managed Grafana Standard Node 0.04104/hour, Standard User 6/month, Zone Redundancy 0.04932/hour; D2s v5 Linux 0.107/hour; Emails 0.00002/messageAzure Retail Prices API(queried 2026-11-15) · follow the pricing page

Video verification notes

The following videos were verified on 2026-11-15 through the YouTube oEmbed endpoint (https://www.youtube.com/oembed?url=…&format=json). Titles and channels verified: Microsoft Azure “Azure Monitor's cloud native offering with Kubernetes Monitoring” (JSBUXNCGLd4); John Savill's Technical Training “Azure Kubernetes Services (AKS) Overview” (c4nTKMU6fBU), “Microsoft Azure Monitor Agent (AMA) and Data Collection Rule (DCR) Overview” (Z1zDlXCwI9k), “Microsoft Azure Monitor - Alert Processing Rules” (cHH4RkL-9Dg), “Azure Master Class v2 - Module 10 - Monitoring & Security” (gzBXFnfvoXo), “Azure Monitor Logs Log Types” (lzVQ3NqMnTE); Azure Kubernetes Service (AKS) “AKS Labs: Observability with Managed Prometheus and Managed Grafana” (A1Ue-IEpoiA); Microsoft Reactor live stream of the same name (Dc0TqbAkQX0); Houssem Dellai “Azure Managed Prometheus and Grafana for AKS monitoring” (sGWtz_kkKX8); Travis Roberts “How to Deploy Azure Managed Grafana” (NAHOIRZlKrM); Azure Power Lunch “Azure Managed Grafana: Latest Updates” (4SOgWXgBnf8); Cloud Quick Labs “Azure Kubernetes Services Insights | AKS Container Insights Using Azure Log Analytics Workspace” (vJkqyF7i_QU); multicloud architect “Kubernetes on Azure series 6/10: AKS observability: Azure Monitor, Container Insights” (Tg-IRdEIOJY). No verified video specifically covering “managed Prometheus rule groups” or “managed monitoring costs and cleanup” was found; the corresponding modules provide storyboards instead. Community videos were recorded earlier, so parameters and interfaces follow this lesson's verified content.

Narration notes

The “Narration” page uses the browser's built-in Web Speech API (speechSynthesis, en-US) to read the narration script aloud in real time, with English terms pronounced in en-US; results depend on the speech packs installed on the operating system (such as Windows “Microsoft Xiaoxiao” or macOS “Tingting”). The courseware generation environment cannot call a TTS service, so no MP3 is embedded; the narration script can be passed directly to tools such as Azure AI Speech to generate audio.

Known limitations

  • The commands in this lesson are written according to the official documentation,and have not actually been executed in this environment; resource IDs, GUIDs, endpoint suffixes, Pod names, IPs, times, counts and price calculation results in the expected outputs are sample values.
  • promconfigvalidator output text, some JSON field names of rule groups / data sources, the CLI internal names of workspace utilization metrics,ama-metrics label selectors of each Pod (rsName/dsName) and the number of containers may change with the add-on version; follow the actual output.
  • The following items were handled conservatively and are marked “follow the official documentation”: when linking Grafana, whether Monitoring Reader or Monitoring Data Reader is assigned automatically (the two official docs word this differently; this lesson uses Monitoring Data Reader as the role needed to read data); az grafana create the details of default role assignments; the Grafana major versions that are currently default / selectable in Managed Grafana; the number of billed nodes for Standard instances; the relationship between the “Metric Samples Ingested/Processed” metering items that newly appeared in the retail prices API in 2026-10 and managed Prometheus; az account get-access-token querying the workspace directly with a user token (the official examples use app registration); --rules @file syntax; az grafana dashboard import requirements on the outer wrapper; ContainerLogV2 table plan options; the specific keys of the container log namespace exclusion ConfigMap; Log Analytics soft delete and --force; rendering of alert annotation templates.
  • The names and locations of the DCR/DCRA created for the cluster when metrics are enabled are not given on this verified page, so the course does not hard-code names.
  • The times, proportions, log lines and costs in the animations are mechanism illustrations and do not represent the service's exact timing or billing.
  • Lessons 1, 2 and 4–8 were written in parallel with this lesson; cross-lesson references (myapp source, Lesson 2 rule file names) follow the course-wide conventions; this lesson provides a minimal myapp implementation consistent with those conventions in module 0 so it can be completed independently.