Skip to content

Avoid Adding a Resource Policy to Lambda While Creating EventBridge Rule Using CDK

0

Problem Statement:

I want to create n numbers of EventBridge Rules where the target resource is a Lambda using CDK. While creating the Rule, EventBridge automatically creates a resource policy for lambda that look like this:

{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement": [
    {
      "Sid": "EventBridge-Rule-1",
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-east-1:XXXXXXXXXXXXX:function:SUBMIT-JOB-LAMBDA",
      "Condition": {
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:events:us-east-1:XXXXXXXXXXXXX:rule/src-project-file.py"
        }
      }
    },
    {
      "Sid": "EventBridge-Rule-2",
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "lambda:InvokeFunction",
      "Resource": "arn:aws:lambda:us-east-1:XXXXXXXXXXXXX:function:SUBMIT-JOB-LAMBDA",
      "Condition": {
        "ArnLike": {
          "AWS:SourceArn": "arn:aws:events:us-east-1:XXXXXXXXXXXXX:rule/src-project-file_2.py"
        }
      }
    }
  ]
}

Currently this policy contains information about two Rules. In future, this policy may have more than 100 statements that will voilate the size of resource policy which is 20KB.

In my case the SourceArn will always start with arn:aws:events:us-east-1:XXXXXXXXXXXXX:rule/src. So I can use the * wildcard in SourceArn and reduce this resource policy to a single statement regardless of the number of Rules.


Possible Solutions?:

  1. How can I avoid adding another resource policy to Lambda while creating a Rule via CDK?
  2. Is it possible to remove the resource policy after adding a Rule via CDK only not via SDK?
  3. Any other solution?
asked a year ago426 views
1 Answer
1
Accepted Answer

Finally I resolved this issue using L1 Rule Construct:

// Creating input for target
const input = JSON.stringify({
  job_name: jobAndRuleName,
  file_path: schedule.file_path,
  cpu: this.get_cpu(schedule?.cpu),
  ram: this.get_ram(this.get_cpu(schedule?.cpu)),
  job_queue: 'JOB-QUEUE',
  job_definition: 'JOB-DEFINITION',
});

// Creating rule
new events.CfnRule(this, jobAndRuleName, {
  name: jobAndRuleName,
  description: `This rule is created via CDK for file: ${schedule.file_path}`,
  scheduleExpression: `cron(${schedule.cron})`,
  state: schedule?.disable ? 'DISABLED' : 'ENABLED',
  targets: [
    {
      arn: this.lambda.functionArn,
      id: 'Target-SUBMIT-JOB-LAMBDA',
      input: input,
    },
  ],
});
answered a year ago
EXPERT
reviewed a year ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.