通知模板示例

以下都是告警和相应 Alertmanager 配置文件(alertmanager.yml)设置的不同示例。每个都使用了 Go 模板 系统。

自定义 Slack 通知

在这个例子中,我们定制了我们的 Slack 通知,以发送一个指向我们组织 wiki 的 URL,该 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'

这个例子在这篇博文中有更详细的解释。

本页内容