最近在公司搭建 prometheus 監控平臺。文章 《Prometheus 使用阿里雲郵件推送發送告警郵件》 已說明如何實現 prometheus 發送郵件告警的功能,這篇文章說明如何實現發送企業微信告警的功能。
申請企業微信賬號
爲實現發送企業微信告警消息,需要一個企業微信賬號,在頁面 企業微信 可以免費申請一個測試賬號。
進入應用管理 - 創建應用,創建一個用於接收告警消息的賬號。創建成功後,可以看到該應用的 AgentId 和 Secret 串,如圖所示:
配置 alertmanager
Alertmanager 用於接收 prometheus 的告警消息並將告警消息發送到指定的用戶。爲實現使用企業微信發送告警消息,需要在 alertmanager 增加企業微信的有關配置。
alertmanager.yml
增加企業微信的配置:
receivers:
- name: 'wechat'
wechat_configs:
- send_resolved: false
agent_id: 100000x
corp_id: 'xxxxxxxxxx'
api_url: 'https://qyapi.weixin.qq.com/cgi-bin/'
api_secret: 'xxxxxxxxxx'
to_user: 'xxx|yyy'
其中,corp_id
爲企業 id,可以在企業微信管理後臺,我的企業 - 企業 ID 查看。agent_id
是上面創建應用的 AgentId,api_secret
是應用的 Secret 。 to_user
可以指定需要接收告警的用戶。
alertmanager.yml
增加企業微信路由:
route:
group_by: ['alertname']
group_wait: 0s
group_interval: 10s
repeat_interval: 15m
receiver: 'wechat'
其中,repeat_interval
是指重複發送告警的時間間隔。
定製告警模板
由於默認的告警模板會顯示一些不必要的信息,爲簡化告警消息,可以自定義告警模板。
修改 alertmanager.yml
,設置自定義模板:
templates:
- '/templates/*.tmpl'
企業微信的告警模板 wechat.tmpl
如下,我們配置了警報和恢復兩種情況的模板,讀者可以根據需要自定進行配置。
{{ define "wechat.html" }}
{{- if gt (len .Alerts.Firing) 0 -}}{{ range .Alerts }}
@警報
實例: {{ .Labels.instance }}
信息: {{ .Annotations.summary }}
詳情: {{ .Annotations.description }}
時間: {{ (.StartsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}
{{ end }}{{ end -}}
{{- if gt (len .Alerts.Resolved) 0 -}}{{ range .Alerts }}
@恢復
實例: {{ .Labels.instance }}
信息: {{ .Annotations.summary }}
時間: {{ (.StartsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}
恢復: {{ (.EndsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}
{{ end }}{{ end -}}
{{- end }}
調整 receivers
配置,以指定使用我們定製的模板:
receivers:
- name: 'wechat'
wechat_configs:
- send_resolved: false
agent_id: 100000x
corp_id: 'xxxxxxxxxx'
api_url: 'https://qyapi.weixin.qq.com/cgi-bin/'
api_secret: 'xxxxxxxxxx'
to_user: 'xxx|yyy'
message: '{{ template "wechat.html" . }}'
使用定製的告警模板後,接收到的微信告警示例:
參考資料
- https://songjiayang.gitbooks.io/prometheus/content/alertmanager/wechat.html
- https://prometheus.io/docs/alerting/latest/configuration/#wechat_config
- https://www.cnblogs.com/elvi/p/11444278.html
- https://www.jianshu.com/p/a8b18d68858d
- https://knight.blog.csdn.net/article/details/106323719