AWS CloudWatch 告警发送到微信:完整代码示例
以下是一个示例 Python 代码,用于将 AWS CloudWatch 告警发送到微信:
import json
import urllib.request
def lambda_handler(event, context):
# 从事件中获取告警的详细信息
message = json.loads(event['Records'][0]['Sns']['Message'])
alarm_name = message['AlarmName']
alarm_description = message['AlarmDescription']
new_state = message['NewStateValue']
reason = message['NewStateReason']
region = message['Region']
# 填写你的微信机器人 Webhook 地址
webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
# 构建微信消息体
data = {
"msgtype": "text",
"text": {
"content": f'{alarm_name} 触发了 {new_state} 状态,原因是 {reason}。'
}
}
# 发送 POST 请求到微信机器人 Webhook
req = urllib.request.Request(webhook_url)
req.add_header('Content-Type', 'application/json; charset=utf-8')
json_data = json.dumps(data).encode('utf-8')
req.add_header('Content-Length', len(json_data))
response = urllib.request.urlopen(req, json_data)
# 打印响应
print(response.read().decode('utf-8'))
该代码使用 Python 的 urllib 库向微信机器人 Webhook 发送 POST 请求,并将告警信息以 JSON 格式作为请求体发送。在 AWS Lambda 中,可以将该代码作为 Lambda 函数上传并配置 CloudWatch 告警触发器,使其在告警触发时自动发送微信消息。请注意,该代码仅供参考,具体实现可能需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/mNI5 著作权归作者所有。请勿转载和采集!