Alertmanager实现企业微信机器人webhook告警

这篇具有很好参考价值的文章主要介绍了Alertmanager实现企业微信机器人webhook告警。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1. 说明

由于企业微信更新问题,现在已经无法直接使用创建应用后在alertmanager的配置文件中定义企业id及secret就可以发送告警信息了,除非填写备案后域名;为了我们这种个人开发者非常的不便,所以本文档是为了解决想使用企业微信告警但又无法备案的朋友;下面只是我的操作过程记录

如果没有自定义的需求可以直接使用我的镜像可以直接使用我的镜像:kfreesre/prometheus-flask:latest

2. 环境

我这里的监控是在kubernetes中部署的(kube-prometheus);镜像是公开的,可直接下载;告警内容可自定义;

3. 步骤

3.1 下载项目并自定义编译内容;

# clone项目(已点start)
~] git clone https://github.com/hsggj002/prometheus-flask.git

# 修改Dockerfile
~] vim prometheus-flask/Dockerfile
FROM python:3.10.2
COPY ./app /app
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
# 指定了一下国内镜像,由于requirement.txt中有要安装的包,下载又很慢,所以选择国内镜像;
RUN pip install -r /app/requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
# 原本是CMD的,这样我们在K8s中部署不好传参,所以改了entrypoint;
ENTRYPOINT ["python", "/app/main.py"]

# 修改requirements.txt文件
~] vim prometheus-flask/requirements.txt
flask_json == 0.3.4
flask == 2.0.1
requests == 2.19.1
gevent == 21.12.0    
# 增加此行,我第一次发布镜像时报错了,加了这行得以解决;
Werkzeug == 2.0.1

3.2 修改源码

~] vim app/Alert.py
# 博主中的源码告警中多机房,所以代码中有,但我这里没有,所以去掉;
# https://github.com/hsggj002/prometheus-flask/issues/3
# 下面图一为仅修改了region参数的告警信息;但我这里想增加pod_name并且恢复告警的内容中没有定义恢复时间
# 为了解决这两个问题,我将Alert.py改了一下,可以直接使用;
# 下面图二是修改后的告警;
# -*- coding: UTF-8 -*-
from doctest import debug_script
from pydoc import describe
from flask import jsonify
import requests
import json
import datetime
import sys

def parse_time(*args):
    times = []
    for dates in args:
        eta_temp = dates
        if len(eta_temp.split('.')) >= 2:
            if 'Z' in eta_temp.split('.')[1]:
                s_eta = eta_temp.split('.')[0] + '.' + eta_temp.split('.')[1][-5:]
                fd = datetime.datetime.strptime(s_eta, "%Y-%m-%dT%H:%M:%S.%fZ")
            else:
                eta_str = eta_temp.split('.')[1] = 'Z'
                fd = datetime.datetime.strptime(eta_temp.split('.')[0] + eta_str, "%Y-%m-%dT%H:%M:%SZ")
        else:
            fd = datetime.datetime.strptime(eta_temp, "%Y-%m-%dT%H:%M:%SZ")
        eta = (fd + datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S.%f")
        times.append(eta)
    return times

def alert(status,alertnames,levels,times,pod_name,ins,instance,description):
    params = json.dumps({
        "msgtype": "markdown",
        "markdown":
            {
                "content": "## <font color=\"red\">告警通知: {0}</font>\n**告警名称:** <font color=\"warning\">{1}</font>\n**告警级别:** {2}\n**告警时间:** {3}\n**Pod名称**: {4}\n{5}: {6}\n**告警详情:** <font color=\"comment\">{7}</font>".format(status,alertnames,levels,times[0],pod_name,ins,instance,description)
            }
        })

    return params

def recive(status,alertnames,levels,times,pod_name,ins,instance,description):
    params = json.dumps({
        "msgtype": "markdown",
        "markdown":
            {
                "content": "## <font color=\"info\">恢复通知: {0}</font>\n**告警名称:** <font color=\"warning\">{1}</font>\n**告警级别:** {2}\n**告警时间:** {3}\n**恢复时间:** {4}\n**Pod名称:** {5}\n{6}: {7}\n**告警详情:** <font color=\"comment\">{8}</font>".format(status,alertnames,levels,times[0],times[1],pod_name,ins,instance,description)
            }
        })

    return params

def webhook_url(params,url_key):
    headers = {"Content-type": "application/json"}
    """
    *****重要*****
    """
    url = "{}".format(url_key)
    r = requests.post(url,params,headers)

def send_alert(json_re,url_key):
    print(json_re)
    for i in json_re['alerts']:
        if i['status'] == 'firing':
            if "instance" in i['labels'] and "pod" in i['labels']:
                if "description" in i['annotations']:
                    webhook_url(alert(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt']),i['labels']['pod'],'故障实例',i['labels']['instance'],i['annotations']['description']),url_key)
                elif "message" in i['annotations']:
                    webhook_url(alert(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt']),i['labels']['pod'],'故障实例',i['labels']['instance'],i['annotations']['message']),url_key)
                else:
                    webhook_url(alert(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt']),i['labels']['pod'],'故障实例',i['labels']['instance'],'Service is wrong'),url_key)
            elif "namespace" in i['labels']:
                webhook_url(alert(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt']),'None','名称空间',i['labels']['namespace'],i['annotations']['description']),url_key)
            elif "Watchdog" in i['labels']['alertname']:
                webhook_url(alert(i['status'],i['labels']['alertname'],'0','0','0','故障实例','自测','0'),url_key)
        elif i['status'] == 'resolved':
            if "instance" in i['labels']:
                if "description" in i['annotations']:
                    webhook_url(recive(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt'],i['endsAt']),i['labels']['pod'],'故障实例',i['labels']['instance'],i['annotations']['description']),url_key)
                elif "message" in i['annotations']:
                    webhook_url(recive(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt'],i['endsAt']),i['labels']['pod'],'故障实例',i['labels']['instance'],i['annotations']['message']),url_key)
                else:
                    webhook_url(recive(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt'],i['endsAt']),i['labels']['pod'],'故障实例',i['labels']['instance'],'Service is wrong'),url_key)
            elif "namespace" in i['labels']:
                webhook_url(recive(i['status'],i['labels']['alertname'],i['labels']['severity'],parse_time(i['startsAt'],i['endsAt']),'None','名称空间',i['labels']['namespace'],i['annotations']['description']),url_key)
            elif "Watchdog" in i['labels']['alertname']:
                webhook_url(alert(i['status'],i['labels']['alertname'],'0','0','0','故障实例','自测','0'),url_key)

图一搭建微信告警机器人,企业微信

图二搭建微信告警机器人,企业微信

3.3 制作镜像

~] docker build -t kfreesre/prometheus-flask:latest .

3.4 部署至kubernetes中

apiVersion: apps/v1
kind: Deployment
metadata:
  name: alertinfo
  namespace: monitoring
spec:
  replicas: 1
  selector:
    matchLabels:
      app: alertinfo
      release: stable
  template:
    metadata:
      labels:
        app: alertinfo 
        release: stable
    spec:
      containers:
      - name: alertinfo-flask
        image: kfreesre/prometheus-flask:latest
        imagePullPolicy: Always
        ports:
        - name: http
          containerPort: 80
        args:
				# 企业微信的webhook-key如何获取可以google一下;很简单,这里不说明了;
        - "-k https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=你自己的webhook-key"
        - "-p 80"
---
apiVersion: v1
kind: Service
metadata:
  name: alertinfo-svc
  namespace: monitoring
spec:
  selector:
    app: alertinfo
    release: stable
  type: ClusterIP
  ports:
  - name: http 
    targetPort: 80
    port: 80
~] kubectl apply -f ./alertinfo.yaml

3.5 修改alertmanager配置

global:
  resolve_timeout: 5m
  smtp_smarthost: "xxx"
  smtp_from: "xxxx"
  smtp_auth_username: "xxx"
  smtp_auth_password: "xxx"
  smtp_require_tls: true
# 告警模板指定
templates:
  - '/etc/template/config/email.tmpl'
route:
  group_by: ['job', 'severity']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 12h
  receiver: 'wechat'
  routes:
  - match_re:
      severity: ^info|warning|critical$
    receiver: 'operation'
    continue: true
  - match_re:
      severity: ^info|warning|critical$
    receiver: 'wechat'
    continue: true

receivers:
- name: 'operation'
  email_configs:
  - to: "xxxxx"
    html: '{{ template "email.html" . }}'
    headers: { Subject: "[WARN] 报警邮件" }
    send_resolved: true
#receivers:
- name: 'wechat'
  webhook_configs:
	# 这里是svc的名称;
  - url: 'http://alertinfo-svc/alertinfo'
    send_resolved: true
inhibit_rules:
  - source_match_re:
      severity: 'critical|warning'
    target_match:
      severity: 'info'
    equal:
    - instance

4. 参考

使用企业微信群机器人接收prometheus报警信息 - hsggj - 博客园 (cnblogs.com)

https://github.com/hsggj002/prometheus-flask文章来源地址https://www.toymoban.com/news/detail-861019.html

到了这里,关于Alertmanager实现企业微信机器人webhook告警的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • WorkTool无障碍服务实现企业微信机器人接口

    想要实现一个企业微信机器人,如京东/拼多多福利群、美团瑞幸定时营销群、自助订单查询、智能咨询或社群管理机器人等,首先官方未提供外部群/客户群的机器人API,会话存档也只在一定场景下适用,及时使用会话存档也存在只能收不能发的问题,有哪些办法可以合规的

    2024年02月14日
    浏览(37)
  • kube-prometheus实现企业微信机器人告警

    公司kubernetes生产环境部署了kube-prometheus-release-0.3用于监控kubernetes集群状态,但是默认预置了告警规则,但是不能发送告警信息。本文着重介绍自己在公司环境实现alertmanager通过企业微信发送告警信息。具体实现方式的逻辑如下图:  实现方式: 1.查看部署的kube-prometheus 2.在

    2023年04月08日
    浏览(28)
  • 基于飞书WebHook机器人的Alert Manager报警实现

    飞书,字节跳动旗下一站式企业协作平台,将即时沟通、智能日历、音视频会议、OKR、云文档、云盘和工作台深度整合,通过开放兼容的平台,集成第三方工具于工作台,让成员在一处即可实现高效的沟通和流畅的协作,全方位提升企业效率,为企业提供安全保障。 默认情况

    2024年02月12日
    浏览(29)
  • 第八篇: K8S Prometheus Operator实现Ceph集群企业微信机器人告警

    我们的k8s集群与ceph集群是部署在不同的服务器上,因此实现方案如下: (1) ceph集群开启mgr内置的exporter服务,用于获取ceph集群的metrics (2) k8s集群通过 Service + Endponit + ServiceMonitor建立ceph集群metrics与Prometheus之间的联系 建立一个 ServiceMonitor 对象,用于 Prometheus 添加监控项; 为

    2024年02月14日
    浏览(28)
  • 企业微信创建群机器人步骤

    1.选择群,右键点击“管理聊天信息“   2.添加机器人的信息    3.创建好的机器人都有一个唯一的Webhook地址,点击Webhook地址就可以看到文档说明,自动推送消息需要自行开发。     开发者中心地址:https://developer.work.weixin.qq.com/

    2024年02月13日
    浏览(33)
  • 飞书机器人webhook调用

    调用飞书机器人webhook进行打卡提醒

    2024年02月16日
    浏览(30)
  • 封装Python脚本:使用企业微信机器人发送消息至企业微信

    官方文档地址:https://developer.work.weixin.qq.com/document/path/91770#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E7%BE%A4%E6%9C%BA%E5%99%A8%E4%BA%BA 可以通过如下步骤设置企业微信机器人: 首先建立或者进入某个群聊 进入群聊设置页面, 点击“群机器人添加”可添加一个机器人成功 添加成功后,复制并保

    2024年02月09日
    浏览(26)
  • Zabbix配置企业微信报警机器人

    微信告警机器人是一种可以将Zabbix告警通知发送到微信群或个人微信号的工具。 1、申请企业微信 自己到企业微信官网申请一个账号 2、配置微信企业号 1、创建机器人 在电脑企业微信群创建机器人 在企业微信上创建一个群聊,并添加需要接收告警通知的成员。 在群管理创建

    2024年02月06日
    浏览(26)
  • 基于ChatGPT的企业微信机器人

    登录OpenAI的账号后,再点击右上角的“Personal”图标,然后点击“view API keys”进入API页面。 点击“create new secret key”按钮。 生成秘钥之后,把秘钥复制下来。 根目录下的config-template.json文件是配置文件的模板,复制该模板,修改复制的文件名为:config.json 打开刚才复制的c

    2024年02月13日
    浏览(31)
  • 企业微信机器人WorkTool使用文档

    先附一下官方介绍 源码友情链接 根据产品需求的 落地场景 我这里最看重的是他的自动创建外部群拉入客户和销售,并能用接口查询群聊记录,连企业微信会话存档的费用都省了,把机器人拉群里,@机器人问问题可以预先设置简单的问答库。另一个我看重的功能是自动通过

    2024年02月02日
    浏览(34)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包