简体   繁体   English

如何从 Node.js Lambda 函数向 SNS 主题发送消息

[英]How to send SNS topic a message from Node.js Lambda function

An SNS topic has been created to call a subscribed Lambda function which adds a user to a group in Cognito.已创建 SNS 主题以调用订阅的 Lambda 函数,该函数将用户添加到 Cognito 中的组。 Sending a message to the topic using the console in the web browser works correctly.使用 Web 浏览器中的控制台向主题发送消息可以正常工作。 The Lambda function is called and the user is added to the group.调用 Lambda 函数并将用户添加到组中。

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.下面的 Lambda 函数尝试通过向 SNS 主题本身发送消息来替换 Web 控制台,该消息应以用户被添加到组结束。 When running the function in the Lambda web console, the function returns with the following message:在 Lambda Web 控制台中运行该函数时,该函数返回以下消息:

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?为什么 Lambda 返回成功,但是消息没有发送到 SNS 主题? 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);
  });
};

The Lambda execution environment might not be waiting for the promise to be returned. Lambda 执行环境可能不会等待返回承诺。 Try rewriting your promise code using async/await .尝试使用 async/await 重写您的承诺代码

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:要允许函数向 SNS 主题发送消息,请向函数的执行角色添加一个策略,授予适当的权限,如下所示:

"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.如果 lambda 函数是在 CloudFormation 模板中定义的,您可以在此处添加它。

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:如果 lambda 函数是在 AWS 控制台中创建的,请转到权限选项卡并使用链接导航到执行角色,并向其添加上述权限:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM