简体   繁体   中英

AWS CloudFormation for Lambda and SNS Topic

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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