Let's use AWS Lambda to create a mechanism to notify slack when the value monitored by CloudWatch is exceeded on Python

Introduction

I'm talking inside the company, "Ramu but Ramu," and for me, a former C #, is it something of a programming language? I thought, but it wasn't. (There is a lambda expression in C #.)

Internally, I placed the node.js runtime on AWS Lambda and notified slack, but I was told that the version of node is old and I will stop supporting it soon, so I decided to switch to Python. (Because there was a person in the company who knew Python better than node)

In AWS Lambda, common processing is provided as a template, so it is fairly easy to do. I will summarize the procedure.

Setup steps

Roughly follow the steps below.

  1. Create Lambda function
  2. Creating SNS and linking with Lambda
  3. Cooperation between EC2 and SNS
  4. Coding
  5. Test

Diagram

The final result will be something like this.

aws.png

procedure

1. Creating a Lambda function

Create the main Lambda function this time. You can easily make it by following the instructions. Rest assured that you can easily recreate or delete it.

Select Lambda from the service list.

①.png

Start creating your Lambda function.

②.png

If you enter slack in the filter, you can create a slack template, but this time we will create it with blanks.

③.png

You'll set the trigger later, so leave it empty.

④.png

2. Creating SNS and linking with Lambda

SNS = Simple Notification Service. It is a service that receives some processing or status change and notifies you as a message. You can send messages to emails and Lamda like this one. The service itself has not been translated as of April 06, 2017, but I think that there is no problem because it is simple English.

Create an SNS and attach the subscription.

Create Subscriptions.

AWS_SNS.png

Select the Lambda function you just created

AWS_SNS.png

3. Cooperation between EC2 (Cloud Watch) and SNS

Set an alarm from the EC2 screen.

EC2_Management_Console.png

4. Coding

Make various settings

The settings are as follows.

This time I set it as follows.

Lambda_Management_Console.png

@code

lambda_handler.py


from __future__ import print_function

import boto3
import json
import logging
import os

from urllib2 import Request, urlopen, URLError, HTTPError

#slack settings
SLACK_CHANNEL = os.environ['SLACK_CHANNEL']
HOOK_URL      = os.environ['HOOK_URL']

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    logger.info("Event: " + str(event))
    message = json.loads(event['Records'][0]['Sns']['Message'])
    logger.info("Message: " + str(message))

    alarm_name  = message['AlarmName']
    description = message['AlarmDescription']
    new_state   = message['NewStateValue']
    reason      = message['NewStateReason']

    if new_state == 'OK':
        emoji = ":+1:"
    elif new_state == 'ALARM':
        emoji = ":exclamation:"
        
    slack_message = {
        'channel': SLACK_CHANNEL,
        'text': "*%s %s: %s*\n %s\n %s" % (emoji, new_state, alarm_name, description, reason)
    }

    req = Request(HOOK_URL, json.dumps(slack_message))
    try:
        response = urlopen(req)
        response.read()
        logger.info("Message posted to %s", slack_message['channel'])
    except HTTPError as e:
        logger.error("Request failed: %d %s", e.code, e.reason)
    except URLError as e:
        logger.error("Server connection failed: %s", e.reason)

@ Environment variable + Arufa

Lambda_Management_Console_1.png

5. Test

From the Lambda screen, do the following:

  1. Action → Test event setting → Test event input
  2. Save and test

This is miso, but I hope you can refer to this for test data.

Execution result

A notification has been successfully sent to the sandbox channel. It also contains emoji.

Slack_-_eversense.png

in conclusion

I was able to realize slack notification with a simple program. Set the metrics appropriately and enjoy a comfortable AWS life. (Even if you notify me, it doesn't make sense if you look at it ...)

In addition, it seems that only SNS created in the same region can be set from Lambda, so if you want to cross regions, select Lambda from SNS of each region.

At first, I tried to use Lambda environment variables, but I couldn't use it because I got an error around base64. If you can use this, the Lambda function can be easily reused, so I will deal with it properly at the next opportunity.

Recommended Posts

Let's use AWS Lambda to create a mechanism to notify slack when the value monitored by CloudWatch is exceeded on Python
Use Heroku in python to notify Slack when a specific word is muttered on Twitter
Use AWS lambda to scrape the news and notify LINE of updates on a regular basis [python]
How to automatically notify by phone when the python system is down
It is convenient to use Layers when putting a library on Lambda
Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack
"Cython" tutorial to make Python explosive: Handling when a function on the C ++ side is passed by reference.
A little trick to know when writing a Twilio application using Python on AWS Lambda
Posted as an attachment to Slack on AWS Lambda (Python)
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
About the error I encountered when trying to use Adafruit_DHT from Python on a Raspberry Pi
Things to note when running Python on EC2 from AWS Lambda
What to do when the value type is ambiguous in Python?
ImportError when trying to use gcloud package with AWS Lambda Python version
What is the fastest way to create a reverse dictionary in python?
Notify Slack when the machine learning process running on GCP is finished
Notify slack when the switch sales page is updated ~ slack bot development with python ③ ~
The format of the message obtained by Slack API is subtly difficult to use
Lambda Function (python version) that decompresses and outputs elements to CloudWatch Logs when a compressed file is uploaded to s3
Periodically run a python program on AWS Lambda
[Introduction to AWS] The first Lambda is Transcribe ♪
Python Note: When assigning a value to a string
Summary of studying Python to use AWS Lambda
[Python] Throw a message to the slack channel
Create a python script to check if the link at the specified URL is valid 2
A story that got stuck when trying to upgrade the Python version on GCE
It is better to use NTFS when connecting SSD to Linux to create a file server.
Create a python script to check if the link at the specified URL is valid
It was a life I wanted to OCR on AWS Lambda to locate the characters.
How to create a Python 3.6.0 environment by putting pyenv on Amazon Linux and Ubuntu
Try running a Schedule to start and stop an instance on AWS Lambda (Python)
Use AWS Lambda + LINE Notify to notify LINE not to forget your umbrella when you get home
Steps to use the AWS command line interface (Python / awscli) on Mac OS X
Use Twitter API to reduce the time taken by Twitter (create a highlighting (like) timeline)
Add a function to tell the weather of today to slack bot (made by python)
Check types_map when using mimetypes on AWS Lambda (Python)
Create a Layer for AWS Lambda Python with Docker
Re: Python lambda is useless ^ H ^ H ^ H ^ H ^ H Difficult to use
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
I tried to create a Python script to get the value of a cell in Microsoft Excel
When a character string of a certain series is in the Key of the dictionary, the character string is converted to the Value of the dictionary.
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7