Triggering a lambda from SNS using cloud-formation?

可紊 提交于 2021-02-19 06:16:05

问题


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

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