dheeraj
dheeraj

Reputation: 55

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

I have imported an S3 bucket using below

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

now I am trying to add lifecycle rule,

if the bucket is created in the stack I know we have 2 options like below

option 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',
});

Option 2:

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

what I want is import an existing bucket and add transition rules to the bucket (similar to option 2)

Thanks !

Upvotes: 4

Views: 10132

Answers (1)

Balu Vyamajala
Balu Vyamajala

Reputation: 10333

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.

Here are some steps we can do without using a custom resource.

  • Create an empty cdk project with just 1 resource create s3 bucket (not import existing bucket) with same configuration as your current S3 bucket.
  • cdk synth and generate Cloud Formation Template.
  • Use cloudformation import process documented here and example for Here for DynamoDB.

Upvotes: 3

Related Questions