
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 - AmazonSNSFullAccessTLDR - 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.
About the author
I'm a software engineer interested in Cloud technologies and web applications.
Comments
Join the discussionInteresting, 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. 😊
AWS SNS can send messages to many kinds of subscribers: HTTP webhooks, Email, SMS, SQS, Push notification.
In order to trigger it, you can use Lambda like this article shows, or EventBridge. The possibilities are endless.
Benoît Bouré, go it! Thanks!
I also followed you on Twitter just now.
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!
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?
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!!




