Prometheus & Grafana Lesson 3: Moving to the Cloud (Azure)
- 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-metricsto connect the AKS clusteraks-prom-labto an Azure Monitor workspaceamw-prom-lab, and identify the extraama-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_totalunified metrics, etc.): PodMonitor / ServiceMonitor (groupazmonitoring.coreos.com/v1),ama-metrics-prometheus-configConfigMap, Pod annotations; and tuneama-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
| # | Time | Module | Core content | Animation / interaction | Lab (AKS aks-prom-lab) |
|---|---|---|---|---|---|
| 0 | Before class | Warm-up and AKS preparation | Resource providers, variables, ACR + AKS, push myapp to ACR and deploy | Environment self-check list | myapp on AKS /metrics reachable |
| 1 | 00–05 | Monitoring architecture choices on Azure | Self-managed kps / managed Prometheus / Container Insights / hybrid remote_write; responsibility boundaries | Requirements → architecture recommender | Draw this lesson's target architecture and list resources |
| 2 | 05–13 | Managed Prometheus and AKS integration | Azure Monitor workspace, DCR/DCE, ama-metrics components, default targets and minimal ingestion profile, control-plane metrics | Core animation: Managed collection → workspace → Grafana data and identity flow | Create amw-prom-lab and enable metrics |
| 3 | 13–21 | Scrape configuration: ConfigMap, PodMonitor, ServiceMonitor | Four scrape entry points, target allocator, settings ConfigMap, promconfigvalidator, label limits | Scrape configuration diagnostic simulator | PodMonitor scrapes myapp, verify targets |
| 4 | 21–29 | Managed Grafana: identity, permissions and data sources | Standard X1/X2, Entra sign-in, Grafana roles, system-assigned managed identity, Monitoring Data Reader, provisioned dashboards | Step-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 |
| 5 | 29–37 | Managed alert rule groups and Action Groups | Rule group scope, record/alert, for/severity/autoResolve, Action Groups, recommended alerts, rule conversion tool | Alert timeline simulator | 5xx alert → email → auto-resolve |
| 6 | 37–45 | Container Insights, correlating logs and metrics | ama-logs, DCR streams, cost presets, ContainerLogV2, KQL, side-by-side correlation in Grafana | Metric spike → logs for the same time window | Enable the “Logs and events” preset, query myapp errors with KQL |
| 7 | 45–54 | Cloud troubleshooting in practice | No data, 403, rule not firing, throttling, case insensitivity, 422 duplicate series | Fault injection: which hop is broken | Reproduce and fix 5 faults |
| 8 | 54–60 | Cost, cleanup and self-test | Metering items and estimates, cost-saving measures, least privilege, cleanup order and leftover resources | Cost calculator + troubleshooting decision tree | Estimate this lab's cost and clean up completely |
| — | After class | Cheat sheet · Capstone lab | One-click script builds the full managed monitoring chain from scratch and verifies it | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skill | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Choose a monitoring architecture for AKS | ✓ | ✓ | · | · | · | ✓ | · | ✓ | — | M1 architecture diagram |
| Enable managed Prometheus | · | ✓ | · | · | · | · | ✓ | · | az monitor account create,az aks update --enable-azure-monitor-metrics | M2 |
| scrape custom application metrics | · | · | ✓ | · | · | · | ✓ | · | kubectl apply PodMonitor,kubectl create configmap ama-metrics-prometheus-config | M3 |
| control ingestion volume and cardinality | · | ✓ | ✓ | · | · | · | ✓ | ✓ | ama-metrics-settings-configmap,metricRelabelings | M3 / M8 |
| Grafana identity and permissions | · | · | · | ✓ | · | · | ✓ | ✓ | az grafana create,az role assignment create | M4 |
| PromQL queries and dashboards | · | ✓ | ✓ | ✓ | ✓ | ✓ | · | · | az grafana dashboard import, query API | M4 |
| managed rules and notifications | · | · | · | · | ✓ | · | ✓ | · | az alerts-management prometheus-rule-group create,az monitor action-group create | M5 |
| log and metric correlation | · | · | · | ✓ | · | ✓ | ✓ | · | az aks enable-addons --addon monitoring, KQL | M6 |
| cloud fault localization | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | kubectl logs -c prometheus-collector/config-reader/addon-token-adapter | M7 |
| cost estimation and cleanup | ✓ | · | · | · | · | ✓ | · | ✓ | az group delete, Retail Prices API | M8 |
Topics excluded from this lesson (and where to learn them)
| Topic | Why it's not in this lesson | Where to learn it |
|---|---|---|
PromQL basics, scrape interval,rate() principles | Covered in Lesson 1; used directly in this lesson | Lesson 1 |
| Alertmanager routing tree, inhibition, silences | On the managed path, Azure Monitor alerts + Action Groups replace this; concept mapping in module 5 | Lesson 2 |
| AWS managed services (AMP / AMG / ADOT) | Belongs to another cloud | Lesson 4 |
| kube-prometheus-stack, Prometheus Operator reconciliation details | This lesson only uses managed add-ons; the self-managed stack is explained more thoroughly on kind | Lesson 5 |
| remote_write to an Azure Monitor workspace (self-managed Prometheus remote_write + managed identity sidecar), Azure Arc clusters | Belongs to hybrid/migration architecture; module 1 only positions it | Lesson 6 · Official: remote-write |
| Application Insights / OpenTelemetry tracing | Beyond the scope of “metrics + logs” | Official: AKS OTLP |
| Full IaC (Bicep/Terraform) of this lesson's resources | This lesson uses the az CLI so that each step is visible | Terraform course Lesson 3; official Bicep templates see module 2 links |
How to use this courseware
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.
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).
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.
--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)
- Completed Lesson 1 and Lesson 2: locally,
~/promlabcontains the myapp source (exposingmyapp_http_requests_total{method,route,status},myapp_http_request_duration_seconds, andmyapp_redis_up) and the alert rules written in Lesson 2prometheus/rules/*.yml. - Tools: Azure CLI (
az version, latest recommended;az grafanais part of theamgextension,az alerts-managementis part of thealertsmanagementextension; 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-labhave 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 buildto 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
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).
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
- 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.
What: four patterns on Azure
| Architecture | Collection | Storage | Query / visualization | Alerting |
|---|---|---|---|---|
| A. Self-managed: kube-prometheus-stack running in AKS | Prometheus (Operator) | In-cluster TSDB + PV (Thanos/Mimir can be added) | Self-managed Grafana | Self-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 portal | Prometheus rule group → Azure Monitor alerts → Action Group |
| C. Hybrid: self-managed Prometheus + remote_write | Self-managed Prometheus | short local retention + remote_write to the Azure Monitor workspace | Managed Grafana / self-managed both work | Either works |
| D. Container Insights only (logs-first) | ama-logs | Log Analytics workspace (KQL tables) | Portal Insights views, workbooks | Log 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
| Resource | Type | Name in this lesson | What it contains |
|---|---|---|---|
| Azure Monitor workspace | Microsoft.Monitor/accounts | amw-prom-lab | Prometheus 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 workspace | Microsoft.OperationalInsights/workspaces | law-prom-lab | KQL tables such as ContainerLogV2, KubeEvents, KubePodInventory |
| Azure Managed Grafana | Microsoft.Dashboard/grafana | amg-prom-lab-<suffix> | dashboards, data sources, Grafana alerts (Standard); system-assigned managed identity |
| Prometheus rule groups | Microsoft.AlertsManagement/prometheusRuleGroups | myapp-rules etc. | record / alert rules, scope = workspace (+ optional cluster) |
| Action Group | Microsoft.Insights/actionGroups | ag-prom-lab | receivers 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) | |
|---|---|---|---|
| Collector | AKS add-on ama-metrics (DaemonSet + replicas + target allocator) | AMP managed scraper, or ADOT / self-managed Prometheus remote_write | Prometheus managed by the Prometheus Operator |
| Storage | Azure Monitor workspace | AMP workspace | Local TSDB + PV |
| Write identity | Cluster managed identity (Entra token) | IAM role + SigV4 | None (local) |
| Visualization | Managed Grafana (Entra sign-in) | AMG (IAM Identity Center) | Self-managed Grafana |
| Alerting | Rule group → Azure Monitor alerts → Action Group | AMP rules + AMP Alertmanager → SNS | PrometheusRule → Alertmanager |
Architecture diagram: this lesson's target architecture (B + D)
Comparison diagram: local Compose (Lessons 1 and 2) → Azure managed (this lesson)
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.
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.
| Command | Purpose | Key parameters / notes |
|---|---|---|
az monitor account list | List Azure Monitor workspaces | -g filter by resource group; note DefaultAzureMonitorWorkspace-* is created automatically when no workspace is specified |
az monitor log-analytics workspace list | List Log Analytics workspaces | DefaultWorkspace-* same as above |
az grafana list | List Managed Grafana | requires amg extension |
az aks show --query azureMonitorProfile | Whether the cluster has managed Prometheus enabled | metrics.enabled |
az aks show --query addonProfiles.omsagent | Whether Container Insights (monitoring add-on) is enabled | config.logAnalyticsWorkspaceResourceID |
az resource list --resource-type Microsoft.AlertsManagement/prometheusRuleGroups | List Prometheus rule groups | Commonly 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)
amw-prom-lab.~/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
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.
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 json2. 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 tableA 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
Official documentation
- Enable monitoring for AKS clusters
- Azure Monitor managed service for Prometheus overview
- What is Azure Managed Grafana?
Video storyboard (about 75 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
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.
Module 2 · Azure Monitor managed Prometheus and AKS integration
- 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-idto enable managed collection, and explain the roles ofama-metrics(replicas),ama-metrics-node(DaemonSet),ama-metrics-ksm,ama-metrics-operator-targets. - Understand the “minimal ingestion profile” and default targets; know where
clusterlabels 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).
What: what managed Prometheus consists of
- Azure Monitor workspace (
Microsoft.Monitor/accounts): time-series storage and PromQL query endpoint (in the formhttps://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 groupMA_<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-configcustom 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, andama-metrics-prometheus-config-nodejobs 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 (containersconfig-reader,targetallocator).
prometheus-collector(a Prometheus receiver based on the OpenTelemetry Collector + MetricsExtension write component) andaddon-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 listoutput).
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
- The target allocator generates scrape jobs from default targets + ConfigMap + CRDs and assigns them to the collector replicas.
prometheus-collectorPer thescrape_interval(default targets: 30s), sends scrape requests to targetsGET /metrics, applies relabeling and the minimal-ingestion keep list, and appendsclusterlabel (by default the last segment of the cluster resource IDaks-prom-lab, can be overridden withcluster_alias).addon-token-adapterUsing 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.- The workspace accepts data according to its active time series and events-per-minute quotas; exceeding them causes throttling (module 7).
- 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
| Category | Target | Notes |
|---|---|---|
| Enabled by default | cadvisor,nodeexporter,kubelet,kube-state-metrics,networkobservabilityRetina | every 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 default | coredns,kubeproxy,apiserver | in ama-metrics-settings-configmap enabled in |
control plane (requires --enable-control-plane-metrics) | apiserver,etcd scheduler, controller-manager, cluster-autoscaler, etc. must be enabled separately | belongs to the controlplane-metrics section of the settings ConfigMap |
| Automatically configured | default recording rules (such as instance:node_cpu_utilisation:rate5m),ux:* visualization rules | created 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 asapp) →--ksm-metric-labels-allow-list "pods=[app]"(can also be overridden in theksm-configof 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-on | Self-managed Prometheus (Lesson 1) | Prometheus agent mode + remote_write | |
|---|---|---|---|
| Local storage | None (send buffer only) | TSDB (head + WAL + block) | WAL only |
| Rule evaluation | Workspace-side rule groups | Local | Not supported (remote required) |
| Write authentication | Cluster managed identity, automatic | — | Self-configured (managed identity sidecar available on Azure) |
| Upgrades | Managed by Microsoft with AKS | Self-managed | by you |
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
Data and identity flow: writing and reading are two different identities
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az monitor account create | Create an Azure Monitor workspace (core CLI) | -n -g -l; optional --public-network-access |
az monitor account show | View ID, query endpoint, default DCR/DCE | --query metrics.prometheusQueryEndpoint |
az aks update --enable-azure-monitor-metrics | Enable 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-metrics | Collect API Server / etcd metrics | Requires managed Prometheus to be enabled (or enabled in the same command) |
az aks update --disable-azure-monitor-metrics | Disable the add-on | Workspace and existing data are retained |
kubectl get pods -n kube-system | grep ama-metrics | Check components | The 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)
kube-system , which consume a small amount of node resources.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
kubectl get pods -n kube-system -w | grep --line-buffered ama-metrics
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).
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"}
0myapp_http_requests_total returns an empty result — this is the problem module 3 will solve.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.
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]'
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
Official documentation
- Enable monitoring for AKS clusters
- Default Prometheus metrics configuration
- Query Prometheus metrics using the API and PromQL
- Monitor AKS control plane metrics
Video storyboard (about 100 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
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.
Module 3 · Scrape configuration: ConfigMap, PodMonitor and ServiceMonitor
- 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 porthttp,labelLimitand the three limit fields). - Will change
ama-metrics-settings-configmap(schema v2:cluster-metrics/controlplane-metrics/prometheus-collector-settings),promconfigvalidatorand pre-check the ConfigMap with - Confirm via the 9090 UI of a collection Pod and its
config-reader/targetallocatorlogs that targets are discovered and scraped.
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:
| Object | What it selects by label | What is finally scraped |
|---|---|---|
| ServiceMonitor | Service (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. |
| PodMonitor | Pod (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.
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 point | Where it is written | Who runs it | Suited for |
|---|---|---|---|
| PodMonitor | any namespace,apiVersion: azmonitoring.coreos.com/v1 | ama-metrics replicas (assigned by the target allocator) | No Service, or you want to scrape each Pod (myapp in this lesson) |
| ServiceMonitor | any namespace, same as above | same as above | Services already exist; scrape by Endpoints |
| ConfigMap custom jobs | kube-system/ama-metrics-prometheus-config, key prometheus-config | ama-metrics replicas | standard Prometheus syntax,static_configs,kubernetes_sd_configs, for migrating an existing prometheus.yml |
| ConfigMap (node-level) | ama-metrics-prometheus-config-node / -node-windows | the DaemonSet Pod on each node | scrapes only targets on this node ($NODE_IP); service discovery must not be used |
| Pod annotations | on the Pod prometheus.io/scrape|path|port + in settings podannotationnamespaceregex | ama-metrics replicas | quick 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; removecontrolplane-prefixes from control-plane targets;minimalingestionprofile = truebecomes a separateminimal-ingestion-profilesection. - 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.comtoazmonitoring.coreos.com,release: kpsselection labels such as are not needed in the managed version). - Migrating Lesson 1's
prometheus.ymljobs → ConfigMap custom jobs (globalexternal_labelsis 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-on | kube-prometheus-stack (Lesson 5) | |
|---|---|---|
| CRD group | azmonitoring.coreos.com/v1 | monitoring.coreos.com/v1 |
| which Monitors are selected | all Monitors in all namespaces | Prometheus CR's serviceMonitorSelector (such as release: kps) |
| Secret access | K8s 1.37+ requires secrets_access_namespaces + a Role/RoleBinding per namespace | Operator RBAC |
| Config validation | promconfigvalidator (built into the Pod) | promtool check config |
| Metric renaming | not supported | supported (relabel __name__) |
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
Flow diagram: a PodMonitor from apply to up=1
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.
Core commands and configuration
| Command | Purpose | Key parameters / notes |
|---|---|---|
kubectl get crd | grep azmonitoring | Confirm the add-on CRDs are installed | podmonitors.azmonitoring.coreos.com,servicemonitors.azmonitoring.coreos.com |
kubectl get podmonitors.azmonitoring.coreos.com -A | List managed PodMonitors | use 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-system | Create a custom job | the file name must be prometheus-config (no extension) |
kubectl apply -f ama-metrics-settings-configmap.yaml | change default targets, keep list, annotation namespaces, alias | Pods restart and take effect after 2–3 minutes |
kubectl port-forward <ama-metrics pod> -n kube-system 9090 | Agent mode UI | /config,/service-discovery,/targets |
kubectl logs <operator-targets pod> -c config-reader|targetallocator | configuration parsing and target discovery logs | look 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"}}}}}'
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)
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'
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).
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
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)./targets will then have an extra myapp-cm job; after confirming, delete the ConfigMap to avoid duplicate scraping.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.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.
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
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
Official documentation
- Create custom scrape jobs using CRDs
- Create custom scrape jobs using ConfigMap
- Customize scraping using ama-metrics-settings-configmap
- Pod/Service Monitor official templates (GitHub)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
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.
Module 4 · Azure Managed Grafana: identity, permissions and data sources
- Use
az grafana createto 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 createto grant access to Entra users or groups. - Link
amw-prom-labto 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 importandbackup/restore.
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.
| Tier | Status | Key points |
|---|---|---|
| Essential | Cannot be newly created; existing instances are scheduled for full deprecation on 2027-03-31 | No SLA, no alerting, only Azure Monitor / Prometheus / TestData data sources |
| Standard (recommended, CLI default) | GA | Instance 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
| Scope | Role | What it can do |
|---|---|---|
| Grafana instance | Grafana Admin | Full control: data sources, dashboards, teams and permission management |
| Grafana Editor | View and edit dashboards and alerts | |
| Grafana Viewer | View dashboards and alerts | |
| Grafana Limited Viewer | Can 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 workspace | Monitoring Data Reader | Read Prometheus data in the workspace (needed by the Grafana managed identity, your users, and rule automation) |
| Subscription / resource group | Monitoring Reader | Read 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
- 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'sazureMonitorWorkspaceIntegrations, requires Owner or Contributor + User Access Administrator). - 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). - 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 Grafana | Self-managed Grafana (Lesson 1) | AWS AMG (Lesson 4) | |
|---|---|---|---|
| Sign-in | Entra ID SSO | Local admin/password or self-configured OAuth | IAM Identity Center / SAML |
| Authorization | Azure RBAC's four Grafana roles | Grafana internal organization roles | AMG user/group assignments |
| Data source authentication | Managed identity (system-assigned by default) | Basic/Token stored in the Grafana DB | Workspace IAM roles |
| Upgrades | Microsoft-managed; major version selectable (--grafana-major-version) | Self | AWS-managed |
Architecture diagram: two identity chains
Flow diagram: one panel refresh
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).
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az grafana create | Create 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 show | endpoint, managed identity, version | --query properties.endpoint,identity.principalId |
az grafana integration monitor add | Link workspace (preview) | --monitor-rg-name --monitor-name; by default assigns the read role |
az role assignment create | grants the Grafana role / data-read role | --scope are the Grafana instance ID / workspace ID respectively |
az grafana data-source list | View data sources | Confirm the managed Prometheus data source exists |
az grafana dashboard import | Import dashboard | --definition can be a JSON string, gallery ID, file path (@file.json) or URL; --folder,--overwrite |
az grafana backup / restore | Backup / migrate content | --components dashboards folders datasources,--remap-data-sources |
az grafana update --major-version | Upgrade Grafana major version | follow 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)
{
"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 .
Grafana Viewer , they can view the dashboard but cannot save changes.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
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
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.
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)
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
Official documentation
- What is Azure Managed Grafana?
- Add an Azure Monitor workspace to Managed Grafana
- Grant users and identities access
- az grafana CLI reference
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
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.
Module 5 · Managed alert rule groups and Action Groups
- Understand the scope (workspace + optional cluster ID +
clusterName), evaluation intervalinterval(default PT1M) and rule execution order. - Map Prometheus rule fields to managed fields:
for(ISO 8601, such asPT5M),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.
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 group | Notes |
|---|---|---|
groups[].name | Rule group resource name | unique within the resource group; cannot be changed after creation |
interval: 1m | interval: PT1M | ISO 8601 duration, default PT1M |
| Implicit scope of the Prometheus instance | scopes: workspace ID (required) + optionally one cluster ID; clusterName | if no cluster is specified, rules query data from all clusters in the workspace |
record / expr / labels | record / expression / labels | results are written back to the workspace as new series (this incurs ingestion) |
alert / expr / for: 5m | alert / expression / for: PT5M | also has a pending stage |
labels.severity: critical | severity: 0–4 | 0 is most severe, default 3 |
| Alertmanager routing → receiver | actions[].actionGroupId (specified directly on each rule) | no routing tree; cross-rule silences / inhibition use alert processing rules |
send_resolved: true | resolveConfiguration.autoResolved: true,timeToResolve: PT10M | the 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
- Each
interval, the rule group uses PromQL to query the workspace (on the data scoped byclusterName). - An expression result → enters pending; once the condition has held for the
forduration → fired, generating an Azure Monitor alert (with severity, labels and annotations). - 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).
- 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 groups | Prometheus + Alertmanager (Lesson 2) | AMP rules + Alertmanager (Lesson 4) | |
|---|---|---|---|
| Rule format | ARM/Bicep JSON (convertible from YAML) | YAML | YAML (upload) |
| Routing / grouping | No routing tree; each rule binds an Action Group | Routing tree, group_by | Alertmanager configuration |
| Silences | Alert processing rules (by scope / time) | silence | silence |
| Notification channels | Action Group (email / SMS / webhook / ITSM…) | receiver | SNS |
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
Timeline: 5xx ratio alert
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).
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az monitor action-group create | Create an Action Group | --short-name (shown in SMS),--action email NAME ADDRESS [usecommonalertschema],--action webhook NAME URI … |
az monitor action-group test-notifications create | Send a test notification | Verify the email is received |
az alerts-management prometheus-rule-group create | Create 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/delete | Manage rule groups | update --enabled false Disable the whole group |
az graph query | Query fired alerts | table 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)
az monitor action-group test-notifications create, parameters follow -h ), and confirm the test email is received.myapp-rules, the resource health should be Available.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)./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.kubectl -n myapp scale deploy redis --replicas=0, after about 3–5 minutes you receive MyAppRedisDown (Sev1); then --replicas=1 restore.ag-prom-lab, and save. Note this creates several rule groups; delete them together during cleanup.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.
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
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
No verified video specifically covering “managed Prometheus rule groups” was found; the storyboard below can be used for a self-made video.
Official documentation
- Rule groups in Azure Monitor managed service for Prometheus
- Recommended alert rules for Kubernetes clusters
- az monitor action-group
- az-prom-rules-converter (GitHub)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
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.
Module 6 · Container Insights, correlating logs and metrics
- Name the components of Container Insights (
ama-logsDaemonSet,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-settingswith the “Logs and Events” cost preset to collect onlyContainerLogV2,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.
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.
| Stream | Table | Contents |
|---|---|---|
Microsoft-ContainerLogV2 | ContainerLogV2 | Container stdout/stderr (new architecture: columns such as PodName, PodNamespace, ContainerName, LogMessage, LogLevel) |
Microsoft-KubeEvents | KubeEvents | Kubernetes events (image pull failures, OOMKilled, scheduling failures…) |
Microsoft-KubePodInventory | KubePodInventory | Pod manifests and status, restart counts |
Microsoft-Perf / Microsoft-InsightsMetrics | Perf / InsightsMetrics | performance metrics (usually not needed when managed Prometheus is enabled) |
Microsoft-ContainerInsights-Group-Default | All of the above | Default stream set |
Cost presets (optional when enabling in the portal)
| Preset | Frequency | Namespace filtering | Data collected |
|---|---|---|---|
| Logs and Events (default) | 1m | None | ContainerLogV2, KubeEvents, KubePodInventory — officially noted as “recommended when managed Prometheus is enabled” |
| Standard | 1m | None | All standard tables |
| Cost-optimized | 5m | Excludes kube-system, gatekeeper-system, azure-arc | All standard tables |
| Syslog | 1m | None | All 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
- Create a Log Analytics workspace
law-prom-lab. - Enable the monitoring add-on and collect only the three Logs and Events streams.
- 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). - 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 Insights | Loki (self-managed) | CloudWatch Container Insights (Lesson 4) | |
|---|---|---|---|
| Query language | KQL | LogQL | Logs Insights query language |
| Indexing | all columns queryable (billed by GB ingested) | indexes labels only | per GB |
| Correlation with metrics | Grafana side-by-side panels / portal workbooks | Grafana native (same labels) | CloudWatch dashboards |
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
Correlation key comparison
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.
Core commands and parameters
| Command | Purpose | Key parameters / notes |
|---|---|---|
az monitor log-analytics workspace create | Create a Log Analytics workspace | -g -n -l; --retention-time |
az aks enable-addons --addon monitoring | Enable Container Insights (official documentation example) | --workspace-resource-id,--data-collection-settings dcs.json |
az aks update --enable-azure-monitor-logs | newer 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 monitoring | Disable | workspace data retention |
az monitor log-analytics query | Run 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)
ama-logs and ama-logs-rs Running.kubectl logs should show the access logs; change loadgen back to a version containing /error (module 0 step 5) to produce 5xx errors.Pulling/Started/Killing events.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 ascPlace 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.
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.
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.json2. 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
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
Official documentation
- Enable monitoring (including the Log configuration file and stream list)
- ContainerLogV2 schema
- High scale mode
Video storyboard (about 80 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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”.
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.
Module 7 · Cloud troubleshooting in practice
- 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.
What: the seven-hop model
| # | Hop | Observation point | Typical symptom |
|---|---|---|---|
| 1 | Add-on running | kubectl get pods -n kube-system | grep ama-metrics; describe check the restart reason | Pod missing / CrashLoop / OOMKilled |
| 2 | Configuration processing | operator-targets of the config-reader logs (prometheus-config-merger section) | custom jobs do not appear, ConfigMap rejected |
| 3 | Target discovery | targetallocator logs; collector Pod :9090/service-discovery | Monitor exists but has no targets |
| 4 | Scraping | :9090/targets (lastError),up; debug mode :9091/metrics | up=0, label limit exceeded, TLS/authentication failures |
| 5 | Writing | prometheus-collector and addon-token-adapter logs | “No configuration present for the AKS resource”, token errors |
| 6 | Workspace quota | workspace metrics Active Time Series % Utilization,Events Per Minute Received % Utilization | partial data missing, throttling |
| 7 | Reading | the caller's role on the workspace; query semantics | 403, 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
ExampleLabelandexamplelabel) 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_aliasor relabel). - Query API limits: a time-series query must have exactly one
__name__matcher;/seriesdoes not support regex filtering, at most 12 hours;/query_rangeat 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-modeof theenabled = true), in:9091/metricsview 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
| Question | Self-managed (Lessons 1–2) | Managed (this lesson) |
|---|---|---|
| Check targets | Prometheus /targets | the collector Pod's :9090/targets (agent-mode UI) |
| Check configuration | /config,promtool | :9090/config,promconfigvalidator, config-reader logs |
| Storage problems | Disk full, WAL corruption | Quota throttling, missing DCR/DCE |
| Query permissions | usually none | Monitoring Data Reader |
Seven-hop troubleshooting diagram
Symptom → most likely hop
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.
Troubleshooting command quick reference (by hop)
| Hop | Command | What to look at |
|---|---|---|
| 1 | kubectl get pods -n kube-system | grep ama-metrics | Running; restart count = number of times the ConfigMap was applied |
| 2 | kubectl logs <operator-targets> -n kube-system -c config-reader | Parse / merge / validation errors |
| 3 | kubectl logs <operator-targets> -n kube-system -c targetallocator | Whether the Monitor is recognized; Secret permissions |
| 4 | kubectl port-forward <ama-metrics pod> -n kube-system 9090 | /targets lastError,/service-discovery |
| 5 | kubectl logs <ama-metrics pod> -n kube-system -c prometheus-collector / -c addon-token-adapter | authentication, DCR configuration, MetricsExtension errors |
| 6 | az monitor metrics list --resource $AMW_ID --metric … | Active series and events-per-minute utilization |
| 7 | az role assignment list --scope $AMW_ID | Whether 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.
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.
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.
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
# 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.
# 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.
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.
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]]'
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
Official documentation
- Troubleshoot collection of Prometheus metrics
- Monitor Azure Monitor workspace ingestion limits
- Azure Monitor service limits (Prometheus metrics)
- Official troubleshooting script (GitHub)
Video storyboard (about 90 seconds)
This courseware cannot generate video/MP3 directly; storyboards and narration scripts are provided for a video tool.
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.
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.
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.
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.
Module 8 · Cost, cleanup and self-test
- 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).
What: metering items (canadacentral, retail prices API queried 2026-11-15, USD, for estimation only)
| Service | Metering item | Unit price (retail prices API) | Cost driver |
|---|---|---|---|
| Azure Monitor managed Prometheus | Metrics ingestion (ingested samples) | 0.16 / 10 million samples | Active series × collection frequency |
| Prometheus Metrics Queries (query-processed samples) | 0.001 / 10 million samples | Dashboard refresh, rule evaluation, API queries | |
| Log Analytics | Analytics Logs Data Ingestion | 2.76 / GB (a free-allowance row exists); retention 0.12 / GB / month (after the free retention period) | Log rows and size |
| Managed Grafana Standard | Standard Node | 0.04104 / hour | Instance running time (the number of billed nodes per instance follows the pricing page) |
| Standard User | 6 / active user / month | Users who signed in during the month | |
| Standard Zone Redundancy | 0.04932 / hour | When zone redundancy is enabled | |
| AKS nodes | Standard_D2s_v5 (Linux pay-as-you-go) | 0.107 / hour / node | Number of nodes × duration; the Free tier control plane is not charged |
| Azure Monitor alert notifications | Emails | 0.00002 / message after the free allowance | Number 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
- Keep minimal ingestion: add only the metrics you need via the keep list, and do not turn off
minimal-ingestion-profile. - Adjust frequency:
default-targets-scrape-interval-settingsand the Monitor'sinterval; non-critical targets 60s. - Drop high cardinality:
metricRelabelingsofdrop/labeldrop; keep only the histogram buckets you need. - Logs: Logs and Events preset, namespace exclusion, lower application log levels, evaluate Basic/Auxiliary table plans.
- 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
--forcepermanent deletion (follow the official docs).
Least-privilege overview
| Operation | Minimum role (scope) |
|---|---|
| Create AKS / workspace / Grafana / Log Analytics | Contributor (resource group) |
| Link Grafana during enablement (roles assigned automatically) | Owner, or Contributor + User Access Administrator |
| Create rule groups | Monitoring Contributor (resource group) |
| View monitoring data (portal) | Monitoring Reader / Monitoring Contributor |
| PromQL reads of the workspace | Monitoring Data Reader (workspace) |
| Access the Grafana UI | Grafana Viewer / Editor / Admin (Grafana instance) |
| Assign Grafana roles to others | Role Based Access Control Administrator / User Access Administrator / Owner |
Cost composition diagram
Cleanup order diagram
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.
Cost and cleanup commands
| Command | Purpose | Notes |
|---|---|---|
curl prices.azure.com/api/retail/prices?$filter=… | Query retail unit prices | Public API, no sign-in required |
az consumption usage list / portal cost analysis | View actual spend | Filter by resource group rg-prom-lab |
az alerts-management prometheus-rule-group update --enabled false | Disable rules before deleting | Avoid false alerts |
az group delete -n rg-prom-lab --yes | Delete all lab resources | Not recoverable (except LAW soft delete) |
az group list --query "[?starts_with(name,'MA_')…]" | Check for managed / default resource group leftovers | Delete after confirming |
kubectl config delete-context aks-prom-lab | Clean up the local kubeconfig | Also 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)
rg-prom-lab filter (cost data usually lags by several hours).DefaultRG-canadacentral, delete it after confirming that no other cluster uses it.~/promlab/azure keep the YAML/JSON in the local folder so it can be reused in Lesson 6.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.
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 tableA 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
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.
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.
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.
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.
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.
Command cheat sheet
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 documentationWorkspace 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-insensitiveManaged 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 tableTroubleshooting (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
| Symptom | Most likely cause | First command |
|---|---|---|
| Nothing at all | Add-on not running / DCR/DCE missing | kubectl get pods -n kube-system | grep ama-metrics |
| myapp missing, default metrics present | Wrong API group, unnamed port, selector mismatch | kubectl get podmonitors.azmonitoring.coreos.com -A |
| up=1 but a metric is missing | Minimal ingestion keep list / metricRelabelings | debug mode :9091/metrics |
| Intermittent data gaps | Quota throttling / node-upgrade gap | Workspace % Utilization metrics |
| Grafana 403 | Managed identity lacks Monitoring Data Reader | az role assignment list --scope $AMW_ID |
| Rule does not fire | clusterName / scope inconsistent with data | az alerts-management prometheus-rule-group show |
| Alert has no email | Rule has no actions / recipient unsubscribed / alert processing rule | az monitor action-group show |
| ContainerLogV2 is empty | V2 not enabled / stream name wrong | az aks show --query addonProfiles.omsagent |
| Write 422 | Duplicate 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 = trueMonitor: drop high-cardinality labels
metricRelabelings:
- action: labeldrop
regex: 'user_id|session_id'
- sourceLabels: [__name__]
action: keep
regex: 'myapp_.*'Capstone lab + final quiz
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 -
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]"
kubectl apply -f ~/promlab/azure/myapp-podmonitor.yaml; in a collector replica :9090/targets shows 2 up targets.myapp-dashboard.json; grant one Entra group Grafana Viewer.ag-prom-lab and myapp-rules; keep loadgen with /error, and after about 6–8 minutes receive MyAppHigh5xxRatio; after changing loadgen, receive Resolved.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.metrics, confirm MyAppPodsMissing fires within 3–5 minutes; auto-resolves after recovery.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
| Topic | Verified conclusion | Source |
|---|---|---|
| Enabling managed Prometheus | az 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 Administrator | Enable monitoring for AKS(ms.date 2026-08-18, updated 2026-11-10) |
| Container Insights | az 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-rs | same as above |
| new az aks parameters | appears 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 parameters | az aks CLI reference(accessed 2026-11-15) |
| Default targets and minimal ingestion | Enabled 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 Grafana | Default Prometheus metrics configuration(2026-08-18) |
| settings ConfigMap | ama-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_sms | Customize scraping using ConfigMap(updated 2026-10-13) · official template(retrieved 2026-11-15) |
| custom scrape ConfigMap | ama-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-secret | Custom scrape jobs using ConfigMap(updated 2026-07-17) |
| PodMonitor / ServiceMonitor | API 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) |
| Troubleshooting | Pods: 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 upgrades | Troubleshoot Prometheus metrics(updated 2025-06-19) |
| Query API | token 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 supported | Query Prometheus metrics using API and PromQL(updated 2025-10-01) |
| Rule groups | Type 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 alerts | Portal 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-31 | Recommended 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 create | az monitor action-group(2026-11-06) |
| Azure Monitor workspace CLI | az monitor account create/show/delete is the core CLI (GA) | az monitor account(2026-11-06) |
| Managed Grafana tiers | Essential 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 optional | What is Azure Managed Grafana?(2026-06-24) |
| Grafana roles | Grafana Admin / Editor / Limited Viewer / Viewer (including role IDs); Limited Viewer corresponds to “No Basic Role”, not applicable to v9; assignment requires RBAC Administrator / UAA / Owner | Grant users and identities access(2026-09-22) |
| Link workspace | Assign 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 dashboards | Add an Azure Monitor workspace(2026-07-03) |
| az grafana CLI | amg 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/migrate | az grafana(2026-09-01) · CLI quickstart |
| Pricing | canadacentral (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/message | Azure 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.
promconfigvalidatoroutput text, some JSON field names of rule groups / data sources, the CLI internal names of workspace utilization metrics,ama-metricslabel 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 createthe 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-tokenquerying the workspace directly with a user token (the official examples use app registration);--rules @filesyntax;az grafana dashboard importrequirements 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.