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

# 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665907710576/oPJr2MyIa.png align="left")

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](https://data-asg.goldprice.org/dbXRates/EUR). 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](https://nodejs.org/en/download/), then create a project using:

```bash
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:

```bash
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.

```bash
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](https://aws.amazon.com/sdk-for-javascript/), this module is really big(&gt;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:

```bash
npm uninstall aws-sdk
```

We need to zip the code like this:

![zip.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665861537992/3-IF7q4Nn.png align="left")

## Create AWS Lambda and upload the zip file

> I assume you already have an AWS account, if not you can create one here https://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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665861895442/cmsze7I9e.png align="left")

* 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665862070630/PwqeiXVSg.png align="left")

* Upload the zip file
    

![Upload zip file.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665862239361/Y7z0x_20U.png align="left")

The Lambda will look like this:

![Lambda code.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665862403513/TOztnh9jm.png align="left")

# 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665862977126/ha3kTDeEL.png align="left")

* 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 &gt; Subscriptions &gt; Create subscription
    

![Add SNS Email Subscription.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665909248307/A5Y6jpkP5.png align="left")

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:

```bash
    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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665863471793/712F7XrCX.png align="left")

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 &gt; Configuration &gt; Permissions
    

![Change Lambda role.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665863649238/mi4XdXUzk.png align="left")

* Create a new Policy that allows only sns:Publish and link it to this role
    

```bash
{
    "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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665907878189/LdAGgNtIm.png align="left")

![SMS.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665907946064/wiV9eKrZh.png align="left")

> Note: you need also to give the Lambda enough timeout, you can configure this on Lambda &gt; Configuration &gt; General configuration &gt; Edit &gt; 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665908503995/865_q0dza.png align="left")

* 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](https://cdn.hashnode.com/res/hashnode/image/upload/v1665908657637/nsPUqAMO2.png align="left")

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

![EventBridge3.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1665908778548/4qXFRrhfL.png align="left")

* Click next &gt; next &gt; 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](https://github.com/laidani/Notification-system-using-AWS-lambda-SNS-EventBridge-and-Terraform)
