Easy server monitoring with AWS Lambda (Python) and result notification in Slack

What I wanted to achieve

--As a simple monitoring of the operating server, I want to periodically perform HTTP access and check the result. --I want to run serverless. --Since the IP that accesses the target server is restricted, the monitoring source needs to have a fixed IP. ――I want you to fully automate and be notified only of the monitoring results.

What was finally achieved

--Overall image 全体イメージ


--Place the monitored server data in S3. --The data format is as follows.

	```json:servers.json
	{
	    "servers": [
	        {"name": "Google", "url": "http://www.google.co.jp"},
	        {"name": "Yahoo", "url": "http://www.yahoo.co.jp"}
	    ]
	}
	```

--ʻRead the above data from AWS Lambda (Python) `and make HTTP access to each server.

--Notify Slack of the monitoring result. --Periodically execute the above with CloudWatch Events --Schedule.

Setting details

VPC settings

――See what you wanted to achieve, as it was completely covered below. - https://www.joyzo.co.jp/blog/2325

IAM settings

--When creating Lambda, select Simple Microservice permissions as the role template. --Attach the policy of ʻAmazonS3ReadOnlyAccess to access S3. --Attach the policy of ʻAWS LambdaVPCAccessExecutionRole to run Lambda on VPC.

CloudWatch Events --Schedule Settings

Slack

-Refer to Incoming Webhooks to get the URL for notification to Slack.

AWS Lambda(Python)

--There is room for improvement around error handling.

lambda_function.py


import json
import requests
import boto3

BUCKET_NAME = 'xxxxxxxxxx'
OBJECT_NAME = 'xxxxxxxxxx/servers.json'
SLACK_POST_URL = 'https://hooks.slack.com/services/xxxxxxxxxx/xxxxxxxxxx/xxxxxxxxxxxxxxxxxxxx'

def lambda_handler(event, context):
    json_data = __getServers()
    __check_server(json_data)

def __getServers():
   s3 = boto3.resource('s3')
   obj = s3.Object(BUCKET_NAME, OBJECT_NAME)
   response = obj.get()
   body = response['Body'].read()
   return body.decode('utf-8')

def __check_server(json_data):
    data = json.loads(json_data)
    servers = data['servers']

    has_error = False

    for server in servers:
        name = server['name']
        url = server['url']
        print("Check: " + name)

        try:
            r = requests.get(url)
            if r.status_code != 200:
                __send_error_message(name, url)
                has_error = True
        except requests.exceptions.RequestException as e:
            __send_request_error_message(name, url)
            has_error = True

    if has_error == False:
        __send_success_message()

def __send_error_message(name, url):
    payload = {
        "text": name + '\n' + url + '\n' + '*ERROR!*',
        "icon_emoji": ":x:"
    }
    __send_message(payload)

def __send_request_error_message(name, url):
    payload = {
        "text": name + '\n' + url + '\n' + '*Request Error!*',
        "icon_emoji": ":warning:"
    }
    __send_message(payload)

def __send_success_message():
    payload = {
        "text": "All Servers OK!",
        "icon_emoji": ":o:"
    }
    __send_message(payload)

def __send_message(payload):
    try:
        return requests.post(SLACK_POST_URL, json=payload)
    except requests.exceptions.RequestException as e:
        return None


Precautions when setting AWS Lambda (Python)

--Place the library in the same directory as the source code.

pip install requests -t .

--Put the source code and library together in a zip.

zip -r lambda_function.zip *

Miscellaneous feelings

―― With the ability to set a VPC for AWS Lambda, you can run Lambda with a fixed IP address as the data source, which has expanded the range of uses. ――As a handy notification destination, cooperation with Slack is too easy and convenient. --I also tried a method in which the contents of servers.json are packed in the body and executed via ʻAPI Gateway triggered by HTTP POST communication, but in the end it became the current form that is easy to execute regularly.

Recommended Posts

Easy server monitoring with AWS Lambda (Python) and result notification in Slack
Site monitoring and alert notification with AWS Lambda + Python + Slack
Install pip in Serverless Framework and AWS Lambda with Python environment
Sample to send slack notification with python lambda
Dynamic HTML pages made with AWS Lambda and Python
Make ordinary tweets fleet-like with AWS Lambda and Python
[Python] Scraping in AWS Lambda
Easy HTTP server with Python
It is easy to execute SQL with Python and output the result in Excel
Write AWS Lambda function in Python
Notify HipChat with AWS Lambda (Python)
Easy modeling with Blender and Python
I compared Node.js and Python in creating thumbnails using AWS Lambda
[AWS] Using ini files with Lambda [Python]
Device monitoring with On-box Python in IOS-XE
Dealing with "years and months" in Python
Traffic monitoring with Kibana, ElasticSearch and Python
[AWS] Link Lambda and S3 with boto3
Easy image processing in Python with Pillow
Connect to s3 with AWS Lambda Python
Easy web scraping with Python and Ruby
Touch AWS with Serverless Framework and Python
Python + Selenium + Headless Chromium with aws lambda
[AWS] Create a Python Lambda environment with CodeStar and do Hello World
RabbitMQ message notification app in Python with Growl ~ with Raspberry Pi and Julius ~
Upload what you got in request to S3 with AWS Lambda Python
Put Docker in Windows Home and run a simple web server with Python
Differences between queryStringParameters and multiValueQueryStringParameters in AWS Lambda
LINE BOT with Python + AWS Lambda + API Gateway
Serverless application with AWS SAM! (APIGATEWAY + Lambda (Python))
Easy X-Ray with Lambda Layer and CloudFormation / sam-cli
Launch a web server with Python and Flask
Getting started with AWS IoT easily in Python
Create a setting in terraform to send a message from AWS Lambda Python3.8 to Slack
Throw costly instance health in Slack with Lambda
Amazon API Gateway and AWS Lambda Python version
[Super easy] Simultaneous face recognition and facial expression recognition in real time with Python and OpenCV!
Create Amazon Linux with AWS EC2 and log in
Easy partial download of mp4 with python and youtube-dl!
Get the result in dict format with Python psycopg2
Calculate Pose and Transform differences in Python with ROS
Easy HTTP server and Systemd autostart settings in Go
Deploy Python3 function with Serverless Framework on AWS Lambda
Create a Layer for AWS Lambda Python with Docker
I want to AWS Lambda with Python on Mac!
Start numerical calculation in Python (with Homebrew and pip)
[Python] Retry process (Exponential Backoff) memo in AWS Lambda
Create a fake Minecraft server in Python with Quarry
AWS CDK with Python
DNS server in Python ....
Local server with python
Posted as an attachment to Slack on AWS Lambda (Python)
Easy to use Nifty Cloud API with botocore and python
Design and test Verilog in Python only with Veriloggen and cocotb.
screen and split screen with python and ssh login to remote server
[AWS] Try adding Python library to Layer with SAM + Lambda (Python)
I tried follow management with Twitter API and Python (easy)
Send experiment results (text and images) to slack with Python
Tips for coding short and easy to read in Python
Easy with just Python! Output Graphviz figures in draw.io format!
Post images of Papillon regularly on Python + AWS Lambda + Slack