Can you publish a message to an SNS topic using an AWS Lambda function backed by node.js?

Amazon Web-ServicesAws LambdaAmazon Sns

Amazon Web-Services Problem Overview


Can you publish a message to an SNS topic using an AWS Lambda function backed by node.js?

Amazon Web-Services Solutions


Solution 1 - Amazon Web-Services

Yes, you could write a Lambda function that publishes to an SNS topic. The code running in Lambda has access to the full AWS SDK for Java or Javascript, whichever your function is using. You just need to make sure you give the IAM role executing the function access to publish to your topic. In Javascript:

console.log("Loading function");
var AWS = require("aws-sdk");

exports.handler = function(event, context) {
    var eventText = JSON.stringify(event, null, 2);
    console.log("Received event:", eventText);
    var sns = new AWS.SNS();
    var params = {
        Message: eventText, 
        Subject: "Test SNS From Lambda",
        TopicArn: "arn:aws:sns:us-west-2:123456789012:test-topic1"
	};
	sns.publish(params, context.done);
};

It is also possible to handle SNS messages using Lambda functions. You might take a look at the sns-message function blueprint, offered through the Create a Lambda function button on the Lambda console.

Solution 2 - Amazon Web-Services

First, you need to grant your Lambda IAM role permissions to publish to your SNS topic using proper IAM policy.

{
	"Action" : [
		"sns:Publish",
		"sns:Subscribe"
	],
	"Effect" : "Allow",
	"Resource" : [
		{ "Ref" : "<your SNS topic ARN>" }
	]
}

Then you can use following code to SNS publish to your SNS topic from your other Lambda or Node.js code.

var message = {};
var sns = new AWS.SNS();
sns.publish({
	TopicArn: "<your SNS topic ARN>",
	Message: JSON.stringify(message)
}, function(err, data) {
	if(err) {
		console.error('error publishing to SNS');
		context.fail(err);
	} else {
		console.info('message published to SNS');
		context.succeed(null, data);
	}
});

Solution 3 - Amazon Web-Services

To send the SNS response into lambda use this:

await sns.publish({
    Message: snsPayload,
    MessageStructure: 'json',
    TargetArn: endPointArn}).promise()

(Answered here)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGary SharpeView Question on Stackoverflow
Solution 1 - Amazon Web-ServicesJamesView Answer on Stackoverflow
Solution 2 - Amazon Web-ServicesadamkonradView Answer on Stackoverflow
Solution 3 - Amazon Web-ServicesguneetgstarView Answer on Stackoverflow