Search code examples
amazon-web-servicesaws-lambdaamazon-iamaws-cdkaws-event-bridge

How to create a role in CDK that will allow a Lamda to create an EventBridge target


In my CDK code, I've created a Lambda function that I want to create an EventBridge target. When creating an EventBridge target in the Lambda, I need to pass a RoleArn. I've attempted to create this role and pass the ARN to the Lambda function.

When the Lambda runs, I get the following error:

ValidationException: RoleArn is not supported for target arn:aws:lambda:eu-central-...

I'm creating the rule like so:

const actionFunctionRole = new iam.Role(this, `ActionServiceRole`, {
  assumedBy: new iam.ServicePrincipal('events.amazonaws.com'),
})

actionFunctionRole.addToPolicy(
  new iam.PolicyStatement({
    resources: ['*'],
    actions: ['events:*', 'lambda:*'],
  })
)

In the Lambda function, I'm using the role ARN like so:

await eventBridge
  .putTargets({
    Rule: `USER_EVENT_${images.new.userId.S}_${images.new.eventId.S}`,
    Targets: [
      {
        Arn: actionFunctionArn,
        Id: `USER_EVENT_TARGET_${images.new.userId.S}_${images.new.eventId.S}`,
        Input: '{"a": 123, "b": "YES"}',
        RoleArn: actionFunctionRoleArn,
      },
    ],
  })
  .promise()

What is wrong with my role definition that is making it fail within the Lambda?


Solution

  • For lambda as target you can't use IAM role. Instead you must specify resource-based policy for your lambda function.

    In other words, you have to set your function's resource-based policy (not execution role, these are different), to allow EB to invoke it.