如何跨网络将Prometheus AlertManager告警推送至Grafana?
如何通过API将Prometheus AlertManager告警推送至跨网络的Grafana
Grafana完全支持通过API接收并展示来自Prometheus AlertManager的告警,正好适配你只能使用HTTP/HTTPS端口的场景,以下是两种可行方案:
方案1:使用Grafana Alerting API推送告警事件
你可以调用Grafana的POST /api/v1/alerts API直接提交告警数据,该API兼容Prometheus AlertManager的告警格式,无需额外转换结构:
请求示例
- 请求头需包含Grafana API密钥(在Grafana后台
Configuration > API Keys创建,需赋予alerting:write权限):Authorization: Bearer <你的API密钥> Content-Type: application/json - 请求体(JSON格式,与AlertManager输出结构一致):
[ { "labels": { "alertname": "HighCPUUsage", "severity": "critical" }, "annotations": { "summary": "服务器CPU使用率超过90%", "description": "example.com服务器CPU使用率已达95%,持续5分钟" }, "startsAt": "2024-05-20T12:00:00Z", "endsAt": "2024-05-20T12:10:00Z" } ]
提交后,告警会出现在Grafana的Alerting > Alerts页面,支持过滤、分组展示。
方案2:使用Annotations API关联告警到可视化面板
如果需要将告警直接绑定到特定仪表盘面板,方便查看告警上下文,可以调用POST /api/annotations API添加告警注释:
请求示例
- 请求头同样需要API密钥(需赋予
annotations:write权限) - 请求体:
{ "dashboardUid": "你的仪表盘UID", "panelId": 目标面板ID, "time": 1716201600000, // 告警开始时间戳(毫秒) "timeEnd": 1716202200000, // 告警结束时间戳(毫秒) "tags": ["alert", "high-cpu"], "text": "严重告警:example.com服务器CPU使用率超过90%" }
这种方式会在指定面板的时间轴上显示告警标记,鼠标悬停可查看详情。
实现注意事项
- 确保Grafana的HTTP/HTTPS端口(默认3000,若已修改为80/443则用对应端口)在你的网络环境中可达。
- 脚本捕获AlertManager告警的方式:可以通过AlertManager的Webhook配置触发脚本,或者定期轮询AlertManager的
/api/v2/alerts接口拉取告警数据,再转发到Grafana API。 - API密钥权限需匹配操作,避免过度授权。
内容的提问来源于stack exchange,提问作者JurajRabcan
相关产品推荐
相关产品推荐

