问题
Triggering a lambda from SNS using cloud-formation?
回答1:
What we do is that we don't point sns to an unqualified lambda, rather we point it to a lambda-alias. Basically, create a lambda, and then create an alias, use sns to point to the lambda-alias.
When you have new code for lambda (your ci/cd can do the following), update lambda function code, create a new lambda version, and repoint your alias to the new version. This way you sns doesn't have to change at all with new lambda code drops.
Resources:
AwsServerlessExpressFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: mylambda
Description: mylambda
Runtime: nodejs8.10
Handler: index.handler
MemorySize: 512
Timeout: 60
Role: !Ref LambdaExecutionRoleArn
AwsServerlessExpressFunctionAlias:
Type: AWS::Lambda::Alias
Properties:
FunctionName: !Ref AwsServerlessExpressFunction
FunctionVersion: '$LATEST'
Name: live
SNSTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: mysnstopic
TopicName: mysnstopic
Subscription:
-
Endpoint: !Ref AwsServerlessExpressFunctionAlias
Protocol: lambda
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
Principal: sns.amazonaws.com
SourceArn: !Ref SNSTopic
FunctionName: !Ref AwsServerlessExpressFunctionAlias
回答2:
You can use events to set up the trigger.
lambda:
Type: 'AWS::Serverless::Function'
Properties:
Handler:
------
Events:
SNS1:
Type: SNS
Properties:
Topic:
Ref: SNSTopic1
SNSTopic1:
Type: 'AWS::SNS::Topic'
Ref: Ref: https://docs.aws.amazon.com/lambda/latest/dg/serverless_app.html#serverless_app_resources
回答3:
You should not forget to add LambdaFunctionPermission
to allow using of the SNS topic.
This is resource part of the Cloud Formation template in yaml:
Resources:
SNSTopic:
Type: AWS::SNS::Topic
Properties:
DisplayName: sns-topic-for-lambda
TopicName: sns-topic-for-lambda
Subscription:
- Endpoint: !GetAtt LambdaFunction.Arn
Protocol: lambda
LambdaFunctionPermission:
Type: AWS::Lambda::Permission
Properties:
Action: lambda:InvokeFunction
FunctionName: !GetAtt LambdaFunction.Arn
Principal: sns.amazonaws.com
LambdaFunction:
Type: AWS::Lambda::Function
Properties:
...
来源:https://stackoverflow.com/questions/48898995/triggering-a-lambda-from-sns-using-cloud-formation