将 lambda 目标角色添加到 Cloudformation 中的 AWS Eventbridge 规则失败

Adding lambda target role to AWS Eventbridge rule in Cloudformation fails

我正在尝试创建一个以 Lambda 函数作为目标的 AWS Eventbridge 规则。我可以很好地添加规则和目标,但是当我尝试通过 RoleArn 设置 lambda 权限时,Cloudformation 堆栈部署失败并显示: RoleArn is not supported for target arn:aws:lambda:us-east-1:1234567890:function:contacts-lambda-consume-new-customer. (Service: AmazonCloudWatchEvents; Status Code: 400; Error Code: ValidationException; Request ID: xxxxx-ec5d-45e8-b45d-xxxxxx; Proxy: null)

这是我的 Cloudformation 堆栈代码:

  EventRuleNewCustomer: 
    Type: AWS::Events::Rule
    Properties: 
      Name: new-customer
      EventBusName: myEventBus
      # RoleArn: !Join ["", ["arn:aws:iam::",!Ref "AWS::AccountId", ":role/my-role"] ] #no error but doesn't add the permissions
      Description: "New customer event rule"
      EventPattern: 
        detail-type: 
          - "NewCustomer"
      State: "ENABLED"
      Targets: 
        - 
          Arn: !Join ["", ["arn:aws:lambda:" ,!Ref "AWS::Region", ":", !Ref "AWS::AccountId", ":function:contacts-lambda-consume-new-customer"] ]
          Id: "NewCustomer"
          RoleArn: !Join ["", ["arn:aws:iam::",!Ref "AWS::AccountId", ":role/my-role"] ]

我尝试在规则本身上设置 RoleArn,这在创建堆栈时不会出错,但也不会添加执行 Lambda 的必要权限。

我使用的解决方法是在 AWS Eventbridge 控制台中编辑 lambda 目标。这似乎在幕后做了一些魔术,为 Eventbridge 添加了正确的权限,以便能够执行 lambda

感谢任何想法。

This seems to do some behind the scenes magic to add the correct permissions for Eventbridge to be able to execute the lambda

在 lambda 的情况下,使用 Lambda's resource-based policy 设置权限。

因此您应该在 CloudFormation 中使用 AWS::Lambda::Permission 以允许 EventBridge 调用您的函数,而不是使用 RoleArn.

因此您的权限将如下所示(仅作为示例):

EventBridgeLambdaPermission:
  Type: AWS::Lambda::Permission
  Properties:
    FunctionName: !GetAtt function.Arn
    Action: lambda:InvokeFunction
    Principal: events.amazonaws.com
    SourceArn: !GetAtt EventRuleNewCustomer.Arn