如何将Metrics标签添加到Prometheus Alert告警标签中?
如何在Prometheus告警规则中添加指标的host标签
你可以通过Prometheus的模板语法直接引用指标的标签,将其添加到告警规则的标签中,正确的配置示例如下:
apiVersion: monitoring.coreos.com/v1 kind: PrometheusRule # 省略其他元数据配置 spec: groups: - name: my-alert rules: - alert: MyMetricsHighAlert expr: my_metrics > 0 labels: severity: warning host: "{{ $labels.host }}" annotations: summary: "my_metrics 值过高,主机: {{ $labels.host }}"
需要注意几个核心要点:
- 保留指标的host标签:如果你的查询使用了聚合函数(比如
sum、avg),必须通过by (host)来保留该标签,例如sum(my_metrics) by (host) > 0,否则聚合操作会丢弃原始标签,导致无法引用$labels.host - YAML语法规范:模板变量
{{ $labels.host }}必须用双引号包裹,防止YAML解析器将其识别为特殊语法而报错 - 完整规则结构:原示例缺少
rules数组和alert名称字段,这是PrometheusRule的必填结构,必须补充完整
内容的提问来源于stack exchange,提问作者YeKc1M
相关产品推荐
相关产品推荐

