在 Kubernetes 集群中配置企微机器人告警,最通用的方案是通过 Prometheus Alertmanager 的 Webhook 接收器对接企微群机器人接口。该方案适合已部署 Prometheus 监控栈的团队,无需额外开发代码,重点在于密钥安全管理和消息格式适配。
先说结论:利用 Alertmanager 原生 Webhook 能力即可打通,但需注意配置文件安全性与消息模板渲染。
- 适合:已运行 Prometheus + Alertmanager 监控体系的集群
- 先准备:企业微信管理后台创建的群机器人 Webhook 地址
- 验收:手动触发测试告警并能收到格式正常的消息卡片
核心配置与安全性修正
Alertmanager 配置的核心在于 receivers 部分。为避免密钥泄露,不建议将包含 Webhook URL 的配置文件 stored 在 ConfigMap 中,建议直接存储为 Kubernetes Secret 或通过 Helm values 注入。
以下是一个包含消息模板的最小化配置片段示例(alertmanager.yml):
global:
resolve_timeout: 5m
templates:
- '/etc/alertmanager/templates/*.tmpl'
route:
group_by: ['alertname']
receiver: 'wecom-webhook'
receivers:
- name: 'wecom-webhook'
webhook_configs:
- url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY'
send_resolved: true
# 使用模板渲染消息内容,适配企微 Markdown 语法
message: '{{ template "wecom.default.message" . }}'安全建议:生产环境中,请将上述包含 `key=YOUR_KEY` 的配置文件创建为 Kubernetes Secret,而非 ConfigMap,并限制访问权限。
企微消息模板配置
企微机器人支持 Markdown 格式,但 Alertmanager 默认发送的是纯文本,直接发送会导致格式错乱。需自定义模板文件(如 wecom.tmpl):
{{ define "wecom.default.message" }}
## 🚨 告警通知
**告警名称:** {{ .CommonLabels.alertname }}
**严重级别:** {{ .CommonLabels.severity }}
**触发时间:** {{ .StartsAt.Format "2006-01-02 15:04:05" }}
**详情:** {{ .CommonAnnotations.description }}
**实例:** {{ .CommonLabels.instance }}
{{ end }}将该模板文件挂载到 Alertmanager Pod 的 /etc/alertmanager/templates/ 目录下。
密钥管理与挂载实践
1. 创建 Kubernetes Secret
修正后的命令如下(注意参数格式,不要使用反引号):
kubectl create secret generic alertmanager-wecom \
`--from-literal`=url='https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY'2. 挂载 Secret 到 Pod
在 Alertmanager 的 Deployment 或 StatefulSet 中,将 Secret 挂载为环境变量或文件。若需动态注入 URL,可配合 init-container 生成配置文件。最简方式是直接将包含敏感信息的 alertmanager.yml 整体存为 Secret:
kubectl create secret generic alertmanager-config \
`--from-file`=alertmanager.yml=./alertmanager.yml然后在 Pod spec 中引用:
volumes:
- name: config-volume
secret:
secretName: alertmanager-config
volumeMounts:
- name: config-volume
mountPath: /etc/alertmanager怎么验证是否生效
不要等待生产故障,建议分两步验证:
1. 验证企微接口连通性
使用 curl 直接调用 Webhook 接口,确认网络通畅且 Key 有效:
curl -X POST -H "Content-Type: application/json" \ -d '{"msgtype":"text","text":{"content":"K8s 告警连通性测试"}}' \ 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY'若返回
{"errcode":0,"errmsg":"ok"}则接口正常。2. 验证 Alertmanager 通知
在 Alertmanager UI 界面使用 "Silences" 或临时修改规则触发一条测试告警,观察企业微信群是否收到格式正常的消息卡片,同时检查 Alertmanager Pod 日志是否有
level=error的发送失败报错。常见坑与排查
1. 网络连通性:集群节点必须能访问
qyapi.weixin.qq.com。如果集群在内网且无出站 NAT 权限,告警会发送失败。可在 Pod 内使用curl -v测试。2. 消息格式乱码:务必配置
templates和message字段。企微对 Markdown 语法有特定要求,避免使用 unsupported 的语法。3. 频率限制:企微机器人有发送频率限制(通常 20 次/分钟)。如果告警风暴发生,可能会触发接口限流。建议在 Alertmanager 中配置好
group_wait、group_interval和repeat_interval进行聚合。4. 配置重载:修改 ConfigMap 或 Secret 后,Alertmanager 不会自动重载。如果使用 Helm 部署通常会自动滚动更新 Pod;如果是手动挂载,可能需要发送
SIGHUP信号或重启 Pod。参考来源
- Prometheus Official Documentation, Alertmanager configuration, https://prometheus.io/docs/alerting/latest/configuration/
- 企业微信开放文档,群机器人,https://work.weixin.qq.com/api/doc/90000/90136/91770