alertmanager邮件模版

说明

alertmanager能够设置多种通知规则,这篇文章介绍如何配置邮件通知

简单设置

如下修改receivers-email_configs-html后,收到的邮件内容是:测试 http://ming:9093html表示的是邮件内容。

1
2
3
4
5
receivers:
- name: 'mengyuan'
email_configs:
- to: 'xxxx@xxx.com'
html: '测试 {{ .ExternalURL }}'

模版变量

邮件模版使用go template编写,两对大括号中的.ExternalURL即表示变量的ExternalURL字段,Data结构如下,源码在这里。请自行google go template的使用方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// Data is the data passed to notification templates and webhook pushes.
//
// End-users should not be exposed to Go's type system, as this will confuse them and prevent
// simple things like simple equality checks to fail. Map everything to float64/string.
type Data struct {
Receiver string `json:"receiver"`
Status string `json:"status"`
Alerts Alerts `json:"alerts"`

GroupLabels KV `json:"groupLabels"`
CommonLabels KV `json:"commonLabels"`
CommonAnnotations KV `json:"commonAnnotations"`

ExternalURL string `json:"externalURL"`
}
// Alert holds one alert for notification templates.
type Alert struct {
Status string `json:"status"`
Labels KV `json:"labels"`
Annotations KV `json:"annotations"`
StartsAt time.Time `json:"startsAt"`
EndsAt time.Time `json:"endsAt"`
GeneratorURL string `json:"generatorURL"`
}
// Alerts is a list of Alert objects.
type Alerts []Alert
// KV is a set of key/value string pairs.
type KV map[string]string

邮件模版文件

上面例子将html的值写为邮件模版,但实际情况一般需要我们在其他文件中定义好模版,在html中引用模版名字,go tempate的子模版功能可以满足我们的要求。
templates下填写模版文件路径,html下引用定义好的子模版

1
2
3
4
5
6
7
8
9
10
# Files from which custom notification template definitions are read.
# The last component may use a wildcard matcher, e.g. 'templates/*.tmpl'.
templates:
[ - <filepath> ... ]
receivers:
- name: 'mengyuan'
email_configs:
- to: 'xxx@xxx.com'
html: '{{ template "email.mengyuan.html" . }}'
headers: { Subject: "[WARN] 报警邮件test" }

模版文件mengyuan.tmpl

1
2
3
4
5
6
7
8
{{ define "email.mengyuan.html" }}
<table>
<tr><td>报警名</td><td>开始时间</td></tr>
{{ range $i, $alert := .Alerts }}
<tr><td>{{ index $alert.Labels "alertname" }}</td><td>{{ $alert.StartsAt }}</td></tr>
{{ end }}
</table>
{{ end }}

测试时发现子模版名称有数字时(如email.mengyuan1.html)不会收到通知alermanager也不报错,可能是BUG。
配置好后,收到的邮件内容如下