问题
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