Skip to content

Instantly share code, notes, and snippets.

@momota10s
Created November 18, 2021 11:09
Show Gist options
  • Save momota10s/cea8e38d1b95fd14710dc28b16cd2ed4 to your computer and use it in GitHub Desktop.
Save momota10s/cea8e38d1b95fd14710dc28b16cd2ed4 to your computer and use it in GitHub Desktop.
cloudwatchのサブスクリプションにlambdaを登録してエラーをslackに通知するスクリプト
import os
import gzip
import json
import base64
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
SLACK_CHANNEL = os.environ['SLACK_CHANNEL']
SLACK_WEBHOOK = os.environ['SLACK_WEBHOOK']
def lambda_handler(event, context):
print("Event: " + str(event))
cw_data = event['awslogs']['data']
compressed_payload = base64.b64decode(cw_data)
uncompressed_payload = gzip.decompress(compressed_payload)
payload = json.loads(uncompressed_payload)
print("payload: " + str(payload))
log_events = payload['logEvents']
print("log_events: " + str(log_events))
for log_event in log_events:
send_message(log_event)
return {
'statusCode': 200,
'body': json.dumps('finish!')
}
def send_message(log_event):
slack_message = {
'channel': 'your-slack-chanell',
'icon_emoji': ":error-dayo:",
'username': 'your-username',
'attachments': [
{
'color': '#ff4400',
'title': 'error messenger',
'fields': [
{
'title': 'message',
'value': log_event['message'],
'short': True,
}
]
}
]
}
req = Request(SLACK_WEBHOOK, json.dumps(slack_message).encode("utf-8"))
try:
response = urlopen(req)
response.read()
print("Message posted to ", slack_message['channel'])
except HTTPError as e:
print("error: Request failed: ", e.code, e.reason)
except URLError as e:
print("error: Server connection failed: ", e.reason)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment