侧边栏壁纸
  • 累计撰写 208 篇文章
  • 累计创建 16 个标签
  • 累计收到 5 条评论

目 录CONTENT

文章目录

Prometheus Alertmanager 通过 Telegram 发送警报

Wake
2022-08-31 / 0 评论 / 5 点赞 / 3,878 阅读 / 757 字

1.创建 Telegrambot

遵循 Telegram 文档中的指南:https 😕/core.telegram.org/bots#creating-a-new-bot 您将收到电报令牌 ID。我们将其存储并稍后使用。

2. 创建新组以接收警报,然后将机器人添加到组中。

更改机器人加入群组,获取群组id: 我们需要用这个bot来发送消息,首先需要创建一个group,加入一些人,也可以不加人,同时将这个bot也加进去。然后在这个group中发送消息。类似 /hello @xxxxx_Bot 然后访问 https://api.telegram.org/botxxx:xxx/getUpdates xxx:xxx部分就是机器人的api token 需要妥善保管。 注意: 群组的chat_id就是上面的id,注意是负数,必须有-,机器人的chat_id则可以是正数。

创建和构建电报机器人 docker 镜像

1.来自 github 的克隆 Telegram bot 源代码

https://github.com/inCaller/prometheus_bot

2. 进入源代码

cd prometheus_bot/

3. 编辑 Dockerfile
FROM golang:1.14.4-alpine3.12 as builder
RUN apk add --no-cache git ca-certificates make tzdata
COPY . /app
RUN cd /app && \
    go get -d -v && \
    CGO_ENABLED=0 GOOS=linux go build -v -a -installsuffix cgo -o prometheus_bot

FROM alpine:3.12
COPY --from=builder /app/prometheus_bot /
RUN apk add --no-cache ca-certificates tzdata tini
RUN mkdir /etc/telegrambot/
USER nobody
EXPOSE 9087
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["/prometheus_bot", "-c", "/etc/telegrambot/config.yaml" , "-l", "9087", "-t", "/etc/telegrambot/template.tmpl"]
4.构建docker镜像
docker build -t tienbm90/prometheus-bot:0.0.1

镜像已上传到镜像仓库中

配置电报机器人

1.创建文件夹以存储电报机器人配置
mkdir telegrambot
2.创建telegrambot配置文件telegrambot/config.yaml:
telegram_token: "telegram-token"
template_path: "/etc/telegrambot/template.tmpl"
time_zone: "Asia/Shanghai"
split_token: "|"
time_outdata: "02/01/2006 15:04:05"
split_msg_byte: 10000
  • 使用telegrambot/template.tmpl 定义警报格式:(这里的告警格式可以后期进行优化调整)
Type: {{.CommonAnnotations.description}}
Summary: {{.CommonAnnotations.summary}}
Alertname: {{ .CommonLabels.alertname }}
Instance: {{ .CommonLabels.instance }}
Serverity: {{ .CommonLabels.serverity}}
Status:  {{ .Status }}

配置警报管理器

警报管理器配置文件:(prometheus的样例配置,关键就是receivers处的配置)

global:
  resolve_timeout: 5m
route:
  group_by: ['alertname']
  group_wait: 30s
  group_interval: 30s
  repeat_interval: 5m
  receiver: 'web.hook'
receivers:
- name: 'web.hook'
  webhook_configs:
  - url: 'http://#你的IP地址:9087/alert/<telegram-chat-id(TG的群组id)>'    #这里配置TG的webhook
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

创建 docker-compose.yml 文件

version: '3.3'

services:
  prometheus-bot:
          #container_name: telegrambot
    image: telegram/prometheus-bot:0.0.1  #你的镜像仓库地址

    volumes:
      - /etc/telegrambot/:/etc/telegrambot/
      - /etc/telegrambot/config.yaml:/config.yaml 
    ports:
      - 9087:9087
    restart: always

启动警报管理器和电报机器人

docker-compose up -d

验证和检查结果: TG的告警群组将会收到这样的告警信息:

Type: Host out of memory
Summary: Host out of memory (instance x.x.x.x:y)
Alertname: HostOutOfMemory
Instance:  x.x.x.x:y
Serverity: information
Status:  firing
5

评论区