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

如何在Prometheus告警模板中移除不必要的标签?

解决Prometheus Alert Manager告警模板标签过滤问题

你可以在标签遍历的逻辑中增加判断条件,通过保留指定标签或排除不需要的标签两种方式实现需求:

方式1:只保留指定标签

如果需要保留的标签数量较少,直接定义允许的标签列表,遍历仅输出符合条件的标签:

{{ if gt (len $alerts.Labels.SortedPairs) 0 -}},
"labels": 
    {{ "{" }}
        {{ $allowedLabels := list "alertname" "severity" "instance" }}  <!-- 替换为你需要保留的标签名 -->
        {{ $index := 0 }}
        {{ range $label := $alerts.Labels.SortedPairs }}
            {{ if in $allowedLabels $label.Name }}
                {{ if $index }}, 
                {{ end }}
                "{{ $label.Name }}": "{{ $label.Value }}"
                {{ $index = add $index 1 }}
            {{ end }}
        {{ end }}
    {{ "}" }}
{{- end }}

方式2:排除不需要的标签

如果需要移除的标签数量更少,定义排除列表,遍历跳过这些标签:

{{ if gt (len $alerts.Labels.SortedPairs) 0 -}},
"labels": 
    {{ "{" }}
        {{ $excludedLabels := list "pod" "namespace" "job" }}  <!-- 替换为你要移除的标签名 -->
        {{ $index := 0 }}
        {{ range $label := $alerts.Labels.SortedPairs }}
            {{ if not (in $excludedLabels $label.Name) }}
                {{ if $index }}, 
                {{ end }}
                "{{ $label.Name }}": "{{ $label.Value }}"
                {{ $index = add $index 1 }}
            {{ end }}
        {{ end }}
    {{ "}" }}
{{- end }}

关键说明

  • 模板中使用的in(判断元素是否在列表)和add(数值累加)是Prometheus Alert Manager支持的标准模板函数,Amazon Prometheus环境可直接使用。
  • 通过$index变量控制逗号输出,避免JSON格式出现多余逗号导致解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:52:44