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

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

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

错误是 错误:“my-bucket-stack”依赖于“my-service-stack”(取决于 Lambda 资源。,取决于资源。)。添加此依赖项 (my-service-stack -> my-bucket-stack/myBucket/Resource.Arn) 将创建循环引用。

最佳答案

错误消息表明您使用了 Lambda。

Lamdba 定义在哪里?

您想通过 SNS 做什么?

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

继续我的假设,让我向您展示您当前面临的问题: Circular Dependency between Bucket and Lambda (Role)

Plain Cloud Formation 与 CDK 一起使用,它本身无法解决这个问题,您需要创建一个自定义资源来解决这个问题。 不过,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));
  }
}

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

关于typescript - CDK - S3 通知导致循环引用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64637238/

相关文章:

typescript - 使用类似包的类型定义

amazon-web-services - 如何将 JSON 类型传入 yaml cloudformation 模板

linux - 我应该使用哪个 docker OS 基础镜像?

linux - 在Amazon Linux中创建新服务

ruby-on-rails - Rails4.1 : AWS errors missing region

sql - 更改 Parquet 文件中的列数据类型

web-services - 是否可以批量上传到亚马逊s3?

html - Angular Material 选项卡未突出显示

javascript - 如何使用 CSS 和 html 在容器内动态创建和排列复选框?

javascript - 停止动态创建的音频