Send an SNS notification using AWS Lambda

Send an SNS notification using AWS Lambda

ยท

3 min read

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.

Did you find this article valuable?

Support Phillip Ninan by becoming a sponsor. Any amount is appreciated!