Integrate Vonage With Grafana to Receive Notifications by SMS
Published on November 21, 2023

Introduction

Grafana is an open multi-platform observability platform that developers could use to keep track of metrics from applications or systems in the cloud. It generates analytics and visualization from the metrics with charts, graphs, and alerts. This article will show how to integrate Vonage with a Grafana setup to receive notifications by SMS using the Vonage Messages API.

The language of instruction will be Python. The knowledge shared via the proposed article would be helpful to DevOps teams, SREs, and system administrators who rely on Grafana to notify them of activities and unusual occurrences in their system.

Table of Content

Step 1: Set up the Grafana Stack

Grafana lets you set up your own Grafana instance on your local machine or server. Alternatively, you can use Grafana on the cloud when you sign up for a new account. Therefore, you won't have to install or maintain your Grafana instance, as it is cloud-based and managed.

Create a Dashboard

In this tutorial, You will build a simple dashboard using the built-in Grafana -- data source. For a new Grafana user, Grafana prompts a first-time workflow to guide you on creating a new dashboard. You can follow the steps in the prompts or the steps highlighted in this article section. You can skip this section if you are familiar with Grafana already.

  1. Click Dashboards in the left-side menu to go to the Dashboards page

  2. Click the New button to get a drop-down menu of options and select New Dashboard

  3. On the New dashboard page, click + Add Visualization to open up a model for choosing a data source.

  4. Select a data source modal and select the -- Grafana -- option on the right.

Select Data Sourceselect-data-source.png

When you select the -- Grafana -- option, which is the default built-in Grafana data source, two things happen:

- Grafana configures your query 
- Grafana generates the Random Walk dashboard.
  1. You can now click the Refresh dashboard icon in the following image to query the data source.

Create Contact Pointcreate-contact-point.png

  1. Then, you can click Save in the top-right corner. You will be prompted to supply a name for the dashboard before it is saved.

You should now have a basic dashboard set up in your Grafana account. You can explore Grafana further by adding data sources to create dashboards for your other projects.

Step 2: Create a Python Application For the Implementation of Logic

You need to install Flask to power the Python script you will use in this tutorial. You can run the following command in your terminal to install Flask.

pip install flask

Write the First Python Function

Now, you will set up a Flask webhook for receiving Grafana alerts.

Create a file, notify.py, and add the following Python code.

from flask import Flask, request

app = Flask(__name__)

@app.route("/grafana-webhook", methods=["POST"])

def grafana_webhook():

    if request.method == "POST":

        data = request.json

        alert_description = data["alerts"][0]["annotations"]["desc"]

        print(alert_description)

        return "Webhook received!"

if __name__ == "__main__":

    app.run(host="", port=3000, debug=True)

In the above code, you:

  • created a POST route, /grafana-webhook

  • The route decorates the grafana_webhook function, a POST endpoint for receiving POST requests.

  • extracted the alert_description from the request payload

  • One of the extracted attributes, alert_summary, is printed to the console at runtime using the print() function.

  • You designated port 3000 for the application to run on. Doing this will allow mapping the application port with the port where Ngrok would run. That way, the application is served via the Ngrok server.

To run the application locally, use the following bash command in your terminal:

python notify.py 3000

You should get a terminal output like the following, signifying an active development server:

* Serving Flask app 'notify' * Debug mode: on WARNING: This is a development server. Please do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:3000 Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 144-577-375

Setup Ngrok Server

Then, you can install Ngrok, a lightweight online server for testing the Python application. It will allow you to serve your Python script over the public internet. Follow the installation instructions on the official website to install it.

You can run Ngrok with the following terminal command, and it will spin up a lightweight server for you:

ngrok http 3000

Running the above command spins up a lightweight server for you, and you will see its public URL in your terminal like the following:

https://d5fs-104-25-63-145.eu.ngrok.io -> http://localhost:3000

This implies that your webhook endpoint based on your Python script is as follows:

https://d5fs-104-25-63-145.eu.ngrok.io/grafana-webhook

This will be your dedicated URL for Grafana to send webhook notifications to your Python application.

Connect Grafana With The Python Application

To connect Grafana with your Python application, you will specify the webhook URL through which Grafana can send its alerts to your application. Since you have a webhook URL for this purpose, you will add it to the Alerts contact points on your Grafana dashboard. Follow the next steps to configure your Grafana Alerts with your application webhook.

  1. On the Grafana main menu, go to Alerts & IRM > Alerting, as shown in the following screenshot.

Alerting Menualerting-menu.png

  1. Click Contact Points on the Alerting page to go to the Contact Points page, as shown in the following screenshot. Click the + Add Contact Point button. This takes you to the Create Contact Point page in the following screenshot.

Contact Pointscontact-points.png

  1. Input your desired Name, and select Webhook in the Integration list. Input your dedicated webhook URL in the URL field, as shown in the following screenshot.

Contact Point Setupcontact-point-setup.png

  1. You may click the Test button to follow the prompts for testing the contact point. Try using the custom notification option while testing, not the predefined option. This will allow your endpoint code to correctly parse the notification summary and description for you to see in your terminal. The test sends a dummy notification to your webhook URL. If the notification was successfully sent, you will get a success alert, “Test alert sent”, at the top-right corner of the page, as shown in the following image.

Test Alert Senttest-alert-sent.png

  1. Click the Save Contact Point button to save the contact point.

Step 3: Configure Vonage Account For Messages API SMS Notification

Define Vonage Application URLs

You can append the status and inbound endpoints to the URL that Ngrok generated. They will look like the following:

Status URL: https://d5fs-104-25-63-145.eu.ngrok.io/webhooks/message-status

Inbound URL: https://d5fs-104-25-63-145.eu.ngrok.io/webhooks/inbound-message

Note the above URLs, as you will need them when configuring your Vonage account for the Messages API in the following section.

Configure A Vonage Application

You need to sign up for a Vonage account if you don’t already have one.

You need a Vonage account configured with the Messages API to send SMS messages to your users via Vonage. In this case, your user might be a teammate you want to notify about your Grafana updates.

Use the following steps to configure your Vonage account for the Messages API:

  1. Navigate to the API Settings menu on your Vonage dashboard main menu to go to the API Settings page. The API Settings

  2. In the SMS settings section, select Messages API. Leave other settings there in their defaults.

  3. Visit the applications page and click the + Create application button to create an application.

  4. Input a name in the Name field. Click the Generate public and private key button. A private key file private.key will be downloaded to your local machine.

  5. Select Messages in the Capabilities section.

  6. Enter the Inbound and Status URL you noted while setting up Ngrok.

  7. Click the Generate new application button to complete the creation. Then, you will be redirected to the application overview page, where you can also link your Vonage number to the application.

Note: Check out Manage Numbers with the Vonage CLI for a short guide on buying a Vonage number.

You must note the APPLICATION ID on the application overview page, as you will need it in the next session. You must also note the local path where the private.key file is located. They should look like the following:

Application ID: 53a2ed68-f2d8-498c-9b17-032669e3bf90

Private Key Path: /Users/Downloads/private.key

Send SMS To User

In this subsection, you will send the Grafana webhook notification to your user via SMS. You can use the Vonage Python SDK for this feature in a Python application. Use the following bash command to install the Vonage Python SDK on your local machine.

pip install vonage

Next, add the following code to your Python script:

...

import vonage

def grafana_webhook():

    if request.method == "POST":

        ...

        client = vonage.Client(

            application_id=YOUR_VONAGE_APPLICATION_ID,

            private_key=YOUR_APPLICATION_PRIVATE_KEY_PATH,

        )

        notification = client.messages.send_message(

            {

                "channel": "sms",

                "message_type": "text",

                "from": YOUR_VONAGE_NUMBER,

                "to": DESTINATION_PHONE_NUMBER,

                "text": alert_description,

            }

        )

        return "Webhook successfully delivered as a notification message."

In the above code:

  • You initialized the Python SDK client with the line client = vonage.Client(). Replace the YOUR_VONAGE_APPLICATION_ID and YOUR_APPLICATION_PRIVATE_KEY_PATH with the application ID and private key path of the Vonage application you created earlier.

  • You then used the send_message() function in the line notification = client.messages.send_message() to send a message with the initialized client where:

    • "channel": is the message mode, SMS.

    • "message_type": text format of the message to be sent.

    • "from": the sender of the message. You can use your Vonage number here. Replace YOUR_VONAGE_NUMBER with your purchased number.

    • "to": the recipient who receives the SMS, a phone number. Replace DESTINATION_PHONE_NUMBER with the recipient number.

    • "text": the message content to be sent, which is the alert description string from Grafana.

  • You modified the return statement to reflect the action when the code runs.

The complete code is as follows:

from flask import Flask, request

import vonage

app = Flask(__name__)

@app.route("/grafana-webhook", methods=["POST"])

def grafana_webhook():

    if request.method == "POST":

        data = request.json

        alert_description = data["alerts"][0]["annotations"]["desc"]

        print(alert_description)

        client = vonage.Client(

            application_id=YOUR_VONAGE_APPLICATION_ID,

            private_key=YOUR_APPLICATION_PRIVATE_KEY_PATH,

        )

        notification = client.messages.send_message(

            {

                "channel": "sms",

                "message_type": "text",

                "from": YOUR_VONAGE_NUMBER,

                "to": DESTINATION_PHONE_NUMBER,

                "text": alert_description,

            }

        )

        return "Webhook successfully delivered as a notification message."

if __name__ == "__main__":

    app.run(host="", port=3000, debug=True)

Test the Application

To test the code and ensure the setup works, navigate to Contact Points on your Grafana dashboard and select the edit contact point button. This is shown in the following image.

Edit Contact Point Buttonedit-contact-button.png

You can send a test webhook notification in the Test contact point modal, as shown in the following image.

Test Contact Pointtest-contact-point.png

  1. Select the Custom tab to send a test custom message

  2. Supply your preferred summary and description texts

  3. Scroll down to click the Send test notification button

  4. The recipient should receive a test message like the following screenshot:

Alert from Grafanaalert-from-grafana.png

Summary

This article has provided a guide on using the Grafana webhook notification system to get and send alerts to your users using the Vonage Messages API. We discussed setting up your Grafana dashboards, creating Python webhooks with Flask, and configuring a Vonage application that works with the Messages API.

If you have questions or feedback, join us on the Vonage Developer Slack or send us a Tweet on X, previously known as Twitter, and we'll get back to you. Thanks again for reading, and we'll catch you on the next one!

Further Resources

  • Check out Grafana documentation on more Alerting configuration

  • See more ways to use the Messages API in its documentation

Jekayinoluwa Olabemiwo

Jẹ́káyinOlúwa is a software craftsman and product manager passionate about technology and its impact on people. He works on product management, backend development, DevOps, technical writing, and community strategy. He enjoys dealing in the intersection of software, design, and human interaction. He likes reading and music.

Ready to start building?

Experience seamless connectivity, real-time messaging, and crystal-clear voice and video calls-all at your fingertips.

Subscribe to Our Developer Newsletter

Subscribe to our monthly newsletter to receive our latest updates on tutorials, releases, and events. No spam.