深色模式
告警模板 template
摘要:默认通知只有机器字段,排查时要自己拼。用
templates定义.tmpl文件,结合{{.CommonAnnotations.summary}}等变量,把标题、正文、链接都排版好。
适用环境
- 已运行 Alertmanager
- 想在钉钉/邮件/Webhook 里看到结构化文案
操作步骤
1. 写模板文件
go
{{/* /etc/alertmanager/tmpl/alert.tmpl */}}
{{ define "alert.title" }}[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}{{ end }}
{{ define "alert.body" }}
级别: {{ .CommonLabels.severity }}
实例: {{ range .Alerts }}{{ .Labels.instance }} {{ end }}
摘要: {{ .CommonAnnotations.summary }}
链接: <http://alert.example.com/#/alerts>
{{ end }}1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
2. 在配置里引用
yaml
# /etc/alertmanager/alertmanager.yml
templates:
- '/etc/alertmanager/tmpl/*.tmpl'
route:
receiver: default
receivers:
- name: default
email_configs:
- to: 'ops@example.com'
headers: { Subject: '{{ template "alert.title" . }}' }
html: '{{ template "alert.body" . }}'1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
3. 加载并校验
bash
amtool check-config /etc/alertmanager/alertmanager.yml
curl -X POST http://localhost:9093/-/reload1
2
2
验证
bash
# 构造一条带 annotation 的告警
amtool alert add alertname=HighCpu \
severity=critical \
instance=node1 \
annotation.summary="CPU 持续 >90%"
# 查看通知里的标题/正文是否按模板渲染1
2
3
4
5
6
2
3
4
5
6
常见坑
WARNING
- 模板语法是 Go text/template,写错一个
{{ }}会让整个配置加载失败;改完务必amtool check-config。 - 邮件用
html:字段才支持换行/加粗,text:是纯文本。
DANGER
模板里不要拼外部 URL 时漏掉转义,含特殊字符的链接在飞书里可能失效。