[PYTHON] [AWS] Detects the specified character string from the Lambda execution log and notifies slack

This time, I will introduce one of the notification methods that can be used when operating using AWS services that I often touch.

Service used

Implementation flow

  1. Output logs from Lambda function to CloudWatch Logs
  2. Detect the specified character string from CloudWatch Logs
  3. Fire the Lambda function for Slack notification triggered by the detected character string
  4. Notify Slack of strings with Lambda for notification

Flow details

We will actually implement it according to the above flow.

__ Step 1 __

This time, the string "test" is output to CloudWatch Logs. スクリーンショット 2020-12-23 16.14.07.png

__ Step 2 __

We will use the CloudWatch Logs subscription filter (Lambda) for string detection. スクリーンショット 2020-12-23 16.25.49.png

__ Step 3 __

Set the Lambda function for notification, log format and filter pattern スクリーンショット 2020-12-23 16.35.33.png

__ Step 4 __

The environment variable "Webhook URL" is set to the slack Webhook URL you want to notify.

notifi.py


import json
import os
import urllib.request
import slackweb

def lambda_handler(event, context):
    decoded_data = zlib.decompress(
        base64.b64decode(event['awslogs']['data']),
        16+zlib.MAX_WBITS
    )
    json_data = json.loads(decoded_data) 
    print(json_data['logEvents'])
    for i in json_data['logEvents']:
        test = i['message'] #Log contents
        slack = slackweb.Slack(url=os.environ['WebhookURL'])
        slack.notify(text=test)

I confirmed that it detects the character string set earlier and notifies slack. スクリーンショット 2020-12-23 16.48.51.png

Summary

There are multiple notification methods other than the above, but it is easier to manage if you summarize them as concisely as possible, so I would like to make it easier and easier to simplify.

Recommended Posts

[AWS] Detects the specified character string from the Lambda execution log and notifies slack
Outputs a line containing the specified character string from a text file
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate
Divides the character string by the specified number of characters. In Ruby and Python.
Python version (PHP to Python) that deletes the subsequent character string from the specified character string (extension)
Tweet from AWS Lambda
Remove double-byte spaces before and after the character string (python)
Site monitoring and alert notification with AWS Lambda + Python + Slack