首页 > 解决方案 > CDK - S3 通知导致循环参考错误

问题描述

我想在一个堆栈中创建一个 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.

标签: typescriptamazon-web-servicesamazon-s3amazon-cloudformationaws-cdk

解决方案


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

那个 lamdba 定义在哪里?

你想用 SNS 做什么?

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

继续我的假设,让我向您展示您当前面临的问题: Bucket和Lambda之间的循环依赖(角色)

与 CDK 一起在后台使用的普通 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));
  }
}

让我知道,如果这回答了您的问题或者您是否遇到任何问题。


推荐阅读