Create a notification system using AWS Lambda, SNS, and Event Bridge

Create a notification system using AWS Lambda, SNS, and Event Bridge

AWS Sample using Lambda, SNS, Event Bridge, Terraform

Introduction

In this article, we will create a process to get a notification if the price of silver or gold is below x price. This example can be used with any service, for example, to check airline prices or dates, amazon product prices, appointments, etc...

Architecture

Architecture.png

The idea here is to start a Lambda using EventBridge, this Lambda will make an HTTP query, in this example, we use an endpoint from goldprice.org. If the price of gold is below 1500 EUR, the lambda will publish a notification in an SNS topic, and the topic will send an email, SMS, or both.

Lambda

The lambda is made using NodeJS, to create this you need to install NodeJS, then create a project using:

npm init

and follow the instructions.

Lambda code

After the project is created, create a file index.js then copy and paste the following code:

const request = require('request-promise');
const aws = require("aws-sdk");
const sns = new aws.SNS();

const priceAlert = 1500;

const options = {
    'method': 'GET',
    'url': 'https://data-asg.goldprice.org/dbXRates/EUR',
    resolveWithFullResponse: true
};

function check_gold_price() {
    return request(options);
}

function send_message(price) {
    const snsParams = {
        TopicArn: "arn:aws:sns:<Region>:<AccountId>:<TopicName>",
        Subject: "Gold price",
        Message: `Hey, the price of gold is ${price}`
    };
    let response = sns.publish(snsParams).promise();

    response.then(function () {
        console.log('Message has been sent');
    }).catch(function (err) {
        console.error(err, err.stack);
    });
}

exports.handler = () => {
    check_gold_price().then(response => {
        if (response.statusCode === 200 && response.body) {
            let json = JSON.parse(response.body);
            let price = json.items[0]?.xauPrice;
            if (price < priceAlert) {
                send_message(price);
            }
        }
    });
};

To install the missing modules, execute this command.

npm install

Lambda package

there are many ways to deploy your code to Lambda, in this article we will use the simple one, we will zip our code and upload it to the lambda.

As you have seen in the code of our Lambda, we use aws-sdk, this module is really big(>80MB), and we don't need it to be packaged with the other modules, because the Lambda runtime has already this module. to remove this module we can just execute:

npm uninstall aws-sdk

We need to zip the code like this:

zip.png

Create AWS Lambda and upload the zip file

I assume you already have an AWS account, if not you can create one here aws.amazon.com

In this article, we will create a Lambda from the AWS console, to do this:

  • Login to your AWS Account

  • Search Lambda

search lambda.png

  • Select Functions, and then click Create function button

  • Then fill in the information, and in the end click Create function button

create new AWS Lambda.png

  • Upload the zip file

Upload zip file.png

The Lambda will look like this:

Lambda code.png

Create SNS Topic

To create an SNS Topic:

  • Search SNS in the AWS console

  • Select Simple Notification Service

  • Select Topics and then click Create Topic button

  • Choose a Standard topic and give a name to the topic like this

TopicSNS.png

  • Click at the end Create topic button

SNS Subscriptions

In this step, we will add an email to test the process, to do this:

  • Amazon SNS > Subscriptions > Create subscription

Add SNS Email Subscription.png

In this example, we add only an email, you can add a phone number, and many other services to receive notifications.

Select the ARN of the topic and put it in TopicArn like this:

    const snsParams = {
        TopicArn: "arn:aws:sns:eu-west-1:1222331122:MyTopic",
        Subject: "Gold price",
        Message: `Hey, the price of gold is ${price}`
    };

Note: this is not the recommended way, and it is really bad in some cases, to do things better, you must use Environment variables, by Secret Manager, or KMS, it depends on your variables.

When you test the Lambda you will get this error:

Error.png

To fix this error, you have to give your Lambda the right to publish SNS notifications, to do this:

  • Select the Lambda's role from Lambda > Configuration > Permissions

Change Lambda role.png

  • Create a new Policy that allows only sns:Publish and link it to this role
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "sns:Publish",
            "Resource": "arn:aws:sns:eu-west-1:1222331122:MyTopic"
        }
    ]
}

Test again, and everything will work correctly, and you will receive an email and SMS that looks like this

Email.png

SMS.png

Note: you need also to give the Lambda enough timeout, you can configure this on Lambda > Configuration > General configuration > Edit > and change the Timeout to 30sec for example.

EventBridge

Until now everything is good, we will just configure the EventBridge to launch the Lambda each period of time, to configure this:

  • Search EventBrdidge in the AWS console

  • Select Amazon EventBridge

  • Select Rules then click Create rule button

  • Give a name to this rule and choose the Schedule rule type and click the next button

EventBridge1.png

  • Choose "A schedule that runs at a regular rate, such as every 10 minutes" as the schedule pattern

  • For the "Rate expression" for test purposes we use 5min and click the next button

EventBridge2.png

  • For "Target" select Lambda, and then choose the name of Lambda that we have created

EventBridge3.png

  • Click next > next > Create rule in the end

In this stage, the Lambda will be executed each 5min, if the price is below 1500 EUR, a notification will be sent via SNS.

That's it.

Terraform

You found the terraform for this sample here: https://github.com/laidani/Notification-system-using-AWS-lambda-SNS-EventBridge-and-Terraform