如何将生命周期策略添加到 AWS CDK Typescript 中的现有 S3 存储桶

How to add a lifecycle policy to an existing S3 bucket in AWS CDK Typescript

我已经使用下面的方法导入了一个 S3 存储桶

const importbucket = s3.Bucket.fromBucketAttributes(this, 'ImportedBucket', {
  bucketArn: 'arn:aws:s3:::BUCKETNAME'
});

现在我正在尝试添加生命周期规则,

如果存储桶是在堆栈中创建的,我知道我们有 2 个选项,如下所示

选项 1:

const nitinbucket = new s3.Bucket(this, 'bucket', {
  bucketName: 'sdasbktjsdhfksajdkdjlkas',
  removalPolicy: RemovalPolicy.DESTROY,
  versioned: false, 
});

nitinbucket.addLifecycleRule({
  abortIncompleteMultipartUploadAfter: Duration.days(7),
  enabled: true,
  expiration: Duration.days(75),
  id: 'rule',
});

选项 2:

const myBucket = new s3.Bucket(this, 'BuckyMcBucketface', {
  lifecycleRules: [
      {
          transitions: [
              {
                  storageClass: s3.StorageClass.INFREQUENT_ACCESS,
                  transitionAfter: cdk.Duration.days(30),
              },
          ],
      },
  ],
});

我想要的是导入现有的桶并向桶添加转换规则(类似于选项 2)

谢谢!

life cycle configuration is part of same cloudformation resource which creates S3 Bucket. Making changes to a resource that was created manually outside cloudformation/CDK is not supported unless we use a custom resource.

以下是我们可以在不使用自定义资源的情况下执行的一些步骤。

  • 创建一个只有 1 个资源的空 cdk 项目,创建与当前 S3 存储桶具有相同配置的 s3 存储桶(不导入现有存储桶)。
  • cdk synth 并生成云形成模板。
  • 使用记录的 cloudformation 导入过程 here 和示例 对于 DynamoDB。