Alertmanager 自定义邮件模版

半兽人 发表于: 2021-03-24   最后更新时间: 2021-03-25 10:17:17  
{{totalSubscript}} 订阅, 4,793 游览

Alertmanager 默认的邮件模版不能满足你的审美,你可以自定义邮件模板。

简单模板

字段html表示的是邮件内容。

receivers:
- name: 'xxxx'
  email_configs:
  - to: 'xxxx@xxx.com'
    html: '测试 {{ .ExternalURL }}'

收到的邮件内容是:

测试 http://xxxx:9093

模版变量

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

// 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
<!--more-->

邮件模版文件

上面的例子是将html字段的值写为邮件模版,但实际情况一般需要我们在其他文件中定义好模版,在html字段中引用模版名字即可。

邮件模版文件template/test.tmpl

{{ define "email.test.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 }}

templates下填写模版文件路径,html下引用定义好的子模版

templates:
  - ./template/*.tmpl

receivers:
- name: 'xxxx'
  email_configs:
  - to: 'xxx@xxx.com'
    html: '{{ template "email.test.html" . }}'
    headers: { Subject: "[WARN] 报警邮件test" }

配置好后,收到的邮件内容格式如下:

报警名 开始时间
HighRequestLatency  2021-03-23 10:52:28.878593578 +0000 UTC
HighRequestLatency  2021-03-23 10:47:28.878593578 +0000 UTC
HighRequestLatency  2021-03-23 10:42:28.878593578 +0000 UTC
HighRequestLatency  2021-03-23 10:37:28.878593578 +0000 UTC

默认的邮件模板

官方的默认模板,你可以基于它进行修改:
https://raw.githubusercontent.com/prometheus/alertmanager/master/template/email.html

更新于 2021-03-25

查看Prometheus更多相关的文章或提一个关于Prometheus的问题,也可以与我们一起分享文章