Prometheus & Grafana 第 3 课:走向云平台(Azure)
- 能说清 自建 Prometheus、Azure Monitor 托管 Prometheus、Container Insights 三者的边界与组合方式,并为一个 AKS 团队做出有理由的架构选型。
- 用
az aks update --enable-azure-monitor-metrics把 AKS 集群aks-prom-lab接入 Azure Monitor 工作区amw-prom-lab,能指出集群里多出来的ama-metrics*组件各自做什么、数据怎样带着托管标识令牌写进工作区。 - 用三种方式抓取 myapp(端口 5000,
myapp_http_requests_total等统一指标):PodMonitor / ServiceMonitor(组azmonitoring.coreos.com/v1)、ama-metrics-prometheus-configConfigMap、Pod 注解;会调整ama-metrics-settings-configmap(最小采集配置、keep list、cluster_alias)。 - 创建 Azure Managed Grafana
amg-prom-lab,理解两条身份链:人 → Entra ID → Grafana Admin/Editor/Viewer;Grafana 托管标识 → Monitoring Data Reader → 工作区查询端点。 - 把第 2 课的 Prometheus 规则改写为 托管 Prometheus 规则组(
Microsoft.AlertsManagement/prometheusRuleGroups),通过 Action Group 发邮件;启用推荐告警。 - 用 Container Insights(
ContainerLogV2、KubeEvents、KubePodInventory)把日志与指标对上同一个时间点;能独立排查“没有数据 / 403 / 规则不触发 / 被限流”等云上故障,并能估算费用、按清单清理资源。
1 小时时间分配表
| # | 时间 | 模块 | 核心内容 | 动画 / 交互 | 实验(AKS aks-prom-lab) |
|---|---|---|---|---|---|
| 0 | 课前 | 热身与 AKS 准备 | 资源提供程序、变量、ACR + AKS、把 myapp 推到 ACR 并部署 | 环境自检清单 | myapp 在 AKS 上 /metrics 可访问 |
| 1 | 00–05 | Azure 上的监控架构选型 | 自建 kps / 托管 Prometheus / Container Insights / 混合 remote_write;责任边界 | 需求 → 架构推荐器 | 画出本课目标架构、列出资源清单 |
| 2 | 05–13 | 托管 Prometheus 与 AKS 集成 | Azure Monitor 工作区、DCR/DCE、ama-metrics 组件、默认目标与最小采集、控制面指标 | 核心动画:托管采集 → 工作区 → Grafana 的数据与身份流 | 创建 amw-prom-lab 并启用指标 |
| 3 | 13–21 | 抓取配置:ConfigMap、PodMonitor、ServiceMonitor | 四种抓取入口、target allocator、settings ConfigMap、promconfigvalidator、标签限制 | 抓取配置诊断模拟器 | PodMonitor 抓 myapp,验证 targets |
| 4 | 21–29 | Managed Grafana:身份、权限与数据源 | Standard X1/X2、Entra 登录、Grafana 角色、系统托管标识、Monitoring Data Reader、预置仪表板 | 两条身份链逐跳动画(可“拔掉”角色看报错) | 创建 amg-prom-lab 并做 myapp 仪表板 |
| 5 | 29–37 | 托管告警规则组与 Action Group | 规则组作用域、record/alert、for/severity/autoResolve、Action Group、推荐告警、规则转换工具 | 告警时间线模拟器 | 5xx 告警 → 邮件 → 自动解决 |
| 6 | 37–45 | Container Insights、日志与指标关联 | ama-logs、DCR 流、成本预设、ContainerLogV2、KQL、Grafana 中并排关联 | 指标尖峰 → 同时间窗日志 | 启用“日志与事件”预设,KQL 查 myapp 错误 |
| 7 | 45–54 | 云上排错实战 | 没有数据、403、规则不触发、限流、大小写不敏感、422 重复序列 | 故障注入:哪一跳断了 | 5 个故障复现与修复 |
| 8 | 54–60 | 成本、清理与自测 | 计量项与估算、降本手段、权限最小化、清理顺序与残留资源 | 费用计算器 + 排障决策树 | 估算本实验费用并完整清理 |
| — | 课后 | 速查表 · 综合实验 | 一键脚本从零搭出完整托管监控链路并验收 | 结业测验(12 题) | 综合实验 |
知识覆盖矩阵 Knowledge Coverage Matrix
| 目标技能 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | 关键命令 | 实验 |
|---|---|---|---|---|---|---|---|---|---|---|
| 为 AKS 选择监控架构 | ✓ | ✓ | · | · | · | ✓ | · | ✓ | — | M1 架构图 |
| 启用托管 Prometheus | · | ✓ | · | · | · | · | ✓ | · | az monitor account create、az aks update --enable-azure-monitor-metrics | M2 |
| 抓取自定义应用指标 | · | · | ✓ | · | · | · | ✓ | · | kubectl apply PodMonitor、kubectl create configmap ama-metrics-prometheus-config | M3 |
| 控制采集量与基数 | · | ✓ | ✓ | · | · | · | ✓ | ✓ | ama-metrics-settings-configmap、metricRelabelings | M3 / M8 |
| Grafana 身份与权限 | · | · | · | ✓ | · | · | ✓ | ✓ | az grafana create、az role assignment create | M4 |
| PromQL 查询与仪表板 | · | ✓ | ✓ | ✓ | ✓ | ✓ | · | · | az grafana dashboard import、查询 API | M4 |
| 托管规则与通知 | · | · | · | · | ✓ | · | ✓ | · | az alerts-management prometheus-rule-group create、az monitor action-group create | M5 |
| 日志与指标关联 | · | · | · | ✓ | · | ✓ | ✓ | · | az aks enable-addons --addon monitoring、KQL | M6 |
| 云上故障定位 | · | ✓ | ✓ | ✓ | ✓ | · | ✓ | ✓ | kubectl logs -c prometheus-collector/config-reader/addon-token-adapter | M7 |
| 费用估算与清理 | ✓ | · | · | · | · | ✓ | · | ✓ | az group delete、零售价格 API | M8 |
本课排除的内容(以及在哪里学)
| 主题 | 为什么不在本课 | 去哪里学 |
|---|---|---|
PromQL 基础、抓取周期、rate() 原理 | 第 1 课已讲,本课直接使用 | 第 1 课 |
| Alertmanager 路由树、抑制、静默 | 托管路径中由 Azure Monitor 告警 + Action Group 替代,概念对照见模块 5 | 第 2 课 |
| AWS 托管服务(AMP / AMG / ADOT) | 属于另一朵云 | 第 4 课 |
| kube-prometheus-stack、Prometheus Operator 调和细节 | 本课只用托管附加组件;自建栈在 kind 上讲更透彻 | 第 5 课 |
| 远程写入到 Azure Monitor 工作区(自建 Prometheus remote_write + 托管标识 sidecar)、Azure Arc 集群 | 属于混合/迁移架构,模块 1 只做定位 | 第 6 课 · 官方:remote-write |
| Application Insights / OpenTelemetry 链路追踪 | 超出“指标 + 日志”范围 | 官方:AKS OTLP |
| Bicep/Terraform 全量 IaC 化本课资源 | 本课用 az CLI 让每一步可见 | Terraform 课第 3 课;官方 Bicep 模板见模块 2 链接 |
如何使用本课件
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。先看“原理”和“动画”,再做“实验”;云上实验会产生费用,按模块 8 的清单清理。
测验得分 ≥ 70% 或点击“标记本模块完成”即计入进度,保存在本浏览器(禁止本地存储时刷新后会清空)。
“语音”分页用浏览器内置 Web Speech API(zh-CN)朗读讲解稿;没有中文语音包时讲解稿仍可阅读或交给 TTS 工具。
--enable-azure-monitor-metrics / --azure-monitor-workspace-resource-id / --grafana-resource-id / --enable-control-plane-metrics;自定义抓取 ConfigMap ama-metrics-prometheus-config(以及 -node、-node-windows)与设置 ConfigMap ama-metrics-settings-configmap(schema v2);PodMonitor/ServiceMonitor 的 API 组 azmonitoring.coreos.com/v1;规则组 API 2023-03-01;Managed Grafana 新建只能选 Standard(Essential 已不可新建,2027-03-31 完全弃用)。价格取自 Azure 零售价格 API(canadacentral,USD)。Managed Grafana 当前可选的 Grafana 主版本请以 az grafana show 与官方文档为准(文档已出现 Grafana 13 的数据源迁移说明)。第 1、2 课与本课并行编写,跨课引用以课程统一约定为准(myapp 端口 5000、指标名 myapp_*)。模块 0 · 热身与 AKS 准备(课前完成)
- 已完成 第 1 课 与 第 2 课:本机
~/promlab中有 myapp 源码(暴露myapp_http_requests_total{method,route,status}、myapp_http_request_duration_seconds、myapp_redis_up)和第 2 课写过的告警规则prometheus/rules/*.yml。 - 工具:Azure CLI(
az version,建议最新;az grafana属于amg扩展,az alerts-management属于alertsmanagement扩展,首次使用会自动提示安装)、kubectl、jq。Docker 课与 K8s 课已经装好这些工具。 - Azure 权限:对订阅或资源组
rg-prom-lab拥有 Owner,或 Contributor + User Access Administrator(关联 Grafana 时需要给它的托管标识分配角色)。查看数据需要 Monitoring Reader / Monitoring Contributor。 - 若本机没有 Docker,可用
az acr build在云端构建镜像(本课默认这样做)。
步骤 1:变量与资源提供程序
本课所有命令都引用下面这组变量。Managed Grafana 与 ACR 的名称需要全局唯一,所以加一个随机后缀;请把后缀记下来,新开终端时重新导出这些变量。
# ~/promlab/azure/env.sh —— 每次新开终端先 source 它
export SUFFIX=${SUFFIX:-$RANDOM} # 第一次运行后请把值写死在这里
export RG=rg-prom-lab
export LOC=canadacentral
export AKS=aks-prom-lab
export AMW=amw-prom-lab
export AMG=amg-prom-lab-$SUFFIX # 全局唯一(课程约定名 amg-prom-lab + 后缀)
export ACR=acrpromlab$SUFFIX # 只能小写字母数字
export LAW=law-prom-lab # Log Analytics 工作区(模块 6)
export AG=ag-prom-lab # Action Group(模块 5)
export ALERT_EMAIL=you@example.com # 改成你的邮箱
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
# 托管 Prometheus / Grafana / 告警需要的资源提供程序(官方前提条件)
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 扩展(若装过:az extension remove --name aks-preview),集群必须使用托管标识(CLI 2.49.0 起默认)。步骤 2:资源组、ACR 与 AKS(先不启用任何监控)
故意先建一个“裸”集群,模块 2 再用 az aks update 启用托管 Prometheus,这样你能亲眼看到启用前后 kube-system 里多了什么。
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
不指定 --kubernetes-version 时使用该区域的默认版本;版本号以 az aks get-versions -l $LOC -o table 为准(K8s 课第 6 课已核实 AKS 1.37 于 2026-10 GA)。
步骤 3:构建 myapp 镜像并推送到 ACR
如果第 1 课的 ~/promlab/myapp 已经存在,直接构建;否则用下面这份最小版本(与课程统一约定的指标名完全一致)。gunicorn 多进程下每个 worker 有独立内存,必须用 PROMETHEUS_MULTIPROC_DIR 让 prometheus_client 把样本写到共享目录再合并。
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 # 每次启动清空多进程目录,避免旧 worker 的文件残留 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
步骤 4:在命名空间 myapp 部署 myapp + Redis
注意两点,后面模块 3 都要用到:① 容器端口命名为 http(PodMonitor/ServiceMonitor 要求“named port”);② Pod 与 Service 都带标签 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
步骤 5:给 myapp 一个持续的流量发生器
托管服务的数据有 1–2 分钟的端到端延迟,持续流量能让你在每个模块都看到“活”的曲线。约 10% 的请求打到 /error,为模块 5 的告警做准备。
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
热身:凭记忆回答(30 秒)
第 1 课里 Prometheus 怎么知道 myapp 在哪里?
通过 scrape_configs(Compose 里是 static_configs 的 myapp:5000)。在 K8s 上会换成 kubernetes_sd_configs 或 Operator 的 ServiceMonitor/PodMonitor——本课托管版本用的是同一套概念,只是 API 组换成了 azmonitoring.coreos.com。
第 2 课里一条告警从 firing 到邮件,经过了哪些组件?
Prometheus 规则评估(pending → firing)→ 推送给 Alertmanager → 路由树分组/抑制/静默 → receiver(邮件/Webhook)。托管版本中,“规则评估”由规则组完成,“Alertmanager”换成了 Azure Monitor 告警 + Action Group(模块 5)。
Prometheus 自己存数据,托管服务把数据存哪?
存进 Azure Monitor 工作区(资源类型 Microsoft.Monitor/accounts),集群里只运行“代理模式”的采集器,不保留本地 TSDB(模块 2 详解)。
az aks stop -g $RG -n $AKS(停止后不收节点计算费,磁盘等仍计费,以官方为准);学完立即执行模块 8 的清理。模块 1 · Azure 上的监控架构选型
- 列出 Azure 上 AKS 监控的四种常见架构,并说出每种架构里“采集 / 存储 / 查询 / 告警 / 身份”分别由谁负责。
- 理解 Azure Monitor 工作区、Log Analytics 工作区、Managed Grafana 三种资源的分工,以及为什么它们是三个独立资源。
- 能根据保留期、团队技能、多集群、合规、成本等需求给出有理由的推荐。
What:Azure 上的四种拼法
| 架构 | 采集 | 存储 | 查询 / 可视化 | 告警 |
|---|---|---|---|---|
| A. 自建:kube-prometheus-stack 跑在 AKS 里 | Prometheus(Operator) | 集群内 TSDB + PV(可加 Thanos/Mimir) | 自建 Grafana | 自建 Alertmanager |
| B. 全托管(本课主线) | AKS 附加组件 ama-metrics(Azure Monitor agent 的容器化版本,以代理模式运行 Prometheus 抓取) | Azure Monitor 工作区(Microsoft.Monitor/accounts) | Azure Managed Grafana(Microsoft.Dashboard/grafana)或门户内置 Grafana 视图 | Prometheus 规则组 → Azure Monitor 告警 → Action Group |
| C. 混合:自建 Prometheus + remote_write | 自建 Prometheus | 本地短保留 + 远程写入 Azure Monitor 工作区 | Managed Grafana / 自建均可 | 两边都可 |
| D. 仅 Container Insights(日志为主) | ama-logs | Log Analytics 工作区(KQL 表) | 门户 Insights 视图、工作簿 | 日志搜索告警 / 平台指标告警 |
官方推荐的 AKS 完整监控是 B + D 的组合:指标走托管 Prometheus,日志与事件走 Container Insights,并且 Container Insights 的成本预设里专门有“Logs and Events”分组,注明“启用了托管 Prometheus 时推荐”——即性能指标交给 Prometheus,Log Analytics 只收日志和事件,避免同一指标双份付费。
Why:为什么要托管
- 存储运维外包:不再管理 TSDB 磁盘、压缩、WAL、远程存储与长期保留;工作区按“摄取样本数 + 查询处理样本数”计费,而不是按磁盘与节点。
- 身份统一:采集端用集群托管标识写入,Grafana 用自己的托管标识读取,人用 Entra ID 登录 Grafana——不再有 basic auth 密码和长期 API Key。
- 告警进入 Azure Monitor 体系:与平台指标告警、日志告警共享 Action Group、告警处理规则(维护窗口静默)、ITSM 集成。
- 代价:可定制性下降(例如不支持重命名指标、ConfigMap 不支持全局 external_labels、查询必须带
__name__匹配器、系统对大小写不敏感),并受工作区配额限制(活动时间序列、每分钟事件数)。
How:资源与责任边界
| 资源 | 类型 | 本课名称 | 里面装什么 |
|---|---|---|---|
| Azure Monitor 工作区 | Microsoft.Monitor/accounts | amw-prom-lab | Prometheus 时间序列;创建时自动生成同名 DCR 与 DCE,放在托管资源组 MA_amw-prom-lab_canadacentral_managed |
| Log Analytics 工作区 | Microsoft.OperationalInsights/workspaces | law-prom-lab | ContainerLogV2、KubeEvents、KubePodInventory 等 KQL 表 |
| Azure Managed Grafana | Microsoft.Dashboard/grafana | amg-prom-lab-<后缀> | 仪表板、数据源、Grafana 告警(Standard);系统分配托管标识 |
| Prometheus 规则组 | Microsoft.AlertsManagement/prometheusRuleGroups | myapp-rules 等 | record / alert 规则,作用域 = 工作区(+ 可选集群) |
| Action Group | Microsoft.Insights/actionGroups | ag-prom-lab | 邮件、短信、Webhook、Logic App、ITSM 等接收方 |
When:怎么选
- 团队已有成熟的自建 Prometheus 运维能力、需要 Thanos/Mimir 的多租户与全局视图、或者必须离线/私有化 → A 或 C。
- 多个 AKS 集群、希望统一身份与告警、平台团队人手有限、能接受托管服务的限制 → B(+D 日志)。
- 迁移期:保留现有 Prometheus 规则与仪表板,先 remote_write 到工作区 → C,再逐步切到 B。
- 只关心“Pod 起没起来、日志里报什么错” → D 起步,但指标仪表板与 PromQL 告警最终仍建议用 B。
与相似技术对比
| Azure 托管(本课) | AWS 托管(第 4 课) | 自建 kps(第 5 课) | |
|---|---|---|---|
| 采集器 | AKS 附加组件 ama-metrics(DaemonSet + 副本 + target allocator) | AMP 托管 scraper 或 ADOT / 自建 Prometheus remote_write | Prometheus Operator 管理的 Prometheus |
| 存储 | Azure Monitor 工作区 | AMP 工作区 | 本地 TSDB + PV |
| 写入身份 | 集群托管标识(Entra 令牌) | IAM 角色 + SigV4 | 无(本地) |
| 可视化 | Managed Grafana(Entra 登录) | AMG(IAM Identity Center) | 自建 Grafana |
| 告警 | 规则组 → Azure Monitor 告警 → Action Group | AMP 规则 + AMP Alertmanager → SNS | PrometheusRule → Alertmanager |
架构图:本课的目标架构(B + D)
对照图:本机 Compose(第 1、2 课)→ Azure 托管(本课)
交互:需求 → 架构推荐器
勾选你的团队需求,推荐器按“谁来负责存储、身份、告警”给出得分。每条需求下方的解释说明它为什么让某种架构加分或减分——这就是架构评审会上要讲清楚的理由。
本模块的“侦察”命令
选型前先摸清现状:订阅里已有哪些工作区、Grafana、规则组,集群是否已经启用了某种监控。
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
az monitor account list | 列出 Azure Monitor 工作区 | -g 过滤资源组;注意 DefaultAzureMonitorWorkspace-* 是不指定工作区时自动创建的 |
az monitor log-analytics workspace list | 列出 Log Analytics 工作区 | DefaultWorkspace-* 同理 |
az grafana list | 列出 Managed Grafana | 需要 amg 扩展 |
az aks show --query azureMonitorProfile | 集群是否启用托管 Prometheus | metrics.enabled |
az aks show --query addonProfiles.omsagent | 是否启用 Container Insights(monitoring 附加组件) | config.logAnalyticsWorkspaceResourceID |
az resource list --resource-type Microsoft.AlertsManagement/prometheusRuleGroups | 列出 Prometheus 规则组 | 清理时常用 |
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
}
如何验证:两项都是 null/false 说明集群是“裸”的。常见错误:别的同事用门户“一键启用”时没选工作区,会在 DefaultRG-<region> 里生成默认工作区——费用与数据都落在那里,审计时容易漏掉。生产用途:把这几条命令放进平台巡检脚本,发现“有集群没监控”或“默认工作区”就报警。
查看可用区域与 SKU
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
两项都应包含 Canada Central。如果你的区域不支持 Managed Grafana,可以把 Grafana 放在邻近区域——它只是查询端,跨区域查询会有少量延迟与出站流量。
实验 1:画出你的目标架构并列出资源清单(约 4 分钟)
amw-prom-lab。~/promlab/azure/ARCHITECTURE.md,后面模块逐项打勾):
目标:架构 B(托管 Prometheus + Managed Grafana)+ D(Container Insights:仅日志与事件) - [ ] Azure Monitor 工作区 amw-prom-lab(canadacentral) 模块 2 - [ ] AKS aks-prom-lab 启用 azureMonitorProfile.metrics 模块 2 - [ ] myapp 抓取:PodMonitor azmonitoring.coreos.com/v1 模块 3 - [ ] Managed Grafana amg-prom-lab-<后缀>(Standard X1) 模块 4 - [ ] Grafana MI → Monitoring Data Reader @ amw-prom-lab 模块 4 - [ ] 规则组 myapp-rules + Action Group ag-prom-lab 模块 5 - [ ] Log Analytics law-prom-lab + monitoring 附加组件(Logs and Events) 模块 6 - [ ] 清理:az group delete + 检查 MA_*_managed / DefaultRG-* 模块 8
案例 1:30 个 AKS 集群的平台团队从自建迁到托管
问题:每个集群一套 kube-prometheus-stack,Prometheus 内存随节点数暴涨,Thanos sidecar 与对象存储维护成本高,Grafana 账号靠手工分发。做法:按“环境 × 区域”建 4 个 Azure Monitor 工作区,所有集群启用 --enable-azure-monitor-metrics 指向对应工作区;一个 Managed Grafana Standard 连接 4 个工作区;Grafana 角色绑定到 Entra 组(Grafana Admin 给平台组,Viewer 给应用团队)。配置:Azure Policy 强制新集群启用指标附加组件(官方提供策略模板)。限制:原来的 PrometheusRule 需要用 az-prom-rules-converter 转成规则组;自定义的 recording rule 名字里有大小写差异的需要统一(工作区大小写不敏感)。
案例 2:金融客户要求 13 个月保留与私网访问
问题:审计要求指标保留超过一年,且所有访问走私网。做法:采用架构 B,工作区与 Grafana 都开启私有终结点(Grafana 私有终结点仅 Standard 支持),集群通过 Azure Monitor Private Link Scope 写入。限制:官方故障排查文档指出,私有 AKS 集群若同时被链接到其他服务的 AMPLS,会出现 “No configuration present for the AKS resource” —— 网络设计要先按官方 Private Link 文档评审。保留期、配额以 Azure Monitor 服务限制页为准。
案例 3:迁移期的混合架构
问题:业务团队有上百个 Grafana 仪表板绑定在自建 Prometheus 数据源上,不能一夜切换。做法:架构 C:自建 Prometheus 保留 15 天本地数据,同时 remote_write 到 Azure Monitor 工作区;Managed Grafana 中新增“托管 Prometheus”数据源,用 az grafana backup/restore --remap-data-sources 迁移仪表板。限制:双写期间费用叠加;同一集群若同时启用附加组件与 remote_write 会产生重复序列(可能出现 422),必须区分 cluster 标签或只保留一条写入路径。
选型阶段的常见“坑”
启用后数据进了 DefaultAzureMonitorWorkspace-canadacentral(DefaultRG-canadacentral)
原因:启用时没有指定 --azure-monitor-workspace-resource-id,官方行为是使用资源组默认工作区,不存在时在 DefaultRG-<cluster_region> 中创建 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
修复:先 az aks update --disable-azure-monitor-metrics,再带上正确的工作区 ID 重新启用(模块 2);确认无其他集群使用后删除默认工作区。
门户提示:You can't create new Essential workspaces
原因:Managed Grafana Essential 层已不能新建,现有实例计划在 2027-03-31 完全弃用。
修复:新建一律 Standard(CLI --sku-tier 默认值就是 Standard);存量 Essential 按官方迁移指南迁移。
Resource 'amw-prom-lab' was disallowed by policy
原因:组织的命名/标签策略拦截了工作区,或拦截了随工作区自动创建的 DCR/DCE(名称固定,位于 MA_<工作区名>_<区域>_managed 资源组,不能改名)。
az policy assignment list --query "[].{name:displayName,scope:scope}" -o table
修复:官方建议为托管资源组与 DCR/DCE 设置策略豁免(exemption)。
集群同时装了自建 kube-prometheus-stack,担心 CRD 冲突
原因分析:附加组件的 CRD 是 azmonitoring.coreos.com 组,与开源的 monitoring.coreos.com 不冲突;附加组件不会读取开源组的 ServiceMonitor(官方说明这是有意的隔离)。
kubectl get crd | grep -E 'coreos.com'
修复:无需修复;但迁移时要为需要托管采集的目标复制一份 azmonitoring.coreos.com/v1 版本的 Monitor。
1. 一条命令判断集群 aks-prom-lab 是否启用了托管 Prometheus 和 Container Insights。
az aks show -g rg-prom-lab -n aks-prom-lab --query "{metrics:azureMonitorProfile.metrics.enabled, ci:addonProfiles.omsagent.enabled}" -o json2. 列出订阅中所有“默认”Azure Monitor 工作区,找出谁在“无意中”付费。
az monitor account list --query "[?starts_with(name,'DefaultAzureMonitorWorkspace')].{name:name,rg:resourceGroup,loc:location}" -o table一个 5 人应用团队只有 1 个 AKS 集群,没有专职 SRE,需要 PromQL 告警和 3 个仪表板,日志只看错误。你推荐哪种架构?要提醒他们注意什么?
推荐 B + D(托管 Prometheus + Managed Grafana Standard X1 + Container Insights 的 Logs and Events 预设):没有存储运维负担,身份统一。提醒:① Grafana 按实例小时 + 活跃用户计费,小团队也有固定成本,可评估门户内置 Grafana 视图是否够用;② 默认最小采集只保留仪表板/推荐告警用到的指标,自定义指标要自己配置抓取;③ 日志按 GB 计费,使用命名空间过滤与 ContainerLogV2;④ 规则组与 Action Group 都是 ARM 资源,纳入 IaC。
经核实的教学视频
官方文档
- Enable monitoring for AKS clusters
- Azure Monitor managed service for Prometheus overview
- What is Azure Managed Grafana?
视频分镜脚本(约 75 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:左侧是本机 Compose 五个容器,右侧是 Azure 门户里的五个资源图标,中间用箭头一一连接。
旁白:本机的 Prometheus、Alertmanager、Grafana,到了 Azure 上各自都有一个托管对应物。
画面:四张卡片 A 自建、B 全托管、C 混合、D 仅日志,逐张翻开显示“采集、存储、告警、身份”四格。
旁白:选型的关键不是功能清单,而是责任边界:谁维护存储,谁管理身份,谁发告警。
画面:B 和 D 两张卡片合并,Container Insights 的成本预设高亮“日志与事件”。
旁白:官方推荐指标交给托管 Prometheus,日志交给 Container Insights,性能数据不要双份付费。
画面:本课资源清单逐项出现:amw、amg、规则组、Action Group、law。
旁白:接下来五十五分钟,我们把这张清单逐项变成真实资源,最后再全部清理掉。
模块 2 · Azure Monitor 托管 Prometheus 与 AKS 集成
- 创建 Azure Monitor 工作区并读懂它自动生成的 DCR / DCE 与托管资源组。
- 用
az aks update --enable-azure-monitor-metrics --azure-monitor-workspace-resource-id启用托管采集,说出ama-metrics(副本)、ama-metrics-node(DaemonSet)、ama-metrics-ksm、ama-metrics-operator-targets的职责。 - 理解“最小采集配置(minimal ingestion profile)”和默认目标,知道
cluster标签从哪里来,知道控制面指标要额外加--enable-control-plane-metrics。 - 用 PromQL 查询 API 直接查询工作区(令牌受众
https://prometheus.monitor.azure.com,角色 Monitoring Data Reader)。
What:托管 Prometheus 由哪些部分组成
- Azure Monitor 工作区(
Microsoft.Monitor/accounts):时序存储与 PromQL 查询端点(形如https://amw-prom-lab-xxxx.canadacentral.prometheus.monitor.azure.com)。创建时自动生成一个同名的数据收集规则(DCR)和数据收集终结点(DCE),放在托管资源组MA_<工作区名>_<区域>_managed,名称不可修改。 - 指标附加组件(集群内
kube-system,容器化的 Azure Monitor agent):ama-metrics-*(ReplicaSet,集群级采集):抓取 kube-state-metrics、ama-metrics-prometheus-config里的自定义任务、以及 PodMonitor/ServiceMonitor 发现的目标。ama-metrics-node-*(DaemonSet,每节点一个):抓取本节点的 kubelet、cAdvisor、node-exporter 以及ama-metrics-prometheus-config-node里的任务。ama-metrics-ksm-*:附加组件自带的 kube-state-metrics。ama-metrics-operator-targets-*:target allocator,读取配置与 CRD,把目标分配给采集副本(容器config-reader、targetallocator)。
prometheus-collector(基于 OpenTelemetry Collector 的 Prometheus 接收器 + MetricsExtension 写入组件)和addon-token-adapter(用集群托管标识换取写入令牌)。Pod 的 9090 端口提供“Prometheus Agent 模式”的 UI,可看/config、/service-discovery、/targets。 - 集群侧数据收集关联:启用时还会为集群创建把它与工作区 DCR/DCE 连接起来的关联与规则(名称、位置以实际
az monitor data-collection rule list输出为准)。
Why:为什么是“代理模式 + 远端存储”
集群内不保留 TSDB,就不再有 PV 容量、WAL 回放、压缩、保留期这些第 7 课要讲的运维问题;采集器可以无状态地重启与扩缩(官方提供采集副本的 HPA 与高规模指南)。代价是查询必须去工作区,端到端有 1–2 分钟延迟;节点升级时集群级采集器所在节点重启会产生 1–2 分钟数据空洞(官方说明推荐告警不受影响)。
How:一个样本的旅程
- target allocator 根据默认目标 + ConfigMap + CRD 生成抓取任务并分配给采集副本。
prometheus-collector按scrape_interval(默认目标 30s)对目标发GET /metrics,套用 relabel 与最小采集的 keep list,追加cluster标签(默认为集群资源 ID 的最后一段aks-prom-lab,可用cluster_alias覆盖)。addon-token-adapter用集群的托管标识向 Entra ID 获取令牌;MetricsExtension 带令牌把样本批量 POST 到工作区 DCE 的摄取端点,DCR 决定数据流入哪个工作区。- 工作区按“活动时间序列数”和“每分钟事件数”配额接收数据,超出会被限流(模块 7)。
- 查询方(Grafana、规则组、API)带着自己的令牌(受众
https://prometheus.monitor.azure.com)访问查询端点,RBAC 角色 Monitoring Data Reader 决定能否读。
默认采集了什么
| 类别 | 目标 | 说明 |
|---|---|---|
| 默认启用 | cadvisor、nodeexporter、kubelet、kube-state-metrics、networkobservabilityRetina | 每 30 秒;最小采集配置默认开启:只保留默认仪表板、默认 recording rule 与推荐告警用到的指标,其余在 relabel 阶段丢弃 |
| 默认禁用 | coredns、kubeproxy、apiserver | 在 ama-metrics-settings-configmap 中开启 |
控制面(需 --enable-control-plane-metrics) | apiserver、etcd(默认);scheduler、controller-manager、cluster-autoscaler 等需另开 | 属于 settings ConfigMap 的 controlplane-metrics 段 |
| 自动配置 | 默认 recording rules(如 instance:node_cpu_utilisation:rate5m)、ux:* 可视化规则 | 以规则组资源的形式创建;链接 Grafana 后自动预置 “Kubernetes / Compute Resources / …” 等仪表板 |
When:什么时候需要额外参数
- 想在
kube_pod_labels中看到业务标签(如app)→--ksm-metric-labels-allow-list "pods=[app]"(也可在 settings ConfigMap 的ksm-config中覆盖)。 - 需要 API Server/etcd 指标 →
--enable-control-plane-metrics(需已启用或同时启用托管 Prometheus)。 - Windows 节点仪表板 →
--enable-windows-recording-rules。 - 启用时顺手链接 Grafana →
--grafana-resource-id(执行者需要 Owner 或 Contributor + User Access Administrator,模块 4 详解)。
与相似技术对比
| 托管附加组件 | 自建 Prometheus(第 1 课) | Prometheus Agent 模式 + remote_write | |
|---|---|---|---|
| 本地存储 | 无(仅发送缓冲) | TSDB(head + WAL + block) | 仅 WAL |
| 规则评估 | 工作区侧规则组 | 本地 | 不支持(需远端) |
| 写入认证 | 集群托管标识,自动 | — | 自配(Azure 上可用托管标识 sidecar) |
| 升级 | 随 AKS 由微软管理 | 自己 | 自己 |
node_memory_MemAvailable_bytes 在,而很多 node_* 不在;需要时加 keep list 或关闭最小采集(会显著增加费用)。② “我的应用指标会被自动发现”——不会,默认只有 Pod 注解抓取的开关,而且命名空间正则默认为空;自定义目标要配置(模块 3)。③ “托管 Prometheus 区分大小写”——工作区不区分大小写,只差大小写的序列会被视为同一条。架构图:集群内的 ama-metrics 组件
数据与身份流:写入与读取是两条不同的身份
核心动画:托管采集 → Azure Monitor 工作区 → Managed Grafana 的数据与身份流
逐步播放一个 myapp 样本从 /metrics 到 Grafana 面板的全过程。每一步高亮真实组件,终端显示你能在对应位置观察到的命令、日志或 HTTP 请求。可以切换“故障”看链路在哪一跳断开。
核心命令与参数
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
az monitor account create | 创建 Azure Monitor 工作区(核心 CLI) | -n -g -l;可选 --public-network-access |
az monitor account show | 查看 ID、查询端点、默认 DCR/DCE | --query metrics.prometheusQueryEndpoint |
az aks update --enable-azure-monitor-metrics | 为现有集群启用托管 Prometheus | --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 | 采集 API Server / etcd 指标 | 需托管 Prometheus 已启用(或同一命令中启用) |
az aks update --disable-azure-monitor-metrics | 关闭附加组件 | 工作区与已存数据保留 |
kubectl get pods -n kube-system | grep ama-metrics | 检查组件 | 四类 Pod 应为 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 "(启用前:没有 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
如何验证:四类 Pod 都 Running;operator-targets 开头多一次重启属正常(官方说明)。常见错误:容器数量与名称可能随附加组件版本变化,以 kubectl get pod … -o jsonpath='{.spec.containers[*].name}' 为准。生产用途:用 Azure Policy 或 IaC 在建集群时就启用,并显式指定工作区,避免落进默认工作区。
直接用 PromQL API 查询工作区
# 给自己分配读取权限(数据面角色;分配后可能需要几分钟生效)
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
官方 API 文档的示例使用“应用注册 + client credentials”获取令牌(resource=https://prometheus.monitor.azure.com);上面用 az account get-access-token 获取当前用户令牌是同一受众,前提是你在工作区上有 Monitoring Data Reader。API 限制:查询必须带一个 __name__ 匹配器、/query_range 最长 32 天、/series 最长 12 小时、只支持 /api/v1/label/__name__/values。job 名称以你的实际输出为准。
可选:控制面指标
az aks update -g $RG -n $AKS --enable-control-plane-metrics
# 稍后在 Grafana Explore 中查询:
# sum by (code) (rate(apiserver_request_total{cluster="aks-prom-lab"}[5m]))
实验 2:创建工作区、启用托管采集、验证默认目标(约 7 分钟)
kube-system 部署附加组件,占用少量节点资源。MA_amw-prom-lab_canadacentral_managed 资源组:
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 标签选择器以实际为准;若 /api/v1/targets 不可用,浏览器打开 127.0.0.1:9090/targets(官方故障排查文档给出的 UI 路径)。
count by (job) (up{cluster="aks-prom-lab"});再查一条最小采集清单之外的指标,体会“被 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 结果为空——这是模块 3 要解决的问题。az aks update -g $RG -n $AKS --disable-azure-monitor-metrics;工作区用 az monitor account delete -n $AMW -g $RG。案例 1:用 Azure Policy 保证“每个集群都有指标”
问题:新集群由不同团队用不同模板创建,有的忘了开监控。做法:使用官方提供的 “Prometheus Metrics addon” 策略定义(DeployIfNotExists),按区域指定工作区;存量集群用修正任务(remediation)。限制:策略只负责启用附加组件,不负责应用的 PodMonitor 和规则组,这些仍需 GitOps 管理。
案例 2:多集群共用一个工作区时的 cluster 标签冲突
问题:两个资源组里各有一个名为 aks-prod 的集群写入同一工作区,偶发 422 错误,且仪表板把两个集群的数据混在一起。做法:在各自的 ama-metrics-settings-configmap 中设置 cluster_alias(只允许字母数字,其他字符会被替换为下划线),规则组的 clusterName 同步改为别名。限制:修改别名后历史数据仍是旧标签值,仪表板变量需要兼容一段时间。
案例 3:大集群采集副本 OOMKilled
问题:500 节点集群开了大量 ServiceMonitor,ama-metrics 副本反复 OOMKilled,数据断续。做法:按官方“高规模”指南拆分:节点级目标放到 ama-metrics-prometheus-config-node(DaemonSet 分担),启用采集副本 HPA;用 keep list 删掉不用的高基数指标。限制:DaemonSet 的自定义任务只能抓本节点目标($NODE_IP),不能用服务发现,否则每个节点都会抓全部目标并压垮 API Server。
常见错误与解决
No configuration present for the AKS resource(prometheus-collector 日志,每 5 分钟一次,Pod 每 15 分钟重启)
原因:附加组件找不到与集群关联的 DCR/DCE 配置:DCR/DCE 或工作区被删、关联缺失,或私有集群与 AMPLS 组合不受支持(官方故障排查文档列出的三种情况)。
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
修复:确认工作区与 DCR/DCE 存在;--disable-azure-monitor-metrics 后重新启用以重建关联。
(AuthorizationFailed) … does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/write'
原因:带 --grafana-resource-id 启用时,CLI 要为 Grafana 的托管标识分配角色,执行者只有 Contributor。
修复:由 Owner / User Access Administrator 执行,或先不带 Grafana 参数启用,再由有权限的人单独分配角色(模块 4)。
ama-metrics-node Pod CrashLoopBackOff,describe 显示 OOMKilled
原因:节点上抓取量过大(关闭了最小采集、cAdvisor 高基数、节点级自定义任务过多)。
kubectl describe pod -n kube-system POD | grep -A5 "Last State" kubectl top pod -n kube-system | grep ama-metrics
修复:恢复 minimal-ingestion-profile enabled = true,为确需的指标加 keep list;参考官方高规模指南。
ERROR: … aks-preview … / unrecognized arguments: --enable-azure-monitor-metrics
原因:Azure CLI 版本过旧,或装了与文档不一致的 aks-preview 扩展。
az version; az extension list -o table
修复:az upgrade;az extension remove --name aks-preview。
查询 API 返回 403 Forbidden / 401
原因:调用者在工作区上没有 Monitoring Data Reader(Contributor 是管理面角色,不含数据读取),或令牌受众不是 https://prometheus.monitor.azure.com。
az role assignment list --scope $AMW_ID --query "[].{who:principalName,role:roleDefinitionName}" -o table
修复:分配角色并等待生效;重新获取令牌。
1. 为现有集群 aks-prom-lab 启用托管 Prometheus,写入工作区 amw-prom-lab,并把 Pod 的 app 标签暴露到 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. 取出工作区的 PromQL 查询端点并查询 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]'
启用 10 分钟后,Grafana 里的“Kubernetes / Compute Resources / Cluster”有数据,但你查询 node_disk_io_now 为空,同事认为“托管 Prometheus 坏了”。你怎么解释并处理?
默认开启最小采集配置,node-exporter 只保留清单中的指标(如 node_disk_io_time_seconds_total),node_disk_io_now 不在清单中,在 relabel 阶段被丢弃,不是故障。处理:评估是否真的需要;需要时在 ama-metrics-settings-configmap 的 cluster-metrics → default-targets-metrics-keep-list 中加 nodeexporter = "node_disk_io_now"(保留最小采集),2–3 分钟后 ama-metrics Pod 重启生效;不要直接关闭最小采集,那会显著增加摄取量与费用。
经核实的教学视频
官方文档
- Enable monitoring for AKS clusters
- Default Prometheus metrics configuration
- Query Prometheus metrics using the API and PromQL
- Monitor AKS control plane metrics
视频分镜脚本(约 100 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:终端执行 az aks update,右侧 kube-system 中依次弹出四类 ama-metrics Pod。
旁白:一条命令,集群里多了四类组件:目标分配器、集群级采集副本、每节点的 DaemonSet,以及自带的 kube-state-metrics。
画面:一个橙色样本点从 myapp 的 /metrics 出发,经过采集器,旁边弹出“集群托管标识 → Entra 令牌”的钥匙图标。
旁白:采集器在代理模式下工作,不在集群里存数据。它用集群托管标识换取令牌,把样本写到数据收集终结点。
画面:DCE、DCR、工作区三块依次点亮,旁边显示托管资源组名 MA_amw-prom-lab_canadacentral_managed。
旁白:数据收集规则决定数据进入哪个 Azure Monitor 工作区,工作区负责存储和 PromQL 查询端点。
画面:Grafana 图标带着另一把钥匙访问查询端点,门口写着 Monitoring Data Reader;去掉角色时门口亮起 403。
旁白:读取是另一条身份链。没有数据读取角色,就算数据已经写进去,Grafana 也只能看到四零三。
模块 3 · 抓取配置:ConfigMap、PodMonitor 与 ServiceMonitor
- 区分四种抓取入口:PodMonitor、ServiceMonitor(CRD)、
ama-metrics-prometheus-config(ConfigMap 自定义任务)、Pod 注解(在 settings ConfigMap 中按命名空间开启),并知道各自由哪个 Pod 执行。 - 为 myapp 写出可用的 PodMonitor(API 组
azmonitoring.coreos.com/v1、命名端口http、labelLimit等三个限制字段)。 - 会改
ama-metrics-settings-configmap(schema v2:cluster-metrics/controlplane-metrics/prometheus-collector-settings),会用promconfigvalidator预检 ConfigMap 配置。 - 能通过采集 Pod 的 9090 UI 与
config-reader/targetallocator日志确认目标被发现、被抓取。
scrape_configs 与 relabel;模块 2 的组件分工。重要程度:★★★★★先认识两个对象:PodMonitor 与 ServiceMonitor(概念速览)
第 1 课的 Prometheus 是靠 prometheus.yml 里的 scrape_configs 知道“去哪里抓”的。在 Kubernetes 里,Pod 和 Service 一直在变,手写抓取任务很快就会过时。Prometheus Operator 项目因此定义了几个 CRD(自定义资源),让你用 Kubernetes 对象来声明“抓谁”,再由控制器把它们翻译成抓取配置:
| 对象 | 用标签选中什么 | 最后抓的是 |
|---|---|---|
| ServiceMonitor | Service(selector.matchLabels + namespaceSelector) | 该 Service 后面每个就绪 Pod 的端点(经 EndpointSlice),端口按 endpoints[].port 的端口名匹配 |
| PodMonitor | Pod(同样用标签选择) | 每个被选中 Pod 的容器端口(podMetricsEndpoints[].port),不需要 Service |
# 最小 PodMonitor:抓取命名空间 myapp 中带 app=myapp 标签的 Pod 的 http 端口(5000)
apiVersion: azmonitoring.coreos.com/v1 # 托管版的 API 组;开源 Operator 用 monitoring.coreos.com/v1
kind: PodMonitor
metadata: { name: myapp, namespace: myapp }
spec:
selector: { matchLabels: { app: myapp } }
podMetricsEndpoints:
- port: http # 容器端口的名字,不是数字
path: /metrics
interval: 30s
# 托管版还要加 labelLimit 等三个字段,见下文 Why 部分
可以把它理解成:标签选择器 → 一组目标 → 一段自动生成的 scrape_config。本课只用到托管附加组件里的这两个对象;开源 Prometheus Operator、它的 Prometheus CR 以及 serviceMonitorSelector 如何挑选 Monitor,留到 第 5 课 模块 1 和 模块 2 深入讲。
port 写成了数字或写错了端口名;② 选择器标签和 Pod/Service 上的标签对不上(大小写、键名);③ ServiceMonitor 选中的 Service 没有就绪端点。三种情况都表现为“目标列表里根本没有它”,而不是 up=0。What:四个抓取入口
| 入口 | 写在哪里 | 谁执行 | 适合 |
|---|---|---|---|
| PodMonitor | 任意命名空间,apiVersion: azmonitoring.coreos.com/v1 | ama-metrics 副本(target allocator 分配) | 没有 Service 或要抓每个 Pod(本课 myapp) |
| ServiceMonitor | 任意命名空间,同上 | 同上 | 已有 Service、按 Endpoints 抓 |
| ConfigMap 自定义任务 | kube-system/ama-metrics-prometheus-config,键 prometheus-config | ama-metrics 副本 | 标准 Prometheus 语法、static_configs、kubernetes_sd_configs,迁移现成 prometheus.yml |
| ConfigMap(节点级) | ama-metrics-prometheus-config-node / -node-windows | 每个节点的 DaemonSet Pod | 只抓本节点目标($NODE_IP),不得用服务发现 |
| Pod 注解 | Pod 上 prometheus.io/scrape|path|port + settings 中 podannotationnamespaceregex | ama-metrics 副本 | 快速试用;命名空间多时量会很大 |
官方说明:附加组件部署的 PodMonitor/ServiceMonitor CRD 与开源版本只差 API 组名,开源 monitoring.coreos.com 的对象不会被附加组件读取(有意隔离),两套 CRD 不冲突。
Why:为什么有 labelLimit 这几个字段
托管摄取对标签有硬限制:每条序列标签数 ≤ 63、标签名长度 ≤ 511、标签值长度 ≤ 1023,超过时整个抓取任务失败(目标显示 up=0);指标名长度 ≤ 511,超过时只丢该序列。官方模板在 CRD 中写 labelLimit: 63、labelNameLengthLimit: 511、labelValueLengthLimit: 1023,让超限在抓取阶段就被处理,避免在处理阶段被丢弃——请照抄。
How:设置 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
- 这个 ConfigMap 默认不存在,要从官方模板(
https://aka.ms/azureprometheus-addon-settings-configmap)下载后修改再 apply;ama-metrics Pod 会在 2–3 分钟内读取并重启。 - 从 v1 迁移:
default-scrape-settings-enabled→default-targets-scrape-enabled;控制面目标去掉controlplane-前缀;minimalingestionprofile = true改为独立的minimal-ingestion-profile段。 - 注意:官方模板文件里的布尔值是“示例值”,并不完全等于“不存在 ConfigMap 时的默认值”(例如文档列出 coredns、kubeproxy 默认禁用)。apply 模板前逐项核对你想要的开关。
When:选哪个入口
- 团队已经习惯 Prometheus Operator → PodMonitor/ServiceMonitor(把
monitoring.coreos.com改成azmonitoring.coreos.com,release: kps之类的选择标签在托管版本中不需要)。 - 迁移第 1 课
prometheus.yml中的任务 → ConfigMap 自定义任务(全局external_labels在 ConfigMap 方式中不支持,需要在每个任务里用 relabel 加标签)。 - 同一目标只用一种入口,否则会重复抓取、费用翻倍,甚至出现重复序列。
与相似技术对比
| 托管附加组件 | kube-prometheus-stack(第 5 课) | |
|---|---|---|
| CRD 组 | azmonitoring.coreos.com/v1 | monitoring.coreos.com/v1 |
| 选择哪些 Monitor | 所有命名空间中的全部 Monitor | Prometheus CR 的 serviceMonitorSelector(如 release: kps) |
| Secret 访问 | K8s 1.37+ 需 secrets_access_namespaces + 每命名空间 Role/RoleBinding | Operator 的 RBAC |
| 配置校验 | promconfigvalidator(Pod 内自带) | promtool check config |
| 重命名指标 | 不支持 | 支持(relabel __name__) |
podMetricsEndpoints[].port 要求命名端口(官方模板注释:Port requires a named port),所以 Deployment 里给端口起名 http。② “ConfigMap 放在 myapp 命名空间”——三个自定义抓取 ConfigMap 必须在 kube-system,且数据键必须叫 prometheus-config。③ “改了 settings ConfigMap 立刻生效”——要等 ama-metrics Pod 重启(2–3 分钟),重启次数应等于你应用 ConfigMap 的次数。架构图:配置从哪来,目标被谁抓
流程图:一个 PodMonitor 从 apply 到 up=1
交互模拟器:抓取配置诊断
选择抓取入口,并打开/关闭常见错误开关,然后点击“应用配置”。模拟器按真实处理顺序(API Server 校验 → config-reader → targetallocator → 抓取 → 摄取限制)逐步推进,在终端里显示你在对应位置会看到的输出。
核心命令与配置
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
kubectl get crd | grep azmonitoring | 确认附加组件 CRD 已安装 | podmonitors.azmonitoring.coreos.com、servicemonitors.azmonitoring.coreos.com |
kubectl get podmonitors.azmonitoring.coreos.com -A | 列出托管 PodMonitor | 用全名,避免与开源 CRD 的短名混淆 |
kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system | 创建自定义任务 | 文件名必须叫 prometheus-config(无扩展名) |
kubectl apply -f ama-metrics-settings-configmap.yaml | 修改默认目标、keep list、注解命名空间、alias | 2–3 分钟后 Pod 重启生效 |
kubectl port-forward <ama-metrics pod> -n kube-system 9090 | Agent 模式 UI | /config、/service-discovery、/targets |
kubectl logs <operator-targets pod> -c config-reader|targetallocator | 配置解析与目标发现日志 | 看 prometheus-config-merger 段 |
① PodMonitor(本课主选)
apiVersion: azmonitoring.coreos.com/v1 # 不是 monitoring.coreos.com/v1
kind: PodMonitor
metadata:
name: myapp
namespace: myapp
spec:
labelLimit: 63
labelNameLengthLimit: 511
labelValueLengthLimit: 1023
selector:
matchLabels:
app: myapp
podTargetLabels: [app] # 把 Pod 标签 app 加到每条序列
podMetricsEndpoints:
- port: http # 必须是命名端口
path: /metrics
interval: 30s
metricRelabelings: # 抓取后、摄取前:只保留应用指标与 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
说明:up 是抓取器合成的指标,不经过 metricRelabelings,keep 规则不会把它丢掉。按 Prometheus Operator 约定,PodMonitor 产生的序列带 namespace、pod、container、endpoint 等标签,job 通常为 <命名空间>/<PodMonitor 名>——以 /targets 页面实际显示为准,规则里尽量用 namespace="myapp" 这类稳定标签而不是 job。
② ServiceMonitor(二选一,不要与 ① 同时存在)
apiVersion: azmonitoring.coreos.com/v1
kind: ServiceMonitor
metadata: { name: myapp, namespace: myapp }
spec:
labelLimit: 63
labelNameLengthLimit: 511
labelValueLengthLimit: 1023
selector: { matchLabels: { app: myapp } } # 匹配 Service 的标签
endpoints:
- port: http # Service 端口名
path: /metrics
interval: 30s
③ ConfigMap 自定义任务(迁移 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
# 先用 Pod 内自带的 promconfigvalidator 校验(官方方法,需要 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
# 注意:官方文档示例的路径是 ./promconfigvalidator/promconfigvalidator,取决于 kubectl cp 的结果是文件还是目录
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
校验器生成的 merged-otel-config.yaml 仅供调试,不要应用它。常见错误:用 kubectl create configmap … --from-file=myapp.yml,键名变成 myapp.yml,采集器找不到 prometheus-config 键而静默忽略。
④ Pod 注解 + settings ConfigMap
curl -sL https://aka.ms/azureprometheus-addon-settings-configmap -o ama-metrics-settings-configmap.yaml
# 编辑:cluster-metrics → pod-annotation-based-scraping 中
# podannotationnamespaceregex = "myapp"
# 并核对 default-targets-scrape-enabled 中的各项开关是否符合预期
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;把注解命名空间正则改回 ""),否则 myapp 会被抓两遍。实验 3:用 PodMonitor 抓取 myapp 并在工作区查到数据(约 7 分钟)
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
若 jq 过滤为空,在浏览器打开 127.0.0.1:9090/targets 与 /service-discovery 查看(官方给出的 UI 路径)。
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"}) 应为空(多进程模式本来也不导出 python_gc_*/process_*,但 keep 规则是你对“应用还会加什么指标”的保险)。/targets 中会多出 myapp-cm 任务;确认后删除 ConfigMap,避免重复抓取。up{namespace="myapp"} 有 2 条且值为 1;myapp_http_requests_total 在工作区可查;kubectl get pods -n kube-system | grep ama-metrics 的重启次数等于你 apply settings ConfigMap 的次数。案例 1:从 kube-prometheus-stack 迁移 200 个 ServiceMonitor
问题:集群原有开源 ServiceMonitor,启用托管附加组件后一个都没被抓。做法:写一个转换脚本:kubectl get servicemonitors.monitoring.coreos.com -A -o yaml | yq '.items[].apiVersion = "azmonitoring.coreos.com/v1"',补上三个 limit 字段,去掉只对自建 Prometheus 有意义的 release: kps 选择标签依赖,按命名空间灰度 apply。限制:带 basicAuth/Secret 的 Monitor 在 K8s 1.37+ 需要配置 secrets_access_namespaces 与每个命名空间的 Role/RoleBinding(官方步骤);使用 bearerTokenFile 的 Monitor 如果开启了 deny_fs_access_through_sms = true 会被丢弃。
案例 2:安全团队要求禁止 Monitor 读取采集器本地文件
问题:能创建 PodMonitor 的人可以在 bearerTokenFile 中引用采集器容器里的服务账号令牌,并让它发往不受信任的端点(官方文档明确提示此风险)。做法:在 settings ConfigMap 的 prometheus-collector-settings 中设置 deny_fs_access_through_sms = true;同时用 RBAC 限制谁能创建 azmonitoring.coreos.com 资源。限制:该设置默认 false;开启后使用本地 TLS 文件的 Monitor 也会停止抓取,需要先审查。
案例 3:高基数 label 导致整任务 up=0
问题:某服务把 user_agent 原文作为标签,个别值超过 1023 字符,整个任务被判失败。做法:在 Monitor 中用 metricRelabelings 的 labeldrop 去掉该标签,或在应用中改为有限枚举;保持 labelValueLengthLimit: 1023 让问题在抓取阶段显式暴露。限制:托管侧不支持重命名指标,只能丢弃或在源头修改。
常见错误与解决
error: resource mapping not found for name: "myapp" … no matches for kind "PodMonitor" in version "monitoring.coreos.com/v1"
原因:集群里没有开源 Prometheus Operator CRD,而 YAML 用的是开源 API 组(或反过来:有开源 CRD,对象创建成功但附加组件不读)。
kubectl get crd | grep coreos.com kubectl api-resources | grep -i monitor
修复:改为 apiVersion: azmonitoring.coreos.com/v1。
/targets 中看不到 myapp,targetallocator 日志无报错
原因:选择器不匹配(Pod 标签不是 app: myapp)、端口未命名或名称不一致、PodMonitor 与 Pod 不在同一命名空间又没写 namespaceSelector。
kubectl -n myapp get pods --show-labels
kubectl -n myapp get pod -l app=myapp -o jsonpath='{.items[0].spec.containers[0].ports}'
修复:对齐标签与端口名;跨命名空间时加 namespaceSelector: { matchNames: [myapp] }。
目标显示 up=0,原因:label value exceeds the limit / too many labels
原因:某条序列超过 63 个标签或标签值超过 1023 字符——托管摄取会让整个任务失败。
kubectl -n myapp port-forward deploy/myapp 5000:5000 &
curl -s localhost:5000/metrics | awk '{print length($0)}' | sort -n | tail -3; kill %1
修复:metricRelabelings 中 action: labeldrop 去掉问题标签,或修改应用。
自定义 ConfigMap 不生效,config-reader 日志里没有 “custom prometheus config” 字样
原因:ConfigMap 名称/命名空间/键名错误(必须是 kube-system/ama-metrics-prometheus-config,键 prometheus-config),或配置未通过校验被拒绝。
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
修复:用 promconfigvalidator 预检;只支持 static_configs 与 kubernetes_sd_configs 两种发现方式。
forbidden: User "system:serviceaccount:kube-system:ama-metrics-serviceaccount" cannot list resource "secrets"
原因:K8s 1.37+ 上附加组件不再有集群级 Secret 读取权限,Monitor 引用了 basicAuth Secret。
修复:在 settings ConfigMap 设 secrets_access_namespaces = "kube-system,myapp",并在每个命名空间创建 Role(secrets get/list/watch)与绑定到 kube-system/ama-metrics-serviceaccount 的 RoleBinding;重启 ama-metrics 后在 TA 日志中确认 SecretsAccessNamespaces from configmap: [kube-system myapp]。
1. 把本机的 prometheus-config 文件做成附加组件能读取的 ConfigMap。
kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system
2. 列出所有命名空间里由托管附加组件读取的 PodMonitor 和 ServiceMonitor。
kubectl get podmonitors.azmonitoring.coreos.com,servicemonitors.azmonitoring.coreos.com -A
同事给 myapp 同时写了 PodMonitor 和 ServiceMonitor,还开了 myapp 命名空间的注解抓取。仪表板上请求速率是实际的 3 倍。原因是什么?怎么修?
三个入口各自生成一个抓取任务,同一组 Pod 被抓 3 次,sum(rate(myapp_http_requests_total[5m])) 把三份序列加在一起(job/endpoint 标签不同,所以不是“重复序列”而是三组不同序列)。修复:只保留一种入口(推荐 PodMonitor),删除 ServiceMonitor,把 podannotationnamespaceregex 改回 "";短期仪表板可按 job 过滤。同时检查费用:摄取样本也是 3 倍。
经核实的教学视频
官方文档
- Create custom scrape jobs using CRDs
- Create custom scrape jobs using ConfigMap
- Customize scraping using ama-metrics-settings-configmap
- Pod/Service Monitor 官方模板(GitHub)
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:四个入口卡片 PodMonitor、ServiceMonitor、ConfigMap、Pod 注解汇入一个漏斗 target allocator。
旁白:托管采集有四个入口,但它们最终都交给目标分配器,由采集副本去抓。
画面:YAML 中 apiVersion 一行闪烁,monitoring 被划掉改成 azmonitoring。
旁白:唯一的语法差别是 API 组:azmonitoring 点 coreos 点 com。开源组的对象,托管采集器不会读取。
画面:一条序列的标签逐个堆叠,到第六十四个时整列变红,目标状态 up 变成 0。
旁白:每条序列最多六十三个标签,标签值最长一千零二十三个字符。超过时整个任务失败,所以模板里的三个限制字段要照抄。
画面:终端 port-forward 到 9090,浏览器显示 targets 页面两个绿色 up。
旁白:验证永远看三处:目标分配器日志、采集器的 targets 页面、工作区里的 up 指标。
模块 4 · Azure Managed Grafana:身份、权限与数据源
- 用
az grafana create创建 Standard 层工作区,理解--sku-tier、--grafana-major-version、--principal-ids、--skip-role-assignments、--zone-redundancy的含义。 - 说出四个内置 Grafana 角色(Admin / Editor / Viewer / Limited Viewer)的区别,并用
az role assignment create授权给 Entra 用户或组。 - 把
amw-prom-lab链接到 Grafana(三种方式),解释为什么需要 Monitoring Data Reader、为什么 Contributor 不够。 - 为 myapp 导入一个仪表板(请求速率、5xx 比例、P95 延迟、Redis 状态),会用
az grafana dashboard import与backup/restore。
What:Managed Grafana 是什么
由微软运营的 Grafana 服务(资源类型 Microsoft.Dashboard/grafana),内置 Azure Monitor、Azure Data Explorer 数据源,用户通过 Microsoft Entra ID 单点登录,访问控制用 Azure RBAC;提供高可用、SLA 与自动升级。
| 层级 | 状态 | 要点 |
|---|---|---|
| Essential | 不能新建;存量计划 2027-03-31 完全弃用 | 无 SLA、无告警、仅 Azure Monitor / Prometheus / TestData 数据源 |
| Standard(推荐,CLI 默认) | GA | 实例规格 X1(默认)与 X2(内存更大,每组织 1000 条告警规则,X1 为 500);区域冗余、确定性出站 IP、私有终结点、Grafana 告警、SMTP、报表/渲染、全部核心插件;Grafana Enterprise 可选(另付许可)。可从 X1 升到 X2,不能降级。 |
Why:为什么权限要拆成两条链
- 人 → Grafana:谁能打开 Grafana、能不能改仪表板,由 Grafana 实例上的 Azure 角色决定。
- Grafana → 数据:Grafana 后端代表自己(系统分配托管标识,默认启用)去查询工作区,由工作区上的数据面角色决定。这样查看仪表板的人不需要对工作区有任何权限——这正是“共享仪表板”能成立的原因,也意味着 Grafana Viewer 能看到 Grafana 托管标识能读到的所有数据,要用文件夹/数据源权限做隔离。
How:角色清单
| 作用域 | 角色 | 能做什么 |
|---|---|---|
| Grafana 实例 | Grafana Admin | 全部操作:数据源、仪表板、团队与权限管理 |
| Grafana Editor | 查看并编辑仪表板与告警 | |
| Grafana Viewer | 查看仪表板与告警 | |
| Grafana Limited Viewer | 只能看到首页(对应 Grafana 的 “No Basic Role”),再由 Admin 按文件夹/仪表板单独授权;不适用于 Grafana v9 实例 | |
| Azure Monitor 工作区 | Monitoring Data Reader | 读取工作区中的 Prometheus 数据(Grafana 托管标识、你的用户、规则自动化应用都需要) |
| 订阅/资源组 | Monitoring Reader | 读取 Azure Monitor 管理面与平台指标(Azure Monitor 数据源浏览资源时需要) |
注意两份官方文档的措辞差异:“启用 AKS 监控”文档写的是链接时给 Grafana 托管标识分配 Monitoring Reader(并要求执行者为 Owner),而 Managed Grafana 的“添加 Azure Monitor 工作区”文档要求在工作区上分配 Monitoring Data Reader。读取 Prometheus 数据的权限以 Monitoring Data Reader 为准;链接后用 az role assignment list --scope $AMW_ID 检查实际分配了哪些角色。
链接工作区的三种方式
- 启用时一并链接:
az aks update --enable-azure-monitor-metrics --azure-monitor-workspace-resource-id … --grafana-resource-id …(自动做角色分配并把工作区写入 Grafana 的azureMonitorWorkspaceIntegrations,需要 Owner 或 Contributor + User Access Administrator)。 - CLI 集成命令(预览):
az grafana integration monitor add -g … -n … --monitor-rg-name … --monitor-name …,默认会在工作区上为 Grafana 分配读取角色(可--skip-role-assignments)。 - 门户手动:工作区 IAM 中给 Grafana 托管标识分配 Monitoring Data Reader → Grafana 资源 Integrations → Azure Monitor workspaces → Add。
链接成功后,Grafana 中会出现一个“托管 Prometheus”数据源(文档说明从 Grafana 13 起由 Azure Monitor Managed Service for Prometheus 插件提供 Azure 认证,存量数据源自动迁移),并在 Dashboards → Managed Prometheus 文件夹下预置一组 Kubernetes 仪表板。
When:Managed Grafana 还是门户内置视图
- 需要自定义仪表板、跨数据源关联、Grafana 告警、共享给大量用户 → Managed Grafana Standard。
- 只想在 AKS 门户里看看集群曲线 → Azure 门户中的 Grafana 视图(官方博客称门户内原生 Grafana 仪表板不额外收费,功能范围以官方 FAQ“Managed Grafana 与 Azure Monitor 中的 Grafana 的区别”为准)。
与相似技术对比
| Managed Grafana | 自建 Grafana(第 1 课) | AWS AMG(第 4 课) | |
|---|---|---|---|
| 登录 | Entra ID SSO | 本地 admin/密码或自配 OAuth | IAM Identity Center / SAML |
| 授权 | Azure RBAC 四个 Grafana 角色 | Grafana 内部组织角色 | AMG 用户/组分配 |
| 数据源认证 | 托管标识(默认系统分配) | Basic/Token 存在 Grafana DB | 工作区 IAM 角色 |
| 升级 | 微软托管;主版本可选(--grafana-major-version) | 自己 | AWS 托管 |
架构图:两条身份链
流程图:一次面板刷新
交互动画:两条身份链逐跳检查(可“拔掉”角色)
勾掉某个角色分配,然后播放一次“打开 myapp 仪表板”。动画按真实顺序检查每一跳,并在终端显示对应的 HTTP 交互或报错(报错文本为常见形式的示例,实际措辞随版本变化)。
核心命令与参数
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
az grafana create | 创建工作区(幂等) | --sku-tier(默认 Standard)、--grafana-major-version、--principal-ids(指定 Grafana Admin,指定后不再自动给当前账号)、--skip-role-assignments、--zone-redundancy、--public-network-access |
az grafana show | 端点、托管标识、版本 | --query properties.endpoint、identity.principalId |
az grafana integration monitor add | 链接工作区(预览) | --monitor-rg-name --monitor-name;默认分配读取角色 |
az role assignment create | 授予 Grafana 角色 / 数据读取角色 | --scope 分别为 Grafana 实例 ID / 工作区 ID |
az grafana data-source list | 查看数据源 | 确认托管 Prometheus 数据源存在 |
az grafana dashboard import | 导入仪表板 | --definition 可为 JSON 字符串、gallery ID、文件路径(@file.json)或 URL;--folder、--overwrite |
az grafana backup / restore | 备份 / 迁移内容 | --components dashboards folders datasources、--remap-data-sources |
az grafana update --major-version | 升级 Grafana 主版本 | 以官方升级指南为准,升级通常不可逆 |
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"
}
如何验证:浏览器打开 endpoint,以创建者账号 SSO 登录应能进入(创建者默认获得 Grafana Admin)。常见错误:名称全局唯一,重名会报冲突;版本号以实际输出为准。
链接工作区(任选一种)
# 方式 A:重新执行 az aks update,带上 Grafana(需要 Owner 或 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
# 方式 B:CLI 集成命令(预览)
az grafana integration monitor add -g $RG -n $AMG --monitor-rg-name $RG --monitor-name $AMW
# 方式 C:手动角色分配 + 门户 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
# 检查结果
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 托管标识) 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
数据源名称与类型随 Grafana 版本变化(Grafana 13 起使用专用插件),以实际列表为准。
给同事授权
az role assignment create --assignee "bob@contoso.com" --role "Grafana Viewer" --scope $AMG_ID # 推荐授权给 Entra 组(对象 ID) az role assignment create --assignee-object-id <group-object-id> --assignee-principal-type Group \ --role "Grafana Editor" --scope $AMG_ID
实验 4:创建 Grafana、链接工作区、导入 myapp 仪表板(约 7 分钟)
{
"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": "请求速率 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 比例", "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 延迟 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
若 CLI 版本对 --definition 的包装格式要求不同(有的版本需要 {"dashboard": {...}} 外层),按 az grafana dashboard import -h 调整,或直接在 UI 中 Dashboards → New → Import 粘贴 JSON。
Grafana Viewer 后可以查看仪表板但不能保存修改。az role assignment delete --assignee $AMG_MI --role "Monitoring Data Reader" --scope $AMW_ID # 等待几分钟后刷新面板:出现 403 / 权限错误 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(模块 8 统一清理)。案例 1:按 Entra 组授权与“Limited Viewer + 文件夹权限”
问题:一个 Grafana 服务 20 个应用团队,团队 A 不应看到团队 B 的仪表板。做法:所有人默认 Grafana Limited Viewer;Grafana Admin 按团队建文件夹,在 Settings → Permissions 给对应 Grafana Team(与 Entra 组同步)授予 View/Edit。限制:不能用组件权限限制 Grafana Admin;权限取各来源中最高的那个,低权限不会覆盖继承的高权限。数据源层面仍是同一个托管标识,敏感数据要放到独立工作区并单独建数据源。
案例 2:仪表板即代码
问题:手工改仪表板导致环境间不一致。做法:仪表板 JSON 存 Git,CI 中用 az grafana dashboard import --overwrite true 发布;跨实例迁移用 az grafana dashboard sync(预览)或 backup/restore --remap-data-sources。CI 身份用服务主体并授予 Grafana Editor。限制:“Provisioned” 状态的仪表板在 sync 时会被跳过(只读)。
案例 3:私网访问与确定性出站 IP
问题:Grafana 需要查询一个只允许固定 IP 的外部数据源,且公司要求 Grafana 不暴露公网。做法:Standard 启用 --deterministic-outbound-ip Enabled 把出站 IP 加入对方白名单;创建私有终结点并 --public-network-access Disabled。限制:这些都是 Standard 专属功能;关闭公网后 CLI 的数据面命令(dashboard/data-source)也要从能访问私有终结点的网络执行。
常见错误与解决
登录 Grafana 提示:You don't have permission / No role assigned
原因:用户在 Grafana 实例上没有任何 Grafana 角色(订阅 Owner 也不会自动拥有)。
az role assignment list --scope $AMG_ID --query "[].{who:principalName,role:roleDefinitionName}" -o table
修复:分配 Grafana Viewer/Editor/Admin;角色变更后重新登录。
面板报错:403 / "Forbidden" / authorization failed when querying Prometheus
原因:Grafana 托管标识在工作区上缺少 Monitoring Data Reader,或系统托管标识被关闭/替换为用户分配标识但没授权。
az grafana show -n $AMG -g $RG --query identity az role assignment list --scope $AMW_ID --assignee $AMG_MI -o table
修复:补齐角色分配;在 Grafana 资源的 Identity 页确认系统分配标识为 On。
CLI 报错:(AuthorizationFailed) … Microsoft.Authorization/roleAssignments/write(执行 --grafana-resource-id 或 integration monitor add)
原因:执行者没有分配角色的权限。
修复:找 Owner / User Access Administrator 执行;或用 --skip-role-assignments 只做链接,再由管理员单独分配。
Managed Prometheus 文件夹里没有预置仪表板
原因:不是通过“链接工作区”的流程添加数据源(例如手工新建 Prometheus 数据源),或链接尚未完成。
az grafana show -n $AMG -g $RG --query properties.grafanaIntegrations az grafana integration monitor list -g $RG -n $AMG
修复:用方式 A/B/C 之一完成链接;预置仪表板也可从官方 GitHub 手动导入。
图表一直转圈加载(Charts are stuck in a loading state)
原因:浏览器侧拦截了 monitor.azure.com 流量(广告拦截插件或公司代理),官方故障排查文档列出的已知原因。
修复:关闭拦截插件或把 monitor.azure.com 加入允许列表后刷新。
1. 给 Grafana amg-prom-lab-12345 的托管标识授予读取 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. 把 Entra 组(对象 ID 1111…)设为只读用户。
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)
安全审计发现:外包人员只有 Grafana Viewer,却能在 Explore 里查询到生产集群所有命名空间的指标。为什么?如何收紧?
Grafana 以自己的托管标识查询工作区,查看者能看到托管标识能读的全部数据;Viewer 角色在多数版本中仍可使用 Explore(取决于 Grafana 配置)。收紧:① 给外包人员 Grafana Limited Viewer,仅授权特定文件夹/仪表板;② 敏感环境用独立工作区与独立数据源,并通过数据源权限限制谁能查询;③ 必要时为不同受众拆分 Grafana 实例;④ 定期审计 az role assignment list --scope $AMG_ID。
经核实的教学视频
官方文档
- What is Azure Managed Grafana?
- Add an Azure Monitor workspace to Managed Grafana
- Grant users and identities access
- az grafana CLI reference
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:终端 az grafana create,输出 endpoint;浏览器打开后自动跳转到 Microsoft 登录。
旁白:托管 Grafana 用 Entra ID 单点登录,没有本地 admin 密码要保管。
画面:上方一条链“用户 → Entra → Grafana Viewer → Grafana”,下方一条链“Grafana 托管标识 → Entra → Monitoring Data Reader → 工作区”。
旁白:权限分成两条链:人能不能进 Grafana,看实例上的 Grafana 角色;Grafana 能不能读数据,看工作区上的数据读取角色。
画面:下方链条中的 Monitoring Data Reader 被剪断,面板变红显示 403。
旁白:如果剪断第二条链,所有查看者都会看到权限错误,与他们自己的权限无关。
画面:myapp 仪表板四个面板依次出现:请求速率、5xx 比例、Redis 状态、P95 延迟。
旁白:链接完成后,导入仪表板即代码,同一个 JSON 可以在测试和生产 Grafana 之间复用。
模块 5 · 托管告警规则组与 Action Group
- 理解规则组的作用域(工作区 + 可选集群 ID +
clusterName)、评估间隔interval(默认 PT1M)与规则执行顺序。 - 把 Prometheus 规则字段映射到托管字段:
for(ISO 8601,如PT5M)、severity(0–4,默认 3)、resolveConfiguration.autoResolved/timeToResolve(默认 true / PT5M)、actions[].actionGroupId。 - 创建 Action Group(邮件,通用告警架构),把 myapp 的 5xx、目标缺失、Redis 宕机三条告警接上通知,并完成“触发 → 邮件 → 自动解决”的闭环。
- 知道推荐告警(社区规则 + 平台指标规则)的启用方式与
az-prom-rules-converter的用途。
What:规则组与 Action Group
Prometheus 规则组(Microsoft.AlertsManagement/prometheusRuleGroups)是一组一起评估的 recording 与 alert 规则,作为 Azure 资源存在(有订阅、资源组、区域、标签)。规则语法沿用开源 Prometheus(名称、表达式、labels、annotations),另外为告警规则增加了 Azure 专有属性:严重级别、Action Group 关联、自动解决配置。
| 开源 Prometheus(第 2 课) | 托管规则组 | 说明 |
|---|---|---|
groups[].name | 规则组资源名 | 资源组内唯一,创建后不可改 |
interval: 1m | interval: PT1M | ISO 8601 持续时间,默认 PT1M |
| Prometheus 实例隐式作用域 | scopes:工作区 ID(必填)+ 可选一个集群 ID;clusterName | 不指定集群时,规则查询工作区内所有集群的数据 |
record / expr / labels | record / expression / labels | 结果作为新序列写回工作区(会产生摄取量) |
alert / expr / for: 5m | alert / expression / for: PT5M | 同样有 pending 阶段 |
labels.severity: critical | severity: 0–4 | 0 最严重,默认 3 |
| Alertmanager 路由 → receiver | actions[].actionGroupId(每条规则直接指定) | 没有路由树;跨规则的静默/抑制用告警处理规则(alert processing rules) |
send_resolved: true | resolveConfiguration.autoResolved: true、timeToResolve: PT10M | 条件在该时间段内持续不成立才自动解决 |
Action Group(Microsoft.Insights/actionGroups)是一组通知/自动化接收方:邮件、短信、语音、Azure 应用推送、Webhook(可带 Entra 认证)、Logic App(可发 Teams)、Azure Function、Automation Runbook、Event Hub、ITSM、ARM 角色。所有类型的 Azure Monitor 告警都可以复用同一个 Action Group。
Why:为什么规则放在工作区侧
- 采集器是无状态代理,不评估规则;工作区侧评估能跨集群(不限定 cluster 时)、能被 Azure Monitor 告警统一管理(状态、历史、确认、处理规则)。
- 规则组是 ARM 资源 → 可以用 Bicep/ARM/Terraform、Azure Policy、RBAC(Monitoring Contributor 即可创建)统一治理。
- 规则组有资源运行状况(Available / Degraded / Unavailable / Unknown),查询被限流或配置错误会显示 Degraded——这是自建 Prometheus 没有的可观测性。
How:一条告警的生命周期
- 每个
interval,规则组用 PromQL 查询工作区(对clusterName限定的数据)。 - 表达式返回结果 → 进入 pending;持续满足
for时长 → fired,生成 Azure Monitor 告警(带 severity、labels、annotations)。 - 告警触发规则上配置的每个 Action Group;告警处理规则可在此之前抑制或追加通知(如维护窗口)。
- 条件不再满足且持续
timeToResolve→ 自动解决(Resolved),使用通用告警架构的接收方会收到“已解决”通知。
开箱即用的规则
- 默认 recording rules:启用指标时自动创建(节点/命名空间/工作负载的 CPU、内存聚合),供预置仪表板使用。
- 推荐告警:集群 Alerts → Set up recommendations,按集群/节点/Pod 级别开启 Prometheus 社区规则(如
KubePodCrashLooping、KubeContainerOOMKilledCount、KubeNodeUnreachable、KubePVUsageHigh、KubeDeploymentReplicasMismatch)和平台指标规则(节点 CPU > 95%、节点工作集内存 > 100%);也可用官方 ARM/Bicep 模板。另建议启用工作区的摄取配额推荐告警。 - 旧的 Container insights 自定义指标告警已于 2024-05-31 退役,应迁移到推荐告警。
When:选 Prometheus 规则组还是别的告警
- 基于 PromQL 的应用/集群告警 → 规则组(本模块)。
- 基于日志内容(某条错误日志出现)→ 日志搜索告警(Log Analytics,模块 6)。
- 只看 AKS 平台指标(节点 CPU)→ 平台指标告警。
- 团队已重度使用 Grafana 告警且只在 Grafana 内处理 → Managed Grafana Standard 的 Grafana Alerting(X1 每组织 500 条规则,X2 1000 条)。但不要对同一条件在两处都配置。
与相似技术对比
| Azure 托管规则组 | Prometheus + Alertmanager(第 2 课) | AMP 规则 + Alertmanager(第 4 课) | |
|---|---|---|---|
| 规则格式 | ARM/Bicep JSON(可由 YAML 转换) | YAML | YAML(上传) |
| 路由/分组 | 无路由树;每规则绑定 Action Group | 路由树、group_by | Alertmanager 配置 |
| 静默 | 告警处理规则(按作用域/时间) | silence | silence |
| 通知通道 | Action Group(邮件/短信/Webhook/ITSM…) | receiver | SNS |
for: 5m 可以照抄”——托管规则要求 ISO 8601(PT5M)。② “规则组会自动只查我的集群”——不加集群 scope 和 clusterName 时查询工作区内所有集群;若改过 cluster_alias,clusterName 必须填别名。③ “预览图没数据说明表达式错了”——告警表达式通常只返回满足条件的序列,没触发时预览为空是正常的(官方说明)。架构图:规则组、告警与通知
时间线:5xx 比例告警
交互模拟器:托管告警时间线
拖动“5xx 比例”滑块模拟故障与恢复,点击“运行”按评估间隔(PT1M)推进。模拟器显示规则组每次评估的结果、告警状态(Inactive → Pending → Fired → Resolved)、Action Group 的通知与对应的 Azure 侧事件。时间轴已压缩(1 秒 = 1 分钟)。
核心命令与参数
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
az monitor action-group create | 创建 Action Group | --short-name(短信中显示)、--action email NAME ADDRESS [usecommonalertschema]、--action webhook NAME URI … |
az monitor action-group test-notifications create | 发送测试通知 | 验证邮件能收到 |
az alerts-management prometheus-rule-group create | 创建规则组 | --scopes(工作区 ID [+ 集群 ID])、--cluster-name、--interval PT1M、--rules(JSON 数组,可用 @文件)、--enabled |
az alerts-management prometheus-rule-group show/list/update/delete | 管理规则组 | update --enabled false 停用整组 |
az graph query | 查询已触发的告警 | 表 alertsmanagementresources(需 resource-graph 扩展) |
① 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
Action Group 默认位置为 Global。收件人会收到一封“已被加入 Action Group”的通知邮件;如果收件人退订,可用 az monitor action-group enable-receiver 重新启用。
② 规则 JSON(由第 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 比例超过 5%",
"description": "当前 5xx 比例 {{ $value | humanizePercentage }},请查看 myapp 仪表板与 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": "myapp 可抓取的副本少于 2 个" },
"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 无法连接 Redis" },
"enabled": true,
"resolveConfiguration": { "autoResolved": true, "timeToResolve": "PT5M" },
"actions": [ { "actionGroupId": "AG_ID_PLACEHOLDER" } ]
}
]
说明:MyAppPodsMissing 用 or vector(0) 处理“所有目标都消失、up 序列不存在”的情况(第 2 课讲过 absent() 的同类问题)。注解中的 {{ $value }} 模板在托管规则中的渲染效果以实际告警为准。
③ 创建规则组
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
}
常见错误:shell 中直接内联 JSON 时引号转义极易出错,推荐 @文件;如果你的 CLI 版本不接受 @文件,改用 --rules "$(cat myapp-rules.rendered.json)" 或 ARM/Bicep 模板(规则组 API 版本 2023-03-01)。生产用途:规则 YAML 存 Git,CI 中用 az-prom-rules-converter 生成 ARM 模板后部署。
④ 查看已触发的告警
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
实验 5:5xx 告警 → 邮件 → 自动解决(约 10 分钟,含等待)
az monitor action-group test-notifications create,参数以 -h 为准),确认收到测试邮件。myapp-rules,资源运行状况应为 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])"'约 6–8 分钟后应收到
MyAppHigh5xxRatio 的 Fired 邮件(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'5 分钟窗口过后比例降到 0,再经过
timeToResolve(PT10M)收到 Resolved 邮件。kubectl -n myapp scale deploy redis --replicas=0,约 3–5 分钟后收到 MyAppRedisDown(Sev1);随后 --replicas=1 恢复。ag-prom-lab,保存。注意这会新建若干规则组,清理时一起删除。az alerts-management prometheus-rule-group update -n myapp-rules -g $RG --enabled false。案例 1:把 80 条 PrometheusRule 迁移为规则组
问题:自建栈的规则 YAML 分散在多个 chart 里。做法:导出为标准 Prometheus 规则文件,用官方 az-prom-rules-converter 生成 ARM 模板(需要提供订阅、资源组、区域、工作区、集群 ID/名称、Action Group),每个集群一个规则组(同一套规则复制多份,每份 scope 一个集群),避免单组查询全部集群导致限流。限制:依赖 Alertmanager 路由(按 team 标签分发)的逻辑需要改成“每条规则指定 Action Group”,或用 Webhook 接到自己的路由服务。
案例 2:维护窗口静默
问题:每周二 AKS 节点升级时,KubeNodeUnreachable 与应用告警刷屏。做法:创建告警处理规则,作用域为该集群/资源组,规则类型“移除所有 Action Group”,按每周计划生效;告警仍然记录,只是不通知。限制:告警处理规则作用于 Azure Monitor 告警层面,不改变规则组评估;官方说明节点升级期间集群级采集会有 1–2 分钟空洞,但推荐告警已考虑这一点。
案例 3:告警到 Teams 与工单
问题:值班团队用 Teams 和 ServiceNow。做法:Action Group 中加 Logic App(官方提供“发送 Teams 消息”的做法)与 ITSM 接收方;所有接收方启用通用告警架构,便于下游解析。限制:短信/语音按国家计价且有频率限制;Webhook 建议启用 Entra 认证(useaadauth)。
常见错误与解决
规则组资源运行状况 Degraded:query throttled / rule evaluation failed
原因:表达式查询量太大(不限定集群、时间窗过长、高基数 by),或表达式语法在托管侧不被接受。
诊断:门户规则组 → Help → Resource health 展开状态说明(保留 30 天历史);用查询 API 单独执行表达式测耗时。
修复:加集群 scope / clusterName;先用 recording rule 预聚合,告警引用聚合结果;按集群拆分规则组。
(BadRequest) … 'for' … is not a valid duration / Invalid value for 'interval'
原因:把 Prometheus 写法 5m 直接放进了托管规则。
修复:改为 ISO 8601:PT5M、PT1M、PT1H。
规则显示 Enabled,表达式在 Grafana 里能查到 > 0.05,但从不触发
原因:① clusterName 与数据中的 cluster 标签不一致(设置过 cluster_alias);② 规则组 scope 指向了另一个工作区;③ 表达式里的标签(如 job)与托管采集产生的实际值不同。
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'
修复:对齐 clusterName 与 scope;表达式尽量用 namespace/pod 等稳定标签。
告警已 Fired,但没有收到邮件
原因:规则未配置 actions;Action Group 被禁用;收件人退订或在垃圾邮件中;告警处理规则移除了 Action Group;邮件频率限制。
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}"
修复:补 actionGroupId;enable-receiver;检查告警处理规则。
(AuthorizationFailed) … Microsoft.AlertsManagement/prometheusRuleGroups/write
原因:缺少在目标资源组创建规则组的权限。
修复:授予 Monitoring Contributor(官方前提条件)或更高。
1. 创建一个名为 ag-prom-lab、通知 oncall@example.com 并启用通用告警架构的 Action Group。
az monitor action-group create -g rg-prom-lab -n ag-prom-lab --short-name promlab \ --action email oncall oncall@example.com usecommonalertschema
2. 临时停用整个规则组 myapp-rules(不删除)。
az alerts-management prometheus-rule-group update -n myapp-rules -g rg-prom-lab --enabled false
你把第 2 课的规则(for: 5m,Alertmanager 按 team 标签路由到不同邮箱)迁到 Azure。如何设计规则组与 Action Group?
① 用 az-prom-rules-converter 把 YAML 转成 ARM,并把 for 转为 PT5M;② 托管侧没有路由树,按 team 拆分:每个 team 一个 Action Group,规则通过 actions[].actionGroupId 直接指向对应 team(可按 team 拆成多个规则组以便授权与停用);③ 每个集群一个规则组(scope + clusterName),避免跨集群大查询;④ 维护窗口与抑制改用告警处理规则;⑤ 需要复杂路由时,Action Group 用 Webhook 接到自有路由服务(或保留一个 Alertmanager)。
经核实的教学视频
未找到专门讲“托管 Prometheus 规则组”且经核实的视频,以下分镜可用于自制。
官方文档
- Rule groups in Azure Monitor managed service for Prometheus
- Recommended alert rules for Kubernetes clusters
- az monitor action-group
- az-prom-rules-converter(GitHub)
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:左边一份 rules.yml,右边一份 JSON,字段一一连线:for 5m 变成 PT5M,severity 标签变成数字 2。
旁白:托管规则沿用 Prometheus 语法,只是时间写成 ISO 8601,严重级别是零到四的数字。
画面:规则组图标每隔一格时间轴闪烁一次,5xx 曲线越过 5% 虚线后状态从 Pending 变成 Fired。
旁白:规则组在工作区一侧每分钟评估一次,持续满足五分钟后触发 Azure Monitor 告警。
画面:告警卡片飞向 Action Group,分裂成邮件、Teams、工单三个图标。
旁白:通知不再有路由树,每条规则直接指定 Action Group;维护窗口用告警处理规则来静默。
画面:曲线回落,经过十分钟的灰色区间后状态变为 Resolved,邮箱收到第二封邮件。
旁白:条件消失并持续十分钟后自动解决。别忘了,从故障到邮件还要加上一到两分钟的摄取延迟。
模块 6 · Container Insights、日志与指标的关联
- 说出 Container Insights 的组件(
ama-logsDaemonSet、ama-logs-rs)与数据流(DCR 流 → Log Analytics 表),以及它与托管 Prometheus 的分工。 - 用
az aks enable-addons --addon monitoring --data-collection-settings按“Logs and Events”成本预设只采集ContainerLogV2、KubeEvents、KubePodInventory。 - 写出 KQL 找到 myapp 5xx 对应的访问日志、Pod 事件与重启,并在 Grafana 中把 PromQL 面板与 KQL 面板并排关联。
where / summarize / bin)。重要程度:★★★★What:Container Insights 采集什么
Container Insights(AKS monitoring 附加组件,az aks show 中显示为 addonProfiles.omsagent)同样基于容器化 Azure Monitor agent:ama-logs DaemonSet 在每个节点读取容器 stdout/stderr 等,ama-logs-rs 副本采集集群级清单与事件;数据由 DCR 定义的流(stream)写入 Log Analytics 工作区的表。
| 流(stream) | 表 | 内容 |
|---|---|---|
Microsoft-ContainerLogV2 | ContainerLogV2 | 容器 stdout/stderr(新架构:PodName、PodNamespace、ContainerName、LogMessage、LogLevel 等列) |
Microsoft-KubeEvents | KubeEvents | Kubernetes 事件(拉镜像失败、OOMKilled、调度失败…) |
Microsoft-KubePodInventory | KubePodInventory | Pod 清单与状态、重启次数 |
Microsoft-Perf / Microsoft-InsightsMetrics | Perf / InsightsMetrics | 性能指标(已启用托管 Prometheus 时通常不需要) |
Microsoft-ContainerInsights-Group-Default | 以上全部 | 默认的组流 |
成本预设(门户启用时可选)
| 预设 | 频率 | 命名空间过滤 | 采集的数据 |
|---|---|---|---|
| Logs and Events(默认) | 1m | 无 | ContainerLogV2、KubeEvents、KubePodInventory —— 官方注明“启用了托管 Prometheus 时推荐” |
| Standard | 1m | 无 | 全部标准表 |
| Cost-optimized | 5m | 排除 kube-system、gatekeeper-system、azure-arc | 全部标准表 |
| Syslog | 1m | 无 | 全部标准表 + Syslog |
CLI 用 --data-collection-settings 传 JSON:interval(1m–30m)、namespaceFilteringMode(Include/Exclude/Off,作用于清单与性能数据)、namespaces、enableContainerLogV2(默认 true)、streams。
Why:指标与日志为什么要分开又要关联
- 成本模型不同:指标按样本计费,极其便宜且适合聚合与告警;日志按 GB 计费,适合保留原始上下文。用托管 Prometheus 做性能数据,就不必再为 Perf/InsightsMetrics 付日志费用。
- 排障需要两者:告警来自指标(5xx 比例),根因常在日志(异常栈、上游超时)和事件(OOMKilled、镜像拉取失败)。
- 关联键:
namespace/pod(Prometheus 标签)↔PodNamespace/PodName(ContainerLogV2 列),以及时间窗。托管 Prometheus 不支持 exemplars(API 文档说明实验特性不支持),所以“从指标点跳到 trace”的玩法这里不适用,用时间窗 + Pod 关联。
How:本课的日志方案
- 创建 Log Analytics 工作区
law-prom-lab。 - 启用 monitoring 附加组件,只采集 Logs and Events 三个流。
- myapp 升级到
myapp:1.1:gunicorn 增加--access-logfile -,把访问日志打到 stdout(第 1 课的 1.0 版本默认不输出访问日志)。 - 在 Grafana 中为托管标识授予 Log Analytics Reader,使用 Azure Monitor 数据源的 Logs(KQL)查询,与 PromQL 面板放在同一仪表板,共享时间范围。
When:什么时候开哪些流
- 已启用托管 Prometheus → Logs and Events。
- 需要门户 Insights 的全部默认视图(节点/控制器/容器性能页) → Standard(官方说明“All”分组是默认可视化所必需的),但会与 Prometheus 指标重复付费。
- 日志量大 → 命名空间排除、ContainerLogV2 配合较便宜的表计划(Basic/Auxiliary,是否适用以官方表计划文档为准),或开启高规模模式(流改为
Microsoft-ContainerLogV2-HighScale,不可与普通 ContainerLogV2 流同时使用)。
与相似技术对比
| Container Insights | Loki(自建) | CloudWatch Container Insights(第 4 课) | |
|---|---|---|---|
| 查询语言 | KQL | LogQL | Logs Insights 查询语言 |
| 索引 | 全列可查(按 GB 摄取计费) | 只索引标签 | 按 GB |
| 与指标关联 | Grafana 并排面板 / 门户工作簿 | Grafana 原生(同标签) | CloudWatch 仪表板 |
container-azm-ms-agentconfig)设置,具体键以官方文档为准。③ “Grafana Viewer 看不到日志是 Grafana 的问题”——Grafana 托管标识需要对 Log Analytics 工作区有读取权限。架构图:日志路径与指标路径并行
关联键对照
交互:从指标尖峰跳到同一时间窗的日志
下图是 myapp 的 5xx 速率(模拟数据)。点击任意柱子,模拟器生成对应时间窗与 Pod 的 KQL,并展示 ContainerLogV2、KubeEvents 的示例结果——这就是值班时“从告警到根因”的标准动作。
核心命令与参数
| 命令 | 作用 | 关键参数 / 说明 |
|---|---|---|
az monitor log-analytics workspace create | 创建 Log Analytics 工作区 | -g -n -l;--retention-time |
az aks enable-addons --addon monitoring | 启用 Container Insights(官方文档示例) | --workspace-resource-id、--data-collection-settings dcs.json |
az aks update --enable-azure-monitor-logs | 新式启用方式(CLI 参考中出现) | 通过 Azure Monitor profile 配置,不能与 --enable-addons monitoring 同用;本课以官方操作文档的 enable-addons 为主 |
az aks disable-addons --addon monitoring | 关闭 | 工作区数据保留 |
az monitor log-analytics query | 在 CLI 中跑 KQL | -w 是工作区 customerId(GUID),不是资源 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
如何验证:useAADAuth: "true" 表示使用托管标识认证(官方默认)。常见错误:把 dcs.json 中的 streams 写成表名(ContainerLogV2)而不是流名(Microsoft-ContainerLogV2)。生产用途:按团队命名空间分别设置采集策略,日志量大的命名空间单独评估。
myapp:1.1:把访问日志打到 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 查询
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 事件 KubeEvents | where TimeGenerated > ago(1h) and Namespace == "myapp" | project TimeGenerated, Name, Reason, Message, Count | order by TimeGenerated desc // 每个 Pod 最新状态与重启次数 KubePodInventory | where TimeGenerated > ago(15m) and Namespace == "myapp" | summarize arg_max(TimeGenerated, PodStatus, PodRestartCount) by Name
LogMessage 对非 JSON 日志是字符串;如果应用输出 JSON,ContainerLogV2 会把它作为动态类型,可直接 LogMessage.level 访问(以官方 ContainerLogV2 架构文档为准)。日志从产生到可查询通常有数分钟延迟。
实验 6:日志与事件采集 + 指标/日志并排仪表板(约 7 分钟)
ama-logs 与 ama-logs-rs Running。kubectl logs 能看到访问日志;把 loadgen 改回含 /error 的版本(模块 0 步骤 5),制造 5xx。Pulling/Started/Killing 事件。AMG_MI=$(az grafana show -n $AMG -g $RG --query identity.principalId -o tsv) az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal \ --role "Log Analytics Reader" --scope $LAW_ID
ContainerLogV2 | where $__timeFilter(TimeGenerated) | where PodNamespace == "myapp" and LogMessage has "\" 500 " | summarize errors = count() by bin(TimeGenerated, 1m), PodName | order by TimeGenerated asc把它放在“请求速率 by status”面板下面,两者共享仪表板时间范围;放大 5xx 尖峰时,日志面板同步显示同一时间窗的错误行数与 Pod。
az aks disable-addons --addon monitoring -g $RG -n $AKS。案例 1:日志费用一个月翻三倍
问题:启用时选了 Standard 预设,又开了托管 Prometheus,Perf/InsightsMetrics 与 Prometheus 指标重复;某个 debug 级别的 sidecar 每秒输出数千行。做法:改为 Logs and Events 预设;用 Usage | where TimeGenerated > ago(7d) | summarize GB=sum(Quantity)/1024 by DataType 找出大户;对噪声命名空间做日志排除;调低 sidecar 日志级别。限制:排除后该命名空间排障时就没有日志,需与团队约定。
案例 2:从告警邮件一键到日志
问题:值班收到 MyAppHigh5xxRatio 后要手工拼 KQL。做法:规则注解中放 Grafana 仪表板链接(带 var-cluster 参数);仪表板里 PromQL 与 KQL 面板并排,时间范围自动对齐。限制:注解是静态文本,时间范围要靠 Grafana 链接参数(如 from=now-30m)近似。
案例 3:OOMKilled 的证据链
问题:KubeContainerOOMKilledCount 推荐告警触发,开发说“应用没问题”。做法:PromQL 看 container_memory_working_set_bytes 逼近 limit 的曲线;KQL 查 KubePodInventory 的重启次数变化与 KubeEvents 中的相关事件;ContainerLogV2 看被杀前最后几行日志。三者时间对齐后证据完整。限制:内核 OOM 不一定在容器日志中留下记录,以事件与指标为准。
常见错误与解决
KQL 查询 ContainerLogV2 返回 0 行(ContainerLog 却有数据)
原因:enableContainerLogV2 为 false 或 streams 中只有 Microsoft-ContainerLog;或者刚启用,数据还没到。
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
修复:在数据收集设置中启用 ContainerLogV2 并包含 Microsoft-ContainerLogV2 流;不要同时使用普通流与 HighScale 流。
enable-addons 报错:… monitoring addon … cannot be combined / already enabled
原因:集群已通过另一种方式(--enable-azure-monitor-logs 或门户)启用,两种方式互斥。
修复:先用同一种方式关闭,再按需启用;保持团队统一使用一种方式(IaC 中固定)。
ama-logs Pod CrashLoopBackOff / OOMKilled
原因:节点日志量极大或节点资源紧张。
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
修复:评估高规模模式;排除噪声命名空间;标签选择器以实际 Pod 标签为准。
Grafana Azure Monitor Logs 面板:The user or service principal does not have access to the workspace
原因:Grafana 托管标识对 law-prom-lab 没有读取权限。
修复:授予 Log Analytics Reader(或 Monitoring Reader)后刷新数据源。
门户 Insights 页面提示需要启用性能数据
原因:使用 Logs and Events 预设时没有 Perf/InsightsMetrics,部分基于日志的旧视图无数据。
修复:性能视图改用托管 Prometheus 驱动的视图与 Grafana 预置仪表板;确需旧视图再切换 Standard 预设并评估费用。
1. 为 aks-prom-lab 启用 Container Insights,只采集 ContainerLogV2 与 KubeEvents,写入 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. 用 KQL 统计过去 7 天各表的摄取量(GB)。
Usage | where TimeGenerated > ago(7d) | summarize GB = sum(Quantity) / 1024 by DataType | order by GB desc
团队想“把所有东西都放进 Log Analytics,方便 KQL 一站式查询”,包括每 30 秒一次的应用指标。你怎么评估?
不建议。指标按样本计费在托管 Prometheus 中极便宜(每千万样本约 0.16 USD),而写进 Log Analytics 按 GB 计费(canadacentral 2.76 USD/GB),高频数值数据会被放大成大量行;PromQL 的 rate/histogram_quantile 也更适合指标。推荐:指标 → 托管 Prometheus;日志、事件、清单 → Log Analytics(Logs and Events 预设);在 Grafana 中并排关联;需要 KQL 联合分析时,再对少量聚合结果做导出或使用工作簿。
经核实的教学视频
官方文档
视频分镜脚本(约 80 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:一个 Pod 发出两条线:绿色的 /metrics 线去 Azure Monitor 工作区,橙色的 stdout 线去 Log Analytics。
旁白:同一个 Pod 的数据走两条路:指标进托管 Prometheus,日志进 Log Analytics。
画面:四个成本预设卡片,“日志与事件”卡片亮起并标注“已启用托管 Prometheus 时推荐”。
旁白:性能数据交给 Prometheus,Container Insights 只收日志、事件和 Pod 清单,避免重复付费。
画面:Grafana 中 5xx 曲线出现尖峰,鼠标框选尖峰,下方 KQL 面板同步缩放显示 500 日志行。
旁白:在同一个仪表板里并排放 PromQL 和 KQL 面板,时间范围一致,从“何时”直接跳到“为什么”。
画面:Usage 表查询结果柱状图,ContainerLogV2 占比最高。
旁白:最后,用 Usage 表定期检查谁在产生日志费用。
模块 7 · 云上排错实战
- 掌握七跳排查法,每一跳知道看哪个命令/日志/指标。
- 识别托管服务特有的问题:DCR/DCE 缺失、写入令牌失败、活动序列/每分钟事件配额限流、查询 403、大小写不敏感导致序列合并、重复序列 422、查询必须带
__name__。 - 会用 debug 模式(9091 端口)查看采集器实际抓到的指标,会使用官方排障脚本收集诊断包。
What:七跳模型
| # | 跳 | 观察点 | 典型症状 |
|---|---|---|---|
| 1 | 附加组件运行 | kubectl get pods -n kube-system | grep ama-metrics;describe 看重启原因 | Pod 不存在 / CrashLoop / OOMKilled |
| 2 | 配置处理 | operator-targets 的 config-reader 日志(prometheus-config-merger 段) | 自定义任务不出现、ConfigMap 被拒 |
| 3 | 目标发现 | targetallocator 日志;采集 Pod :9090/service-discovery | Monitor 存在但没有目标 |
| 4 | 抓取 | :9090/targets(lastError)、up;debug 模式 :9091/metrics | up=0、标签超限、TLS/认证失败 |
| 5 | 写入 | prometheus-collector 与 addon-token-adapter 日志 | “No configuration present for the AKS resource”、令牌错误 |
| 6 | 工作区配额 | 工作区指标 Active Time Series % Utilization、Events Per Minute Received % Utilization | 部分数据缺失、限流 |
| 7 | 读取 | 调用方在工作区上的角色;查询语义 | 403、查询报错、结果“奇怪地合并” |
Why:托管服务特有的“坑”
- 大小写不敏感:工作区把只差大小写的指标名/标签名/标签值视为同一序列,同时间戳写入时随机丢一个,查询返回的大小写不可预测;同一样本里出现只差大小写的两个标签(如
ExampleLabel与examplelabel)会被视为重复标签而丢弃。 - 重复序列返回 422:例如两个不同资源组里的同名集群写入同一工作区、时间戳与值完全相同。官方建议加唯一标签(
cluster_alias或 relabel)。 - 查询 API 限制:时序查询必须有且只有一个
__name__匹配器;/series不支持正则过滤、最多 12 小时;/query_range最多 32 天(含区间选择器)。 - 采集空洞:节点升级时集群级采集器所在节点重建,会有 1–2 分钟空洞(预期行为)。
- 配额:每个工作区有活动时间序列与每分钟事件的默认上限,可通过支持请求提高;官方建议对配额利用率设置告警。
How:排查顺序
永远从数据源头往下游查(1 → 7),每一跳给出“是/否”结论再前进;不要一上来就改 Grafana。对“部分数据缺失”优先看第 6 跳(配额)与最小采集的 keep list;对“全部数据缺失”优先看第 1、5 跳。
When:什么时候用 debug 模式与排障脚本
- 目标 up=1 但某个指标查不到 → 打开 debug 模式(settings ConfigMap
debug-mode的enabled = true),在:9091/metrics看采集器真正收到的数据,确认是被 relabel/keep list 丢弃还是摄取阶段丢弃。debug 模式影响性能,只短时间开启。 - 启用阶段就失败、或要开支持工单 → 运行官方 GitHub 上的排障 PowerShell 脚本,附上生成的文件。
与自建 Prometheus 排错对比
| 问题 | 自建(第 1、2 课) | 托管(本课) |
|---|---|---|
| 看目标 | Prometheus /targets | 采集 Pod 的 :9090/targets(Agent 模式 UI) |
| 看配置 | /config、promtool | :9090/config、promconfigvalidator、config-reader 日志 |
| 存储问题 | 磁盘满、WAL 损坏 | 配额限流、DCR/DCE 缺失 |
| 查询权限 | 通常无 | Monitoring Data Reader |
七跳排查图
症状 → 最可能的跳
故障注入游戏:哪一跳断了?
点击“出题”,模拟器随机注入一个真实故障,并给出你在值班时能看到的症状与日志片段。点击你认为断开的那一跳,然后看解析与修复命令。连续答对 5 题算通关。
排障命令速查(按跳)
| 跳 | 命令 | 看什么 |
|---|---|---|
| 1 | kubectl get pods -n kube-system | grep ama-metrics | Running;重启次数 = 应用 ConfigMap 次数 |
| 2 | kubectl logs <operator-targets> -n kube-system -c config-reader | 解析/合并/校验错误 |
| 3 | kubectl logs <operator-targets> -n kube-system -c targetallocator | Monitor 是否被识别、Secret 权限 |
| 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 | 认证、DCR 配置、MetricsExtension 错误 |
| 6 | az monitor metrics list --resource $AMW_ID --metric … | 活动序列与每分钟事件利用率 |
| 7 | az role assignment list --scope $AMW_ID | 调用方有无 Monitoring Data Reader |
source ~/promlab/azure/env.sh
AMW_ID=$(az monitor account show -n $AMW -g $RG --query id -o tsv)
# 第 1 跳
kubectl get pods -n kube-system | grep ama-metrics
# 第 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'
# 第 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
# 第 6 跳:工作区的利用率指标(名称以 az monitor metrics list-definitions 输出为准)
az monitor metrics list-definitions --resource $AMW_ID --query "[].name.value" -o tsv
# 第 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
官方文档在门户中列出的指标显示名为 Active Time Series % Utilization 与 Events Per Minute Ingested/Received % Utilization;CLI 中的内部名称以 list-definitions 实际输出为准,上面输出为示例。
debug 模式
# 在 ama-metrics-settings-configmap 的 debug-mode 中把 enabled 设为 true(官方:短时间使用),apply 后等待 Pod 重启 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 # 完成后改回 false
官方排障脚本
# 见 https://github.com/Azure/prometheus-collector/tree/main/internal/scripts/troubleshoot # 按 README 下载并在 PowerShell 7+ 中运行,生成的诊断文件可附在支持工单中
实验 7:五个故障的复现、诊断与修复(约 9 分钟)
每个故障都在实验环境中可逆。做完一个就恢复,再做下一个。费用:无额外资源。
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
诊断:报错直接指出版本。若集群装了开源 CRD,apply 会成功但目标不出现——这更隐蔽。修复:使用 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"}]'
# 2–3 分钟后:工作区中 up{namespace="myapp"} 消失;:9090/targets 中没有 myapp
kubectl patch podmonitor.azmonitoring.coreos.com myapp -n myapp --type json \
-p '[{"op":"replace","path":"/spec/podMetricsEndpoints/0/port","value":"http"}]'
诊断:/service-discovery 中能看到 Pod 被发现但被丢弃(端口名不匹配)。模块 5 的 MyAppPodsMissing 告警会在 3 分钟后触发——这是“告警覆盖抓取配置错误”的价值。
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 # 刷新 Grafana 面板 → 权限错误;同时你的 curl 查询仍然正常(不同身份) az role assignment create --assignee-object-id $AMG_MI --assignee-principal-type ServicePrincipal --role "Monitoring Data Reader" --scope $AMW_ID
# 在 settings ConfigMap 的 prometheus-collector-settings 中设置 cluster_alias = "akspromlab",apply # 新数据的 cluster 标签变为 akspromlab;规则组 clusterName 仍为 aks-prom-lab → 告警不再评估到新数据 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]]' # 修复二选一:把 cluster_alias 改回 "";或 az alerts-management prometheus-rule-group update -n myapp-rules -g $RG --cluster-name akspromlab
注意 cluster_alias 只允许字母数字,其他字符会被替换为下划线;改别名后,历史数据仍是旧标签,仪表板 $cluster 变量会出现两个值。
# 构造两条只差大小写的序列(用一个临时静态目标):
kubectl -n myapp create configmap casing --from-literal=metrics='demo_metric{Env="Prod"} 1
demo_metric{Env="prod"} 2
'
# 思考题:用 ConfigMap 自定义任务抓取一个返回上述内容的静态 HTTP 端点后,工作区中会有几条 demo_metric?
# 答案:1 条(被视为同一序列,值随机保留其一,返回的大小写不可预测)。
kubectl -n myapp delete configmap casing
实验中不必真的部署端点;重点是理解:在托管工作区中,标签值的大小写不能作为区分维度,应用侧统一小写。
up{namespace="myapp"} = 2,Grafana 正常,规则组 clusterName 与数据一致)。案例 1:周一早上部分指标缺失
问题:业务大促前上线了带 user_id 标签的指标,周一起部分仪表板出现断点。做法:工作区指标显示活动时间序列利用率持续 100%(第 6 跳);用 count by (__name__) ({__name__=~"shop_.*"}) 找到暴涨的指标;在 PodMonitor 中 labeldrop 去掉 user_id,同时提交配额提升工单(附工作区 ID、内部 ID、区域)。限制:配额提升不是解决基数问题的正确方式,只能争取时间;第 7 课详讲基数治理。
案例 2:私有集群启用后一直没数据
问题:prometheus-collector 每 5 分钟打印 “No configuration present for the AKS resource”,Pod 每 15 分钟重启。做法:按官方三条检查:DCR/DCE 存在、工作区存在、私有集群未被链接到其他服务的 AMPLS;发现网络团队把集群加入了日志专用的 AMPLS。调整 Private Link 设计后恢复。限制:私网场景务必先读官方 Private Link 文档再上线。
案例 3:两个环境数据“打架”
问题:测试与生产集群都叫 aks-app(不同资源组),共用一个工作区,偶发写入 422,图表出现锯齿。做法:两边分别设置 cluster_alias = "aksappprod"/"aksapptest",规则组 clusterName 同步更新,仪表板按新标签筛选。限制:更好的做法是生产与测试使用不同工作区(权限与费用也能分开)。
常见错误与解决
No configuration present for the AKS resource
原因:DCR/DCE/工作区缺失或关联丢失;私有集群 + AMPLS 不受支持的组合。
修复:确认资源存在;--disable-azure-monitor-metrics 后重新启用;按官方 Private Link 文档调整。
ama-metrics Pod 重启次数远多于 ConfigMap 变更次数,Reason: OOMKilled
原因:采集量超过采集器内存能力。
kubectl describe pod -n kube-system $RS | grep -A4 "Last State"
修复:参考官方“高规模”与“采集副本 HPA”文档;减少目标/指标;节点级任务下沉到 DaemonSet。
422 Unprocessable Entity(duplicate time series)
原因:两条来源产生了标签完全相同的序列(同名集群写同一工作区、同时用附加组件与 remote_write 写同一集群)。
修复:加唯一标签(cluster_alias、relabel 注入),或只保留一条写入路径。
查询报错:query must contain a metric name matcher(或类似提示)
原因:托管 API 要求每个时序查询带且只带一个 __name__ 匹配器,例如 {namespace="myapp"} 这样的裸选择器不被接受。
修复:写成 {__name__=~"myapp_.*", namespace="myapp"} 或指定具体指标名。
/targets 中 myapp 为 up,但工作区查不到 myapp_redis_up
原因:Monitor 的 metricRelabelings keep 正则写错(如 myapp_http.*),或应用该时刻没有输出该指标(多进程模式下 Gauge 只在调用过 /metrics 的 worker 中有值)。
kubectl get podmonitor.azmonitoring.coreos.com myapp -n myapp -o jsonpath='{.spec.podMetricsEndpoints[0].metricRelabelings}'
修复:修正正则;用 debug 模式 :9091/metrics 确认采集器收到的内容。
1. 查看采集副本中负责写入认证的容器日志。
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. 找出工作区中每个集群当前有多少个 up 序列(用于发现 cluster 标签冲突)。
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]]'
值班收到“Grafana 上 myapp 仪表板全部空白”。kubelet/cAdvisor 的预置仪表板也空白,你同事的 curl 查询却正常返回数据。最可能断在哪?怎么确认?
数据写入正常(同事能查到),问题在第 7 跳 Grafana 侧的读取身份:Grafana 托管标识失去 Monitoring Data Reader、系统托管标识被关闭/替换、或数据源 URL 被改。确认:az grafana show --query identity;az role assignment list --scope $AMW_ID --assignee <MI>;在 Grafana 数据源页点击 “Save & test”。修复后刷新。若同事也查不到,再回到第 1/5 跳。
经核实的教学视频
官方文档
- Troubleshoot collection of Prometheus metrics
- Monitor Azure Monitor workspace ingestion limits
- Azure Monitor service limits(Prometheus metrics)
- 官方排障脚本(GitHub)
视频分镜脚本(约 90 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:七个方块横排,从“附加组件”到“读取”,Grafana 空白面板在最右边闪烁。
旁白:Grafana 没数据,问题可能出在七跳中的任何一跳。永远从左往右查。
画面:终端分屏:config-reader 日志、targets 页面、collector 日志依次高亮。
旁白:前五跳在集群里,用 kubectl 就能看到:配置有没有被接受,目标有没有被发现,抓取和写入有没有报错。
画面:工作区指标图表,活动时间序列利用率一路爬到百分之百。
旁白:部分数据缺失时,先看工作区配额。高基数标签往往是罪魁祸首。
画面:两个标签 Prod 和 prod 合并成一个,旁边写着“case-insensitive”。
旁白:最后记住两条托管特性:大小写不敏感,以及查询必须带指标名。
模块 8 · 成本、清理与自测
- 说出托管 Prometheus、Log Analytics、Managed Grafana、AKS 的计量单位,能用“序列数 × 采集频率”估算月度摄取费用。
- 掌握五个降本手段:最小采集 + keep list、降低采集频率、metricRelabelings 丢弃高基数、日志预设与命名空间排除、仪表板刷新与时间范围控制。
- 列出本课用到的最小权限,并按顺序完整清理(含托管资源组、默认工作区、节点资源组、kubeconfig 上下文与 Entra 角色分配)。
What:计量项(canadacentral,零售价 API 2026-11-15 查询,USD,仅供估算)
| 服务 | 计量项 | 单价(零售价 API) | 驱动因素 |
|---|---|---|---|
| Azure Monitor 托管 Prometheus | Metrics ingestion(摄取样本) | 0.16 / 1000 万样本 | 活动序列数 × 采集频率 |
| Prometheus Metrics Queries(查询处理样本) | 0.001 / 1000 万样本 | 仪表板刷新、规则评估、API 查询 | |
| Log Analytics | Analytics Logs Data Ingestion | 2.76 / GB(有免费额度行);保留 0.12 / GB / 月(超出免费保留期后) | 日志行数与大小 |
| Managed Grafana Standard | Standard Node | 0.04104 / 小时 | 实例运行时长(实例对应的计费节点数以定价页为准) |
| Standard User | 6 / 活跃用户 / 月 | 当月登录的用户 | |
| Standard Zone Redundancy | 0.04932 / 小时 | 启用区域冗余时 | |
| AKS 节点 | Standard_D2s_v5(Linux 按需) | 0.107 / 小时 / 台 | 节点数 × 时长;Free 层控制面不收费 |
| Azure Monitor 告警通知 | Emails | 免费额度后 0.00002 / 封 | 通知数量 |
说明:零售价 API 中 2026-10 起还出现了 “Metric Samples Ingested 0.11 / 1000 万”“Metric Samples Processed 0.05 / 1000 万” 等新计量项,其与托管 Prometheus 的对应关系未能在定价页上确认,本课按 “Metrics ingestion / Prometheus Metrics Queries” 估算,以 Azure Monitor 定价页 与 Managed Grafana 定价页 为准。
Why:钱花在哪
摄取样本 = Σ(每条活动序列 × 每分钟采集次数)。例:3,000 条序列、30 秒采集 → 每月 3,000 × 2 × 60 × 24 × 30 ≈ 2.59 亿样本 ≈ 4.15 USD。同样的序列改成 60 秒采集,费用减半;序列翻 10 倍(高基数标签),费用也翻 10 倍。相比之下,日志很容易成为大头:每天 1 GB 的访问日志 ≈ 每月 83 USD。
How:五个降本手段
- 保持最小采集:只用 keep list 追加需要的指标,不关闭
minimal-ingestion-profile。 - 调整频率:
default-targets-scrape-interval-settings与 Monitor 的interval;非关键目标 60s。 - 丢弃高基数:
metricRelabelings的drop/labeldrop;直方图只保留需要的桶。 - 日志:Logs and Events 预设、命名空间排除、调低应用日志级别、评估 Basic/Auxiliary 表计划。
- 查询:仪表板刷新间隔 ≥ 1m、默认时间范围不过长、用 recording rule 预聚合给大面板使用。
When:什么时候删、怎么删
- 实验结束立即删除资源组
rg-prom-lab:其中的 AKS、ACR、工作区、Grafana、Log Analytics、规则组、Action Group 一并删除。 - 随后检查“自动生成”的资源:
MC_rg-prom-lab_aks-prom-lab_canadacentral(节点资源组,随 AKS 删除)、MA_amw-prom-lab_canadacentral_managed(工作区的 DCR/DCE)、DefaultRG-*/DefaultAzureMonitorWorkspace-*/DefaultWorkspace-*(若曾未指定工作区启用)。 - Log Analytics 工作区删除后默认进入软删除期(可恢复),需要立即复用同名时用
--force永久删除(以官方为准)。
最小权限一览
| 操作 | 最小角色(作用域) |
|---|---|
| 创建 AKS / 工作区 / Grafana / Log Analytics | Contributor(资源组) |
| 启用时链接 Grafana(自动分配角色) | Owner,或 Contributor + User Access Administrator |
| 创建规则组 | Monitoring Contributor(资源组) |
| 查看监控数据(门户) | Monitoring Reader / Monitoring Contributor |
| PromQL 读取工作区 | Monitoring Data Reader(工作区) |
| 访问 Grafana UI | Grafana Viewer / Editor / Admin(Grafana 实例) |
| 给他人分配 Grafana 角色 | Role Based Access Control Administrator / User Access Administrator / Owner |
费用构成图
清理顺序图
费用计算器(按本页单价估算,仅供量级参考)
调整参数,计算器按“序列数 × 每分钟采集次数 × 分钟数”算摄取样本,并给出各项月度费用与最大头。单价来自零售价 API(canadacentral,2026-11-15),实际以定价页与账单为准。
费用与清理命令
| 命令 | 作用 | 说明 |
|---|---|---|
curl prices.azure.com/api/retail/prices?$filter=… | 查询零售单价 | 公开 API,无需登录 |
az consumption usage list / 门户成本分析 | 查看实际花费 | 按资源组筛选 rg-prom-lab |
az alerts-management prometheus-rule-group update --enabled false | 删除前停用规则 | 避免误报 |
az group delete -n rg-prom-lab --yes | 删除全部实验资源 | 不可恢复(LAW 软删除除外) |
az group list --query "[?starts_with(name,'MA_')…]" | 检查托管/默认资源组残留 | 确认后再删 |
kubectl config delete-context aks-prom-lab | 清理本地 kubeconfig | 同时删 cluster/user 条目 |
# 查询本课用到的单价(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
用 PromQL 估算自己的摄取量
// 每个 job 的活动序列数(在 Grafana Explore 中执行)
count by (job) ({__name__=~".+", cluster="aks-prom-lab"})
// 抓取样本数(每次抓取)
sum by (job) (scrape_samples_post_metric_relabeling{cluster="aks-prom-lab"})
注意第一条查询本身会扫描大量样本(产生查询费用),只在需要时执行;scrape_samples_post_metric_relabeling 是否被采集取决于最小采集配置,查不到时用工作区的 “Active Time Series” 指标代替。
完整清理
source ~/promlab/azure/env.sh
# ① 导出需要保留的内容
az grafana backup -n $AMG -g $RG -d ~/promlab/azure/grafana-backup --components dashboards folders || true
# ② 停用规则组(含推荐告警创建的组)
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
# ③ 删除资源组(AKS、ACR、工作区、Grafana、LAW、规则组、Action Group)
az group delete -n $RG --yes
# ④ 检查残留
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
# ⑤ 本地与身份
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 # 孤立的角色分配(主体已删除)
(无输出) (无输出) (无输出)
常见错误:资源组删除需要数分钟,期间再次执行会提示正在删除;托管资源组 MA_* 若残留且确认工作区已删除,可单独删除。孤立角色分配的查询条件为常用写法,结果以实际为准,删除前逐条确认。
实验 8:估算本实验费用并完整清理(约 5 分钟 + 等待删除)
rg-prom-lab 筛选(费用数据通常有数小时延迟)。DefaultRG-canadacentral,确认无其他集群使用后删除。~/promlab/azure 中保留 YAML/JSON 以便第 6 课复用。案例 1:月度账单中 Prometheus 摄取突增 8 倍
问题:某团队为排障临时关闭了最小采集配置,忘记恢复。做法:启用工作区摄取利用率推荐告警;settings ConfigMap 纳入 GitOps,变更需评审;平台用 Azure Policy 审计。限制:恢复配置后已摄取的样本仍按量计费。
案例 2:Grafana 用户费用
问题:全员都被授予 Grafana Viewer,每月活跃用户数波动大。做法:按需授权到 Entra 组,非值班人员通过定期导出的报表(Standard 支持报表/渲染)查看;评估门户内置 Grafana 视图满足只读场景。限制:计费按“活跃用户”,未登录的用户不计费(以定价页为准)。
案例 3:实验订阅的“僵尸资源”
问题:培训结束一个月后,订阅里仍有 12 个 DefaultAzureMonitorWorkspace-* 与若干 Grafana。做法:实验统一使用带过期标签的资源组(--tags expires=2026-11-30),夜间脚本删除过期资源组并检查 Default* 与 MA_* 残留。限制:默认工作区可能被生产集群共用,自动删除前必须检查关联集群。
交互式排障决策树(覆盖全课)
从症状出发逐步回答问题,得到诊断与修复命令。
清理与成本相关错误
az group delete 卡住或失败:… is locked / ScopeLocked
原因:资源组或资源上有删除锁(组织策略或手动添加)。
az lock list -g $RG -o table
修复:有权限的人删除锁后重试;不要在共享环境中随意删除他人的锁。
删除后重新创建同名 Log Analytics 工作区失败 / 数据“复活”
原因:工作区处于软删除期,同名创建会恢复旧工作区。
修复:需要全新工作区时,删除时使用 az monitor log-analytics workspace delete --force true(永久删除,以官方为准)或换名。
账单中仍有 Azure Monitor 摄取费用,但 rg-prom-lab 已删除
原因:另有集群仍在向默认工作区或其他工作区写入;或费用是删除前产生、延迟入账。
az monitor account list -o table
az aks list --query "[?azureMonitorProfile.metrics.enabled].{name:name,rg:resourceGroup}" -o table
修复:定位并关闭不需要的附加组件,删除无用工作区。
1. 一条命令删除整个实验环境(不等待提示)。
az group delete -n rg-prom-lab --yes --no-wait
2. 列出订阅中仍启用了托管 Prometheus 的 AKS 集群。
az aks list --query "[?azureMonitorProfile.metrics.enabled].{name:name,rg:resourceGroup}" -o table一个 40 节点集群启用托管 Prometheus 后,活动序列约 15 万、30 秒采集。财务问“每月多少钱、怎么降”。你如何回答?
摄取:150,000 × 2 × 60 × 24 × 30 ≈ 129.6 亿样本 ≈ 1,296 × 0.16 ≈ 207 USD/月(按本课单价)。查询费用通常远低于摄取(0.001/千万样本)。降本:① 确认最小采集仍开启,审视 keep list;② 用 count by (__name__) 找前 10 大指标,丢弃不用的直方图桶与高基数标签;③ 非关键目标改 60s(直接减半);④ 日志用 Logs and Events 预设;⑤ Grafana 按组授权控制活跃用户。最终以定价页与成本分析为准。
经核实的教学视频
未找到专门讲“托管 Prometheus + Managed Grafana 费用与清理”且经核实的视频,请使用下方分镜脚本。
官方文档
视频分镜脚本(约 80 秒)
本课件无法直接生成视频/MP3,已提供分镜和讲解稿,可交给视频工具生成。
画面:四个硬币堆:摄取样本、查询样本、日志 GB、Grafana;摄取那一堆随“序列数”滑块变高。
旁白:托管监控的账单由四项组成,摄取量等于序列数乘以采集频率。
画面:计算器动画:三千条序列、三十秒采集,结果约四美元;日志每天一 GB,结果约八十美元。
旁白:指标通常很便宜,日志反而容易成为大头。
画面:五个降本杠杆依次亮起:最小采集、六十秒采集、丢弃高基数标签、日志预设、仪表板刷新间隔。
旁白:五个杠杆,先从最小采集和高基数标签开始。
画面:终端执行 az group delete,随后三条残留检查命令都无输出。
旁白:最后,删除资源组,再检查托管资源组和默认工作区,确认一个不剩。
命令速查表
变量与前提
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 # 官方要求工作区与启用
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
抓取配置
apiVersion: azmonitoring.coreos.com/v1
kind: PodMonitor # 或 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 自定义任务(kube-system,键 prometheus-config):
# kubectl create configmap ama-metrics-prometheus-config --from-file=prometheus-config -n kube-system
# 设置:ama-metrics-settings-configmap(schema v2,模板 aka.ms/azureprometheus-addon-settings-configmap)查询工作区
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"
# 限制:必须有 __name__ 匹配器;query_range ≤ 32 天;series ≤ 12 小时;大小写不敏感Managed Grafana
az grafana create -n $AMG -g $RG -l $LOC --sku-tier Standard AMG_ID=$(az grafana show -n $AMG -g $RG --query id -o tsv) AMG_MI=$(az grafana show -n $AMG -g $RG --query identity.principalId -o tsv) az grafana integration monitor add -g $RG -n $AMG --monitor-rg-name $RG --monitor-name $AMW # 预览 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
规则组与 Action Group
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
# 规则字段:record|alert, expression, for: PT5M, severity: 0-4,
# resolveConfiguration: {autoResolved, timeToResolve}, actions: [{actionGroupId}]Container Insights
az monitor log-analytics workspace create -g $RG -n $LAW -l $LOC
LAW_ID=$(az monitor log-analytics workspace show -g $RG -n $LAW --query id -o tsv)
echo '{"interval":"1m","enableContainerLogV2":true,"streams":["Microsoft-ContainerLogV2","Microsoft-KubeEvents","Microsoft-KubePodInventory"]}' > dcs.json
az aks enable-addons --addon monitoring -g $RG -n $AKS --workspace-resource-id $LAW_ID --data-collection-settings dcs.json
kubectl get ds ama-logs -n kube-system; kubectl get deploy ama-logs-rs -n kube-system
az monitor log-analytics query -w $(az monitor log-analytics workspace show -g $RG -n $LAW --query customerId -o tsv) \
--analytics-query 'ContainerLogV2 | where PodNamespace=="myapp" | take 5' -o table排障(七跳)
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:工作区指标 Active Time Series % / Events Per Minute % Utilization az role assignment list --scope $AMW_ID -o table # 7
快速排错表
| 症状 | 最可能原因 | 第一条命令 |
|---|---|---|
| 所有指标都没有 | 附加组件未运行 / DCR/DCE 缺失 | kubectl get pods -n kube-system | grep ama-metrics |
| myapp 没有,默认指标有 | API 组写错、端口未命名、选择器不匹配 | kubectl get podmonitors.azmonitoring.coreos.com -A |
| up=1 但某指标没有 | 最小采集 keep list / metricRelabelings | debug 模式 :9091/metrics |
| 间歇缺数据 | 配额限流 / 节点升级空洞 | 工作区 % Utilization 指标 |
| Grafana 403 | 托管标识缺 Monitoring Data Reader | az role assignment list --scope $AMW_ID |
| 规则不触发 | clusterName / scope 与数据不一致 | az alerts-management prometheus-rule-group show |
| 告警无邮件 | 规则无 actions / 接收方退订 / 告警处理规则 | az monitor action-group show |
| ContainerLogV2 为空 | 未启用 V2 / 流名写错 | az aks show --query addonProfiles.omsagent |
| 写入 422 | 重复序列(同名集群/双写) | count by (cluster) (up) |
推荐配置片段
settings ConfigMap:只追加需要的指标
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:丢弃高基数标签
metricRelabelings:
- action: labeldrop
regex: 'user_id|session_id'
- sourceLabels: [__name__]
action: keep
regex: 'myapp_.*'综合实验 + 结业测验
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;在采集副本 :9090/targets 看到 2 个 up 目标。myapp-dashboard.json;把一个 Entra 组授予 Grafana Viewer。ag-prom-lab 与 myapp-rules;保持 loadgen 含 /error,约 6–8 分钟后收到 MyAppHigh5xxRatio;改 loadgen 后收到 Resolved。law-prom-lab,启用 monitoring 附加组件(Logs and Events 三个流);给 Grafana 托管标识 Log Analytics Reader;在 myapp 仪表板添加 KQL 面板。metrics,确认 MyAppPodsMissing 在 3–5 分钟内触发;恢复后自动解决。开放式自测(先自己回答,再展开参考答案)
1. 托管 Prometheus 中,一个样本从 myapp 到 Grafana 面板经过哪些组件与身份?
target allocator(operator-targets)把 PodMonitor 目标分配给 ama-metrics 副本 → prometheus-collector 抓取 /metrics、relabel、加 cluster 标签 → addon-token-adapter 用集群托管标识换取 Entra 令牌 → 样本写入工作区 DCE,DCR 路由到 amw-prom-lab → Grafana 以自己的系统托管标识获取受众为 https://prometheus.monitor.azure.com 的令牌,凭工作区上的 Monitoring Data Reader 调用查询端点 → 浏览器中的用户通过 Entra 登录,凭 Grafana 实例上的 Grafana 角色查看。
2. PodMonitor、ServiceMonitor、ConfigMap、Pod 注解四种入口如何选择?
Operator 风格且需要每 Pod 抓取 → PodMonitor;已有 Service → ServiceMonitor;迁移现成 prometheus.yml 或需要 static_configs → ama-metrics-prometheus-config;快速试用 → 注解 + podannotationnamespaceregex。同一目标只用一种。节点级目标用 -node ConfigMap 且只抓 $NODE_IP。
3. 为什么 Grafana Viewer 能看到他本人在 Azure 上无权访问的数据?如何设计隔离?
Grafana 用自己的托管标识查询,数据可见范围等于该标识的角色范围。隔离:Limited Viewer + 文件夹/仪表板权限;敏感数据独立工作区与数据源,并限制数据源权限;必要时拆分 Grafana 实例。
4. 第 2 课的 Alertmanager 路由树在托管路径中如何实现?
托管规则组没有路由树:每条告警规则通过 actions[].actionGroupId 直接指定 Action Group;可按 team 拆分规则组与 Action Group;静默/维护窗口用告警处理规则;复杂路由可通过 Webhook 接自有服务。
5. 指标与日志分别放在哪里?为什么不都放进 Log Analytics?
指标 → Azure Monitor 工作区(按样本计费,每千万样本约 0.16 USD,PromQL 适合聚合与告警);日志、事件、清单 → Log Analytics(按 GB,2.76 USD/GB)。高频数值数据写日志表会被放大成大量行,费用与查询效率都更差。启用托管 Prometheus 时 Container Insights 用 Logs and Events 预设。
6. 清理时除了删除 rg-prom-lab,还要检查什么?
节点资源组 MC_rg-prom-lab_aks-prom-lab_canadacentral(通常随 AKS 删除)、工作区托管资源组 MA_amw-prom-lab_canadacentral_managed、默认工作区与 DefaultRG-*、推荐告警创建的规则组、孤立的角色分配、本地 kubeconfig 上下文;Log Analytics 软删除。
结业测验(12 题,覆盖全部模块)
来源与版本说明
| 主题 | 核实结论 | 来源 |
|---|---|---|
| 启用托管 Prometheus | az aks create/update --enable-azure-monitor-metrics,可选 --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;需托管标识集群、资源提供程序 Microsoft.ContainerService/Insights/AlertsManagement/Monitor(Grafana 订阅需 Microsoft.Dashboard);须卸载 aks-preview;不指定工作区时使用 DefaultAzureMonitorWorkspace-<region>(DefaultRG-<region>);链接 Grafana 需 Owner 或 Contributor + User Access Administrator | Enable monitoring for AKS(ms.date 2026-08-18,更新 2026-11-10) |
| Container Insights | az aks enable-addons --addon monitoring --workspace-resource-id --data-collection-settings;JSON 字段 interval / namespaceFilteringMode / namespaces / enableContainerLogV2(默认 true)/ streams;成本预设 Logs and Events(默认)/ Syslog / Standard / Cost-optimized;“Logs and events” 分组注明启用托管 Prometheus 时推荐;流名列表;验证 ama-logs DS 与 ama-logs-rs | 同上 |
| az aks 新参数 | CLI 参考中出现 --enable-azure-monitor-logs(经 Azure Monitor profile 配置 Container Insights,不能与 --enable-addons monitoring 同用)、OTLP 相关参数 | az aks CLI reference(访问 2026-11-15) |
| 默认目标与最小采集 | 默认启用 cadvisor、nodeexporter、kubelet、kube-state-metrics、networkobservabilityRetina;默认禁用 coredns、kubeproxy、apiserver;控制面 apiserver/etcd;最小采集默认开启;默认 recording rules 与 ux 规则;链接 Grafana 后预置仪表板 | Default Prometheus metrics configuration(2026-08-18) |
| settings ConfigMap | ama-metrics-settings-configmap(kube-system,默认不存在),schema v2:cluster-metrics / controlplane-metrics / prometheus-collector-settings;默认目标 30s;应用后 2–3 分钟 Pod 重启;cluster_alias 仅字母数字;debug 模式;ksm-config;模板中 secrets_access_namespaces、deny_fs_access_through_sms | Customize scraping using ConfigMap(更新 2026-10-13)· 官方模板(2026-11-15 取回) |
| 自定义抓取 ConfigMap | ama-metrics-prometheus-config(副本,推荐)、-node、-node-windows;数据键 prometheus-config;promconfigvalidator 位于 /opt/promconfigvalidator;仅支持 static_configs 与 kubernetes_sd_configs;ConfigMap 方式不支持全局 external_labels;不支持重命名指标;ama-metrics-mtls-secret | Custom scrape jobs using ConfigMap(更新 2026-07-17) |
| PodMonitor / ServiceMonitor | API 组 azmonitoring.coreos.com/v1;可部署在任意命名空间;与开源 CRD 不冲突且不读取开源对象;端口需命名;模板含 labelLimit 63 / labelNameLengthLimit 511 / labelValueLengthLimit 1023;K8s 1.37+ Secret 访问改为按命名空间(secrets_access_namespaces + Role/RoleBinding 到 ama-metrics-serviceaccount) | Custom scrape jobs using CRDs(2026-11-09) |
| 排障 | Pod:ama-metrics-operator-targets-*、ama-metrics-ksm-*、ama-metrics-node-*(及副本 ama-metrics-*);容器 prometheus-collector、config-reader、targetallocator、addon-token-adapter;9090 UI(/config /service-discovery /targets)、debug 9091;“No configuration present for the AKS resource”;标签限制;工作区利用率指标;托管资源组 MA_<amw>_<region>_managed;节点升级 1–2 分钟空洞 | Troubleshoot Prometheus metrics(更新 2025-06-19) |
| 查询 API | 令牌 resource https://prometheus.monitor.azure.com;角色 Monitoring Data Reader;支持 query / query_range / series / labels / label/__name__/values;必须有 __name__ 匹配器;query_range 32 天、series 12 小时;大小写不敏感;重复序列返回 422;不支持 exemplars | Query Prometheus metrics using API and PromQL(更新 2025-10-01) |
| 规则组 | 类型 Microsoft.AlertsManagement/prometheusRuleGroups,API 2023-03-01;scopes 必含工作区、可加一个集群;clusterName;interval 默认 PT1M;severity 0–4 默认 3;autoResolved 默认 true、timeToResolve 默认 PT5M;需要 Monitoring Contributor;资源运行状况;az-prom-rules-converter;CLI az alerts-management prometheus-rule-group create(alertsmanagement 扩展,参数 --scopes --rules --cluster-name --interval --enabled) | Rule groups(2026-08-07)· CLI reference |
| 推荐告警 | 门户 Alerts → Set up recommendations;ARM/Bicep 模板;社区规则列表(KubePodCrashLooping、KubeContainerOOMKilledCount、KubeNodeUnreachable 等)与平台指标规则;旧 Container insights 指标告警 2024-05-31 退役 | Recommended alert rules(2026-07-21) |
| Action Group CLI | --action email NAME EMAIL_ADDRESS [usecommonalertschema]、webhook/logicapp 等格式;--short-name;默认位置 Global;enable-receiver、test-notifications create | az monitor action-group(2026-11-06) |
| Azure Monitor 工作区 CLI | az monitor account create/show/delete 为核心 CLI(GA) | az monitor account(2026-11-06) |
| Managed Grafana 层级 | Essential 不可新建,2027-03-31 完全弃用;Standard 推荐,X1(默认)/X2(告警规则 500/1000 每组织),可升不可降;区域冗余、确定性出站 IP、私有终结点、告警、SMTP、报表仅 Standard;Grafana Enterprise 可选 | What is Azure Managed Grafana?(2026-06-24) |
| Grafana 角色 | Grafana Admin / Editor / Limited Viewer / Viewer(含角色 ID);Limited Viewer 对应“No Basic Role”,不适用于 v9;分配需 RBAC Administrator / UAA / Owner | Grant users and identities access(2026-09-22) |
| 链接工作区 | 在工作区上给 Grafana 托管标识分配 Monitoring Data Reader;需系统分配托管标识;Integrations → Azure Monitor workspaces;Grafana 13 起由 Azure Monitor Managed Service for Prometheus 插件提供认证;预置仪表板列表 | Add an Azure Monitor workspace(2026-07-03) |
| az grafana CLI | amg 扩展;create 参数 --sku-tier(默认 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(预览,--monitor-rg-name --monitor-name);dashboard import --definition(JSON / gallery ID / 路径 / URL);backup/restore/migrate | az grafana(2026-09-01)· CLI quickstart |
| 价格 | canadacentral(USD):Metrics ingestion 0.16/10M 样本;Prometheus Metrics Queries 0.001/10M 样本;Analytics Logs 摄取 2.76/GB、保留 0.12/GB/月;Managed Grafana Standard Node 0.04104/小时、Standard User 6/月、Zone Redundancy 0.04932/小时;D2s v5 Linux 0.107/小时;Emails 0.00002/封 | Azure Retail Prices API(2026-11-15 查询)· 以定价页为准 |
视频核实说明
以下视频均于 2026-11-15 通过 YouTube oEmbed 接口(https://www.youtube.com/oembed?url=…&format=json)核实标题与频道: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 同名直播(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)。未找到专门讲“托管 Prometheus 规则组”和“托管监控费用与清理”的经核实视频,相应模块提供了分镜脚本。社区视频录制时间较早,参数与界面以本课核实内容为准。
语音讲解说明
“语音”分页使用浏览器 Web Speech API(speechSynthesis,zh-CN)实时朗读讲解稿,英文术语用 en-US 发音;效果取决于操作系统安装的语音包(如 Windows “Microsoft Xiaoxiao”、macOS “Tingting”)。本课件生成环境无法调用 TTS 服务,因此没有内嵌 MP3;讲解稿可直接交给 Azure AI Speech 等工具生成音频。
已知限制
- 本课命令按官方文档编写,未在本环境中实际执行;“预期输出”中的资源 ID、GUID、端点后缀、Pod 名、IP、时间、计数、价格计算结果均为示例值。
promconfigvalidator的输出文本、规则组/数据源的部分 JSON 字段名、工作区利用率指标在 CLI 中的内部名称、ama-metrics各 Pod 的标签选择器(rsName/dsName)与容器数量,可能随附加组件版本变化,以实际输出为准。- 以下内容做了保守处理并标注“以官方为准”:链接 Grafana 时自动分配的是 Monitoring Reader 还是 Monitoring Data Reader(两份官方文档措辞不同,本课以 Monitoring Data Reader 作为读取数据的必要角色);
az grafana create默认创建的角色分配细节;Managed Grafana 当前默认/可选 Grafana 主版本;Standard 实例的计费节点数;零售价 API 中 2026-10 新出现的 “Metric Samples Ingested/Processed” 计量项与托管 Prometheus 的关系;az account get-access-token用户令牌直接查询工作区(官方示例为应用注册);--rules @文件写法;az grafana dashboard import对外层包装的要求;ContainerLogV2 的表计划选项;容器日志命名空间排除 ConfigMap 的具体键;Log Analytics 软删除与--force;告警注解模板渲染。 - 启用指标时为集群创建的 DCR/DCRA 的名称与位置未在本次核实页面中给出,课程中未写死名称。
- 动画中的时间、比例、日志行与费用为机制示意,不代表服务的精确时序或账单。
- 第 1、2、4–8 课与本课并行编写,跨课引用(myapp 源码、第 2 课规则文件名)以课程统一约定为准;本课在模块 0 提供了与约定一致的最小 myapp 实现,便于独立完成。