Home > Net >  "Bucket Already Exists" error when re-deploying CDK
"Bucket Already Exists" error when re-deploying CDK

Time:01-30

I was working on some changes to some CDK code in my AWS account and I made a typo (lack of sleep does some crazy things) in the bucket name (the correct name is something like mybucket-alpha) so it created a new bucket (mybucket-alpha-alpha). I rolled back the change but now I get a "Bucket with name mybucket-alpha already exists" error when I deploy. It seems that the old mybucket-alpha is no longer in the part of my CDK stack, so I get this error because CDK is trying to recreate the bucket. Is there a quick way to reimport this bucket into my stack? I can't delete it since it contains a ton of important data

CodePudding user response:

there is a way to import existing resources into you CDK Stack.

In case of S3 Bucket you can use the Bucket.fromBucketArn() method. You can find it in the documentation as well: https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_s3.Bucket.html#static-fromwbrbucketwbrarnscope-id-bucketarn

Quick example:

const myBucket = Bucket.fromBucketArn(this, 'MyBucket', myBucketArnParam.stringValue);

CodePudding user response:

Here is a thorough explanation of how to import an existing bucket into a cdk stack: https://medium.com/@visya/how-to-import-existing-aws-resources-into-cdk-stack-f1cea491e9

In case the link breaks, the basic steps are...

  1. Add an S3 Bucket to your stack and run cdk synth to generate a template.
  2. In the AWS Console, navigate to the stack to which you wish to add the bucket, choose Stack Actons -> Import resources into stack.
  3. Follow the prompts to upload the template you got via synth
  4. Choose the bucket resource and notice it will pick up the cdk generated id from your template
  5. Complete the import process and then verify the bucket is listed in the stack resources and there is no drift detected.

After importing the bucket into the stack you can managed it via you cdk app/stack.

  • Related