通知模板示例

以下是告警及相應 Alertmanager 配置檔案設定(alertmanager.yml)的各種不同示例。每個示例都使用 Go 模板  系統。

自定義 Slack 通知

在此示例中,我們自定義了 Slack 通知,以便傳送一個指向我們組織 Wiki 的 URL,該 Wiki 介紹瞭如何處理已傳送的特定告警。

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 中儲存的 summarydescription

告警

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 接收到的所有告警,並在新行中分別列印它們對應的註解摘要(summary)和描述(description)。

接收器

- 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'

本篇部落格文章中對該示例進行了更詳細的說明。

本頁內容