CDK - S3 通知导致循环引用错误

CDK - S3 notification causing cyclic reference error

我想在一个堆栈中创建一个 S3 存储桶,将其传递到另一个堆栈,然后使用它在 sns 或 sqs 上创建通知。这是分解代码的示例。

堆栈 1

export class BucketStack extends BaseStack {

  public readonly mynBucket: Bucket;


  constructor(scope: App, id: string, props?: StackProps) {
    const properties: StackProps = {
      env: {
        region: StackConfiguration.region,
      },
    };
    super(scope, id, properties);
    this.myBucket = this.createMyBucket();
  }


  private createMyBucket() {
   // create and return bucket
}

堆栈 2

import * as s3n from '@aws-cdk/aws-s3-notifications';

export class ServiceStack extends BaseStack {
  constructor(scope: App, id: string, myBucket: Bucket) {
    const properties: StackProps = {
      env: {
        region: StackConfiguration.region,
      },
    };

    super(scope, id, properties);

    const topic = new Topic(this, 'Topic');
  
    myBucket.addEventNotification(EventType.OBJECT_CREATED_PUT, new s3n.SnsDestination(topic));

错误是 Error: 'my-bucket-stack' depends on 'my-service-stack' (Depends on Lambda resources., Depends on resources.). Adding this dependency (my-service-stack -> my-bucket-stack/myBucket/Resource.Arn) would create a cyclic reference.

错误消息表明,您使用的是 Lambda。

Lamdba 定义在哪里?

你想用 SNS 做什么?

我假设您想应用模式 (S3 PUT -> Notification -> Lambda),因为您没有 post 完整代码(包括 Lambda)本身。

继续我的假设,让我向您展示您目前面临的问题:

在 CDK 的引擎盖下使用的 Plain Cloud Formation 本身无法解决这个问题,您需要创建一个自定义资源来解决这个问题。 AWS CDK 可以解决这个问题,因为它会自动创建所需的自定义资源和正确的创建顺序!

不使用 s3n.SnsDestination,而是使用代码段中所示的 Lambda 目标。您可以轻松地将所有内容提取到单独的堆栈中,因为问题不应该出在单独的堆栈上。

export class TestStack extends Stack {
  constructor(scope: cdk.Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const bucket = new Bucket(this, "your-bucket-construct-id",{
       // ...
    });

     // Lambda
    const lambda = new Function(this, 'the-triggered-lambda', {
      code: Code.asset(path.join(__dirname,  '../src/your-lambda-folder')),
      handler: 'index.handler',
      runtime: Runtime.NODEJS_12_X,
    });

    // S3 -> Lambda
    bucket.addEventNotification(EventType.OBJECT_CREATED_PUT, new LambdaDestination(lambda));
  }
}

如果这能回答您的问题或您遇到任何问题,请告诉我。