如何使用 CDK 创建 EventBridge (CloudWatch Events) 规则并将其作为触发器添加到 Lambda 函数?

How to create an EventBridge (CloudWatch Events) rule and add it to a Lambda function as a trigger using CDK?

我正在尝试创建 EventBridge (CloudWatch Events) 规则并将该规则作为触发器添加到现有 Lambda 函数。

    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));

该代码使用 Lambda 目标正确创建了 EventBridge,但它没有将触发器添加到实际的 Lambda。我必须通过 AWS Web 控制台手动将 EventBridge 添加到 Lambda。

似乎将 Lambda 作为目标添加到事件规则中还不够。我应该如何将事件规则作为触发器添加到 Lambda?

来自 CDK 开发人员指南中的 Importing existing external resources

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.

您无法从 CDK 堆栈向 notificationFunction 添加触发器,因为 notificationFunction 是外部资源。