问题
An SNS topic has been created to call a subscribed Lambda function which adds a user to a group in Cognito. Sending a message to the topic using the console in the web browser works correctly. The Lambda function is called and the user is added to the group.
The Lambda function below attempts to replace the web console by sending a message to the SNS topic itself, which should end with the user being added to the group. When running the function in the Lambda web console, the function returns with the following message:
Execution result: succeeded(logs)
However the user is not successfully added to the group. Why is the Lambda returning successfully, but the message is not being sent to the SNS topic? Is something misconfigured somewhere?
var AWS = require('aws-sdk');
exports.handler = async (event) => {
AWS.config.update({region: 'ca-central-1'});
var params = {
Message: 'Example',
TopicArn: 'arn:aws:sns:ca-central-1:example:example'
};
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();
publishTextPromise.then(
function(data) {
console.log(`Message ${params.Message} sent to the topic ${params.TopicArn}`);
console.log("MessageID is " + data.MessageId);
}).catch(
function(err) {
console.error(err, err.stack);
});
};
回答1:
The Lambda execution environment might not be waiting for the promise to be returned. Try rewriting your promise code using async/await.
回答2:
To allow the function to send messages to the SNS topic, add a policy to the function's execution role giving the appropriate permission like so:
"Action" : [
"sns:Publish",
],
"Effect" : "Allow",
"Resource" : [
{ "Ref" : "arn:aws:sns:ca-central-1:example:example" }
]
If the lambda function is defined in a CloudFormation template, this is where you would add this.
If the lambda function is created in the AWS console, go to the permissions tab and navigate to the execution role using the link, and add the above permission to it:
来源:https://stackoverflow.com/questions/64657399/how-to-send-sns-topic-a-message-from-node-js-lambda-function