Send an SNS notification using AWS Lambda

Subscribe to my newsletter and never miss my upcoming articles

Welcome! Today, I am going to show you how to write an AWS Lambda Function that sends an SNS notification.

🐦 Follow me on Twitter if you would like to see more content like this! 🐦

TLDR - Here is a link to my Github with the given code.

1. Initialize the Project

You can follow my previous post on how to use AWS SAM to spin up a boilerplate Lambda function.

2. Email

First, let's write a function to send an email and return a promise.

function sendEmail(message){
    const awsRegion = "us-east-1";
    // FIXME - update this ARN
    const snsTopic = 'arn:aws:sns:us-east-1:12341234-ABCDABCD';
    const snsSubject = 'SNS Subject';
    // Create publish parameters
    var params = {
      Message: message,
      Subject: snsSubject,
      TopicArn: snsTopic
    };
    var sns = new AWS.SNS({ region: awsRegion });
    return sns.publish(params).promise();
}

3. Next, we bring it all together in the handler.

const AWS = require("aws-sdk");    

/**
 * A Lambda function that sends an SNS message
 */
exports.handler = (event, context) => {
    let message = "Hello from Lambda!";
    return sendEmail(msg).then((err,data)=>{
        console.log ("We are in the callback!");
        if (err) {
            console.log('Error sending a message', err);
            context.fail(err);
        } else {
            console.log('Sent message:', data.MessageId);
            context.succeed("Done!");
        }      
    });
};
...
...

4. Add an SNS Role

You will need to add a policy for this Lambda to be able to properly send SNS messages. We need to make a small update to the CloudFormation template to make use of this. If you did not use AWS SAM to generate the project, you can simply update the assigned role using the AWS Console.

  snsLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: src/handlers/index.handler
      Runtime: nodejs12.x
      MemorySize: 128
      Timeout: 100
      Description: A Lambda function sends an SNS notification.
      Policies:
        # Give Lambda basic execution Permission to the helloFromLambda
        - AWSLambdaBasicExecutionRole
        # This is the new policy
        - AmazonSNSFullAccess

TLDR - Here is a link to my Github with the given code.

🐦 Follow me on Twitter if you would like to see more content like this! 🐦

Conclusion

That's it! In a couple of dozen lines of code, you can easily utilize SNS subscriptions to send notifications.

Interested in reading more such articles from Phillip Ninan?

Support the author by donating an amount of your choice.

Recent sponsors
Catalin Pit's photo

Interesting, nice article! Is it possible to send any type of notifications? For example, a notification every time someone replies to your tweet?

I know the example is pointless, but just trying to understand how one can use it. 😊

Show +1 replies
Catalin Pit's photo

Benoît Bouré, go it! Thanks!

I also followed you on Twitter just now.

Phillip Ninan's photo

Catalin Pit thank you for reading!

My use case for this is to be used doing live sporting events. I write software to score different types of sports in realtime. I use AWS Lambda and AWS CloudWatch Event Rules to periodically (CRON) query our database to find potential errors. If there are errors our team is notified immediately. Some of our team members get emails while others prefer SMS.

I have an article on deck to query an RDS database using AWS Lambda. Stay tuned!

Benoît Bouré's photo

Great article Phillip Ninan

I just wanted to bring something to your attention. With the aws-sdk, you can either use the callback function (on the request method) - OR - use .promise() with .then() or await. It seems you have made a mix of moth here. The .promise() method does not take a callback.

Did I miss something?

Phillip Ninan's photo

Benoît Bouré No, you are correct! I forgot to add a .then(). I updated the article and the Github source code. Ironically, the code still executed properly with this error, but the logs were never printed.

Thank you for pointing that out!!