EASY GUIDE FOR CONFIGURING SMS ALERT IN GRAFANA USING PYTHON AND AWS SNS: PART 1

Share this

In this guide we will learn how to setup our python API in container and configure grafana webhook to connect with our python API and test SMS alert.


If you read my previous blogs, we learnt how to setup various monitoring tools. However we cannot spend all our time by monitoring our resources. This is where grafana alerts plays an important role by alerting us whenever some abnormality is detected in our infrastructure. SMS alerts can be very useful.

By default grafana has inbuilt support for sending alerts in various platforms like discord, slack, email, telegram, etc. All of these platforms need internet to function. It would be really great if we could receive alert even if we didnt have internet connection available.

SMS alert would be great as it doesnt require internet connection. However, grafana doesnt have inbuilt support for SMS alert. But we can use AWS SNS service, boto3 and flask module of python to create a custom webhook api. And finally we can add this webhook url and setup SMS as a contact point.

Then we can create alert and customize it so that alert is sent as SMS.


PART 1: WRITNG OUR PYTHON SMS API CODE

Lets start by writing our python code. I am going to continue from our previous blog and continue working in the same directory. Look at my previous blog from the beginning if you are confused.

We are going to create a folder called sendsms inside prometheus folder and create our python program. Enter the following commands:

mkdir sendsms && cd sendsms
sudo nano sendsms.py

Now enter the following code inside it:

from flask import Flask, request
import boto3
APP = Flask(__name__)
CLIENT = boto3.client(
    "sns",
    aws_access_key_id="YOUR_AWS_SNS_ACCESS_KEY",
    aws_secret_access_key="YOUR_AWS_SNS _SECRECT_ACCESS_KEY",
    region_name="REGION_NAME"
)
@APP.route('/sendsms', methods=['POST'])
def sendsms():
    numbers = ["+9779860485417","+977XXXXXXXXX"]
    message = request.json["message"]
    print(message)
    for number in numbers:
        response = CLIENT.publish(
            PhoneNumber=number,
            Message=message,
            MessageAttributes={
                'AWS.SNS.SMS.SenderID':
                {
                    'DataType': 'String',
                    'StringValue': 'Grafana'
                }
            }
        )
    return response
    print("Message has been sent to" + number)
APP.run(host="0.0.0.0", port=5000)

In the above code we have imported boto3 module. It is an SDK provided by AWS to create, configure, and manage AWS services.

Also we have imported flask. We are going to use it to create a custom webhook API.

I wont be discussing about every lines of code here. For now you only need to know some important parameters to be filled which are:

  • AWS SNS Credentials:

aws_access_key_id=”YOUR_AWS_SNS_ACCESS_KEY”,

aws_secret_access_key=”YOUR_AWS_SNS _SECRECT_ACCESS_KEY”,

region_name=”REGION_NAME”

You can get these credentials from your AWS account.

  • Sendsms function:

Whenever our webhook url is called this function gets executed. Grafana also sends contents of alert message in our webhook url in JSON format. Our function simply catches that message and passes the message and phone number to the boto3 module and the rest is handled by the boto3 internal functions.

Enter your number along with country code as shown in example below:

numbers = [“+9779860485417″,”+977XXXXXXXXX”]

Our python application runs in port 5000.

PART 2: SETTING UP PYTHON CONTAINER

We are going to create a python container and run this code in the same network as grafana.

Before that lets create a requirements.txt file which lists modules to be installed i.e. flask and boto3.

sudo nano requirements.txt

Paste these inside it:

flask
boto3

Now lets setup our python container.

cd ..
sudo nano docker-compose.yml

Add this config:

awsapi:
    image: python:latest
    container_name: awsapi
    working_dir: /sendsms
    volumes:
      - "./sendsms:/sendsms"
    command: bash -c "pip install -r requirements.txt && python sendsms.py"
    restart: unless-stopped
    networks:
      - prometheus-network

Now save the file and lets start our container:

sudo docker-compose up --build -d

Lets check status of container:

sudo docker logs -n 10 awsapi

Seems like everything is working fine.

Now lets configure this as a contact point in grafana.

Go to alerting > Contact Points

Now set the values as shown below:

Lets test whether this is working or not. Click on test and then send test notification.

If everything is correct then you should receive a SMS from Grafana.

Thats it !! We have successfully added SMS as a contact point in grafana.

In my next blog i will teach you how to create a basic alert and send that alert notification to our phone as SMS.