通知模板示例
以下是告警和相应 Alertmanager 配置文件设置 (alertmanager.yml) 的不同示例。每个示例都使用了 Go 模板 系统。
自定义 Slack 通知
在此示例中,我们自定义了 Slack 通知,以发送一个指向我们组织维基的 URL,其中包含了如何处理已发送的特定告警的信息。
global:
# Also possible to place this URL in a file.
# Ex: `slack_api_url_file: '/etc/alertmanager/slack_url'`
slack_api_url: '<slack_webhook_url>'
route:
receiver: 'slack-notifications'
group_by: [alertname, datacenter, app]
receivers:
- name: 'slack-notifications'
slack_configs:
- channel: '#alerts'
text: 'https://internal.myorg.net/wiki/alerts/{{ .GroupLabels.app }}/{{ .GroupLabels.alertname }}'
访问 CommonAnnotations 中的注释
在这个例子中,我们再次自定义了发送到 Slack 接收器的文本,访问了 Alertmanager 发送的数据中 `CommonAnnotations` 里存储的 `summary` 和 `description`。
告警
groups:
- name: Instances
rules:
- alert: InstanceDown
expr: up == 0
for: 5m
labels:
severity: page
# Prometheus templates apply here in the annotation and label fields of the alert.
annotations:
description: '{{ $labels.instance }} of job {{ $labels.job }} has been down for more than 5 minutes.'
summary: 'Instance {{ $labels.instance }} down'
接收器
- name: 'team-x'
slack_configs:
- channel: '#alerts'
# Alertmanager templates apply here.
text: "<!channel> \nsummary: {{ .CommonAnnotations.summary }}\ndescription: {{ .CommonAnnotations.description }}"
遍历所有收到的告警
最后,假设与前一个示例使用相同的告警,我们自定义接收器以遍历从 Alertmanager 收到的所有告警,并在新行上打印它们各自的注释摘要和描述。
接收器
- name: 'default-receiver'
slack_configs:
- channel: '#alerts'
title: "{{ range .Alerts }}{{ .Annotations.summary }}\n{{ end }}"
text: "{{ range .Alerts }}{{ .Annotations.description }}\n{{ end }}"
定义可重用的模板
回到我们的第一个例子,我们还可以提供一个包含命名模板的文件,Alertmanager 会加载这些模板,以避免跨越多行的复杂模板。在 `/alertmanager/template/myorg.tmpl` 下创建一个文件,并在其中创建一个名为“slack.myorg.text”的模板。
{{ define "slack.myorg.text" }}https://internal.myorg.net/wiki/alerts/{{ .GroupLabels.app }}/{{ .GroupLabels.alertname }}{{ end}}
现在,配置会为“text”字段加载具有给定名称的模板,并且我们提供了自定义模板文件的路径。
global:
slack_api_url: '<slack_webhook_url>'
route:
receiver: 'slack-notifications'
group_by: [alertname, datacenter, app]
receivers:
- name: 'slack-notifications'
slack_configs:
- channel: '#alerts'
text: '{{ template "slack.myorg.text" . }}'
templates:
- '/etc/alertmanager/templates/myorg.tmpl'
这个例子在这篇博文中有更详细的解释。