'How to create an EventBridge (CloudWatch Events) rule and add it to a Lambda function as a trigger using CDK?
I'm trying to create an EventBridge (CloudWatch Events) Rule and have that rule added as a trigger to an existing Lambda function.
const notificationFunction = lambda.Function.fromFunctionArn(this,
'DevopsNotificationLambda',
_props.notificationLambdaArn
);
const rule = new Rule(this, `${stackPrefix}-EventRule`, {
eventPattern: {
source: ['aws.codepipeline'],
detailType: ['CodePipeline Pipeline Execution State Change'],
detail: {pipeline: [pipeline.pipelineName]}
},
});
notificationFunction.addPermission(`${stackPrefix}-CloudWatchPermission`, {
principal: new ServicePrincipal('events.amazonaws.com'),
sourceArn: rule.ruleArn
});
rule.addTarget(new LambdaFunction(notificationFunction));
The code creates the EventBridge with the Lambda target correctly, but it doesn't add the trigger to the actual Lambda. I have to manually add the EventBridge to the Lambda through the AWS Web Console.

Seems like it's not enough to add the Lambda as a target to the Event Rule. How should I add the Event Rule as a trigger to the Lambda?
Solution 1:[1]
From Importing existing external resources in the CDK Developer Guide.
Although you can use an imported resource anywhere, you cannot modify the imported resource. For example, calling addToResourcePolicy (Python: add_to_resource_policy) on an imported s3.Bucket does nothing.
You cannot add a trigger to notificationFunction from the CDK stack because notificationFunction is an external resource.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kylevoyto |
