最近在公司搭建 prometheus 监控平台。文章 《Prometheus 使用阿里云邮件推送发送告警邮件》 已说明如何实现 prometheus 发送邮件告警的功能,这篇文章说明如何实现发送企业微信告警的功能。
申请企业微信账号
为实现发送企业微信告警消息,需要一个企业微信账号,在页面 企业微信 可以免费申请一个测试账号。
进入应用管理 - 创建应用,创建一个用于接收告警消息的账号。创建成功后,可以看到该应用的 AgentId 和 Secret 串,如图所示:

配置 alertmanager
Alertmanager 用于接收 prometheus 的告警消息并将告警消息发送到指定的用户。为实现使用企业微信发送告警消息,需要在 alertmanager 增加企业微信的有关配置。
alertmanager.yml 增加企业微信的配置:
| 12
 3
 4
 5
 6
 7
 8
 9
 
 | 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 增加企业微信路由:
| 12
 3
 4
 5
 6
 
 | route:group_by: ['alertname']
 group_wait: 0s
 group_interval: 10s
 repeat_interval: 15m
 receiver: 'wechat'
 
 | 
其中,repeat_interval 是指重复发送告警的时间间隔。
定制告警模板
由于默认的告警模板会显示一些不必要的信息,为简化告警消息,可以自定义告警模板。
修改 alertmanager.yml,设置自定义模板:
| 12
 
 | templates:- '/templates/*.tmpl'
 
 | 
企业微信的告警模板 wechat.tmpl 如下,我们配置了警报和恢复两种情况的模板,读者可以根据需要自定进行配置。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 
 | {{ 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 配置,以指定使用我们定制的模板:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 
 | 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