Search code examples
amazon-web-servicesaws-lambdaaws-cloudformationamazon-iamaws-event-bridge

Adding lambda target role to AWS Eventbridge rule in Cloudformation fails


I am trying to create an AWS Eventbridge rule with a Lambda function as a target. I can add the rule and target fine but when I try to set the lambda permissions via RoleArn the Cloudformation stack deployment fails with: 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)

Here is my Cloudformation stack code:

  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"] ]

I have tried setting a RoleArn on the rule itself which doesn't give an error when the stack is created but also doesn't add the necessary permissions to execute the Lambda.

The work-around I am using is to edit the lambda target in the AWS Eventbridge console. This seems to do some behind the scenes magic to add the correct permissions for Eventbridge to be able to execute the lambda

Any ideas gratefully appreciated.


Solution

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

    In case of lambda, the permissions are set using Lambda's resource-based policy.

    Thus you should use AWS::Lambda::Permission in CloudFormation to allow EventBridge to invoke your function, rather than using RoleArn.

    So your permissions would be something as the following (just an example):

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