如何通过Node.js Lambda函数向SNS主题发送消息 [英] How to send SNS topic a message from Node.js Lambda function

查看:94
本文介绍了如何通过Node.js Lambda函数向SNS主题发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已创建一个SNS主题以调用已订阅的Lambda函数,该函数将用户添加到Cognito中的组.使用Web浏览器中的控制台将消息发送到主题可以正常工作.调用Lambda函数,并将用户添加到组中.

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.

下面的Lambda函数尝试通过向SNS主题本身发送消息来替换Web控制台,该消息应以将用户添加到组中为结尾.在Lambda Web控制台中运行该函数时,该函数返回并显示以下消息:

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)

但是,没有将用户成功添加到组中.为什么Lambda成功返回,但消息没有发送到SNS主题?在某处配置不正确吗?

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);
  });
};

推荐答案

要允许该函数将消息发送到SNS主题,请向该函数的执行角色添加一个策略,并赋予相应的权限,如下所示:

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" }
    ]

如果在CloudFormation模板中定义了lambda函数,则可以在其中添加此函数.

If the lambda function is defined in a CloudFormation template, this is where you would add this.

如果在AWS控制台中创建了lambda函数,请转到权限选项卡并使用链接导航至执行角色,然后向其添加以上权限:

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:

这篇关于如何通过Node.js Lambda函数向SNS主题发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆