AWS CloudFormation for Lambda and SNS Topic

北城以北 提交于 2019-12-12 06:48:28

问题


I have a cloud formation script which I am using to create a Lambda and SNS Topic.

Here is the yml script for SNS Topic and Lambda creation,

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

Question: Using a !Ref on topic ARN fails,

TopicArn: !Ref SampleSNSTopic

Is this the right way to do it? Or is there some other way where I can use my SNS topic's ARN to create lambda in cloud formation?


回答1:


This is something like the answer to this question:

CloudFormation - Access Parameter from Lambda Code

Essentially you assign the Ref value to an Environment key/value:

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

Then you can access that within the 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);
      };


来源:https://stackoverflow.com/questions/44937508/aws-cloudformation-for-lambda-and-sns-topic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!