天天看點

飛書 Amazon CloudWatch 告警代碼更新說明lambda_function函數告警資訊

說明

關于cloudwatch對接飛書告警部署細節,詳見飛書 Amazon CloudWatch 告警

lambda_function函數

# cat lambda_function.py

# -*- coding: UTF-8 -*-
# author: [email protected]
# date: 20211108
# version: V3
# Description: Use Feishu card template to send information

import requests
import json
import os

def lambda_handler(event, context):
    # Set Feishu parameters
    data_app = {
        "app_id": "your-id",
        "app_secret": "your-secret"
    }
    chat_name="your-chat-name"
    # Get token
    try:
        res = requests.post("https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/", json=data_app)
        if res.status_code == 200:
            res_json = res.json()
            access_token = res_json.get("tenant_access_token")
            access_token = access_token
    except Exception as e:
        return {"error": e}
    headers={
        "Authorization": "Bearer {}".format(access_token),
        "Content-Type": "application/json; charset=utf-8"
    }
    # 擷取群清單
    params = {
        "page_size": 100,
        "page_token": ""
    }
    try:
        res = requests.get("https://open.feishu.cn/open-apis/chat/v4/list", params=params, headers=headers)
        if res.status_code == 200:
            res_json = res.json()
            data = res_json.get("data")
            groups = data.get("groups")
            for i in groups:
                if i.get("name") == chat_name:
                    group = i
    except Exception as e:
        return {"error": e}
    # send Message
    chat_id = group.get("chat_id")
    print(chat_id)

    message = event['Records'][0]['Sns']
    Timestamp = message['Timestamp']
    Subject = message['Subject']
    sns_message = json.loads(message['Message'])
    region = message['TopicArn'].split(':')[-3]
    NewStateReason = json.loads(event['Records'][0]['Sns']['Message'])['NewStateReason']

    if "ALARM" in Subject:
        title = '[AI生産環境] 警報!!'
    elif "OK" in Subject:
        title = '[AI生産環境] 故障恢複!'
    else:
        title = '[AI生産環境] 警報狀态異常'

    content = "**【詳情資訊】**\n" \
              + "**時間**: " + Timestamp + "\n" \
              + "**内容**: " + Subject + "\n" \
              + "**狀态**: {old} => {new}".format(old=sns_message['OldStateValue'], new=sns_message['NewStateValue']) + "\n"  \
              + "**AWS區域**: " + sns_message['Region'] + "\n" \
              + "**監控資源對象**: " + sns_message['Trigger']['Namespace'] + "\n" \
              + "**監控名額**: " + sns_message['Trigger']['MetricName'] + "\n" \
              + "**報警名稱**: " + sns_message['AlarmName'] + "\n" \
              + "**報警建立方式**: " + sns_message['AlarmDescription'] + "\n" \
              + "**報警細節**: " + NewStateReason

    data_alert = {
        "chat_id": chat_id,
        "msg_type": 'interactive',
        "card": {
              "config": {
                  "wide_screen_mode": True
        },
        "header": {
            "template": "red",
            "title": {
                "tag": "plain_text",
                "content": title
            }
        },
        "elements": [
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": content
                }
            },
        ]
    }
    }
    data_recover = {
        "chat_id": chat_id,
        "msg_type": 'interactive',
        "card": {
              "config": {
                  "wide_screen_mode": True
        },
        "header": {
            "template": "green",
            "title": {
                "tag": "plain_text",
                "content": title
            }
        },
        "elements": [
            {
                "tag": "div",
                "text": {
                    "tag": "lark_md",
                    "content": content
                }
            },
        ]
    }
    }
    try:
        if "OK" in Subject:
            response=requests.post("https://open.feishu.cn/open-apis/message/v4/send/", headers=headers,json=data_recover)
        else:
            response=requests.post("https://open.feishu.cn/open-apis/message/v4/send/", headers=headers,json=data_alert)
        print(response)
        print(response.json())
    except Exception as e:
        return {"error":e}           

告警資訊

紅色告警

綠色恢複