如何使用CloudFormation从SNS触发Lambda?
如何使用CloudFormation从SNS触发Lambda?
我们所做的是将 SNS(Simple Notification Service) 指向一个有资格的 Lambda 而不是直接指向 Lambda。基本上,创建一个 Lambda,然后创建一个别名,使用 SNS 将其指向 Lambda 的别名。
当您有新的 Lambda 代码时(您的 CI / CD 可以执行以下操作),更新 Lambda 函数代码,创建新的 Lambda 版本,并将别名重新指向新版本。这样,当 Lambda 代码更新时,SNS 不需要进行任何更改。
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
在使用SNS主题的时候,您不应忘记添加LambdaFunctionPermission
。
以下是Cloud Formation模板中资源部分的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:
...
lambda:
Type: 'AWS::Serverless::Function'
Properties:
Handler:
------
Events:
SNS1:
Type: SNS
Properties:
Topic:
Ref: SNSTopic1
SNSTopic1:
Type: 'AWS::SNS::Topic'
参考资料: https://docs.aws.amazon.com/lambda/latest/dg/serverless_app.html#serverless_app_resources
这篇文章介绍了如何使用AWS Lambda构建无服务器应用程序。无服务器应用程序是指在不需要管理服务器的情况下运行的应用程序,可以根据需要自动扩展和缩小。您可以使用Lambda函数、API网关、DynamoDB等AWS服务来构建无服务器应用程序。