如何配置Prometheus告警,实现在Telegram接收含IP标签的告警
问题描述
无法在Telegram中收到Prometheus告警的description和summary字段,原因是告警注解中使用了{{$labels.ip}}标签。移除该标签后可正常收到告警文本,但业务需要显示IP值。
现有配置
1. 流量告警规则(trafic_rules.yml,可正常工作)
groups: - name: Trafic value rules: - alert: Trafic recived by host expr: rate(node_network_receive_bytes_total{device!="lo"}[30s])/1024/1024 > 100 for: 1m labels: severity: high annotations: summary: "Trafic value for {{ $labels.instance}} ip: {{ $labels.ip }} is greater then 100 Mib" description: "Trafic issue for ip {{ $labels.ip }}"
2. 实例宕机告警规则(availability.yml,存在问题)
groups: - name: Instance DOWN rules: - alert: Host is DOWN expr: up == 0 for: 1m labels: severity: high annotations: summary: "Instance not available {{$labels.ip}}" description: "ip {{$labels.ip}} problem"
3. Telegram告警模板(telega.tmpl)
Status: {{ .Status }} Alertname: {{ .CommonLabels.alertname }} Description: {{.CommonAnnotations.description}} Summary: {{.CommonAnnotations.summary}} Instance: {{ .CommonLabels.instance }}
问题原因
核心矛盾在于:
- 流量告警依赖的
node_network_receive_bytes_total指标本身带有ip标签,注解渲染时能正常获取值; - 宕机告警依赖的
up指标没有ip标签,Prometheus渲染注解时找不到该标签,导致整个注解字段渲染失败,最终Telegram无法收到对应的description和summary内容。
解决方案
方案1:给所有告警关联的指标添加ip标签
通过Prometheus的scrape_configs配置,给up指标所在的采集任务自动添加ip标签。以node_exporter为例:
scrape_configs: - job_name: 'node_exporter' static_configs: - targets: ['192.168.1.10:9100', '192.168.1.11:9100'] # 自动从target地址中提取IP作为标签 relabel_configs: - source_labels: [__address__] regex: '(.*):.*' target_label: ip
配置后,up指标会自动带上ip标签,宕机告警的注解就能正常渲染。
方案2:给注解添加标签默认值(兼容标签缺失场景)
如果无法确保所有指标都有ip标签,可使用Prometheus模板的默认值语法,避免标签缺失导致渲染失败。修改告警规则的注解部分:
流量告警规则修改后:
annotations: summary: "Trafic value for {{ $labels.instance}} ip: {{ $labels.ip | default "unknown" }} is greater than 100 Mib" description: "Trafic issue for ip {{ $labels.ip | default "unknown" }}"
宕机告警规则修改后:
annotations: summary: "Instance not available {{ $labels.ip | default "unknown" }}" description: "ip {{ $labels.ip | default "unknown" }} problem"
当ip标签不存在时,会显示unknown替代,保证注解能正常渲染,Telegram可收到完整告警内容。
方案3:优化Telegram模板兼容性
调整模板逻辑,兼容单个告警和聚合告警的场景,避免.CommonAnnotations为空导致字段不显示:
Status: {{ .Status }} Alertname: {{ .CommonLabels.alertname }} Description: {{ if .CommonAnnotations.description }}{{ .CommonAnnotations.description }}{{ else }}{{ range .Alerts }}{{ .Annotations.description }}{{ end }}{{ end }} Summary: {{ if .CommonAnnotations.summary }}{{ .CommonAnnotations.summary }}{{ else }}{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}{{ end }} Instance: {{ .CommonLabels.instance }}
内容的提问来源于stack exchange,提问作者Konstantin
相关产品推荐
相关产品推荐

