适用于Lambda和SNS主题的AWS CloudFormation

时间:2017-07-05 23:27:31

标签: amazon-web-services aws-lambda aws-sdk amazon-cloudformation amazon-sns

我有一个云形成脚本,我用它来创建Lambda和SNS主题。

以下是SNS主题和Lambda创建的yml脚本,

SampleSNSTopic:
Type: AWS::SNS::Topic
Properties:
  DisplayName: sampleTopic
  TopicName: sampleTopic
SampleLambdaFunction:
Type: AWS::Lambda::Function
DependsOn: SampleSNSTopic
Properties:
  Handler: index.handler
  Description: Sample Lambda function
  FunctionName: TestFunction
  Role: !Ref SomeRole
  Code:
    ZipFile: !Sub |
      var AWS = require("aws-sdk");
      exports.handler = function(event, context) {
          var eventText = JSON.stringify(event, null, 2);
          var sns = new AWS.SNS();
          var params = {
              Message: eventText,
              TopicArn: !Ref SampleSNSTopic
          };
          sns.publish(params, context.done);
      };
  Runtime: nodejs6.10
  Timeout: 300
  MemorySize: 512

问题:使用!参考主题ARN失败,

TopicArn: !Ref SampleSNSTopic

这是正确的方法吗?或者是否有其他方法可以使用我的SNS主题的ARN在云层中创建lambda?

1 个答案:

答案 0 :(得分:1)

这就像这个问题的答案:

CloudFormation - Access Parameter from Lambda Code

基本上,您将Ref值分配给Environment键/值:

Properties:
  Handler: index.handler
  Description: Sample Lambda function
  FunctionName: TestFunction
  Environment:
    Variables:
      SNS_TOPIC_ARN: !Ref SampleSNSTopic

然后你可以在Lambda中访问它:

  Code:
    ZipFile: !Sub |
      var AWS = require("aws-sdk");
      exports.handler = function(event, context) {
          var eventText = JSON.stringify(event, null, 2);
          var sns = new AWS.SNS();
          var params = {
              Message: eventText,
              TopicArn: process.env.SNS_TOPIC_ARN
          };
          sns.publish(params, context.done);
      };