如何从两个不同的 AWS 服务(SQS 和 SNS)调用相同的 Lambda 函数?

How to invoke same Lambda function from two different AWS Services (SQS and SNS)?

以下代码调用 SNS,但我希望 SQS 也调用它。我们可以使用多个 Principal 和 Source Arn 吗?我也试过这个但没有用 -

LambdaPermissionMainSNS:
    Type: AWS::Lambda::Permission
    Properties:
      Action: lambda:InvokeFunction
      FunctionName: !GetAtt LambdaFunctionMain.Arn
      Principal: sns.amazonaws.com
      SourceArn: !Ref SNSTopic
LambdaPermissionMainSQS:
   Type: AWS::Lambda::Permission
   Properties:
     Action: lambda:InvokeFunction
     FunctionName: !GetAtt LambdaFunctionMain.Arn
     Principal: sqs.amazonaws.com
     SourceArn: !Ref SQSQueue

您需要 AWS::Lambda::EventSourceMapping SQS 资源:

SQSEventSource:
  Type: AWS::Lambda::EventSourceMapping
  Properties: 
    BatchSize: 10 # this is the default
    Enabled: true
    EventSourceArn: !Ref SQSQueue
    FunctionName: !GetAtt LambdaFunctionMain.Arn

The AWS::Lambda::EventSourceMapping resource creates a mapping between an event source and an AWS Lambda function. Lambda reads items from the event source and triggers the function.

然后您可以同时拥有 SNS 和 SQS "trigger" Lambda 函数。您必须在函数内实现自己的逻辑来处理不同的事件格式。

另见 Using AWS Lambda with Amazon SQS