【问题标题】:CDK - S3 notification causing cyclic reference errorCDK - S3 通知导致循环参考错误
【发布时间】:2020-11-01 21:34:54
【问题描述】:

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

【问题讨论】:

    标签: typescript amazon-web-services amazon-s3 amazon-cloudformation aws-cdk


    【解决方案1】:

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

    Lamdba 定义在哪里?

    你想用 SNS 做什么?

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

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

    在 CDK 底层使用的普通 Cloud Formation 无法自行解决此问题,您需要创建自定义资源来解决此问题。 不过 AWS CDK 可以解决这个问题,因为它会自动创建所需的自定义资源和正确的创建顺序!

    不要使用s3n.SnsDestination,而是使用 Lambda 目标,如 sn-p 中所示。您可以轻松地将所有内容提取到单独的堆栈中,因为问题不应该在于分离堆栈。

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

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

    【讨论】:

    • 认为这是由于 CDK 代码中的错误在此处查看问题github.com/aws/aws-cdk/issues/11245 似乎可以通过 Lambda 目标解决,因为我可以看到他们在这里解决了类似的错误github.com/aws/aws-cdk/issues/5760
    • 无论如何我都会接受这个答案,因为它是目前唯一可行的解​​决方案,并且有据可查。
    猜你喜欢
    • 2020-12-11
    • 1970-01-01
    • 2014-06-24
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多