You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prometheus AlertManager模板解析问题:提取告警指定字段值

解决Prometheus AlertManager模板提取指定字段问题

问题背景

我已配置Prometheus告警规则将告警发送至Telegram,现在需要调整AlertManager的模板,实现只提取告警中的value数值、正确解析alertname字段,达到预期的输出效果。

当前模板代码

{{ define "test" }}
{{ range .Alerts }}
test_1 : {{ .Annotations.query_value.var }}
test_2 : {{ .Status }}
test_3 : {{ .ValueString }}
test_4 : {{ .Labels.alertname }}

{{ end }}
{{ end }}

当前输出

test_1 : [ var='C0' metric='loki-loki-distributed-ingester-0' labels={pod=loki-loki-distributed-ingester-0} value=6.975442944e+09 ]
test_2 : firing 
test_3 : [ var='C0' metric='loki-loki-distributed-ingester-0' labels={pod=loki-loki-distributed-ingester-0} value=6.975442944e+09 ]  
test_4 : map[alertness Usage - Of Machine Grafana_folder:test-dev-memory-usage ]

修改后的模板代码

{{ define "test" }}
{{ range .Alerts }}
test_1 : value={{ index .ValueMatches 0 "value" }}
test_2 : {{ trim .Status }}
test_3 : value={{ index .ValueMatches 0 "value" }}
test_4 : {{ index .Labels "alertname" }}

{{ end }}
{{ end }}

修改说明

  • 提取value数值:用.ValueMatches获取结构化的告警数值数据,index .ValueMatches 0 "value"可以直接拿到纯净的value值,替代之前输出冗余内容的.Annotations.query_value.var和.ValueString。
  • 规整Status格式:通过trim函数去除.Status前后的空格,让输出更整洁。
  • 正确解析alertname:使用index .Labels "alertname"直接从Labels映射中提取alertname字段,解决之前输出map结构的问题。

修改后输出(符合期望)

test_1 : value=6.975442944e+09
test_2 : firing
test_3 : value=6.975442944e+09
test_4 : Memory Usage - Of Machine

内容的提问来源于stack exchange,提问作者russiaisoccupant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:05:33