Skip to content

CDK Typescript check if S3 already exists

1

I create an S3 bucket in my stack. After I delete the stack and deploy it again, the deployment fails because the S3 bucket exists. My approach is now to check in the CDK whether the S3 bucket exists and then ping the creation. What is the best way to check whether an S3 bucket exists and then presumably import this bucket.

1 Answer
5

Hello,

Handling conditions in CDK can indeed be tricky. By default, the removalPolicy on resources like S3 buckets is set to RemovalPolicy.RETAIN (see CDK bucket documentation), which keeps the bucket even when the stack is deleted. You might want to set it to RemovalPolicy.DESTROY if you're okay with the bucket being deleted when you remove the stack, so you can redeploy it without issues.

If you want to keep the bucket but still delete and recreate the stack, you could try:

  • Adding a boolean context variable in your CDK stack to control whether the S3 bucket should be created. (context variables)
  • Creating the S3 bucket outside of CDK using the AWS SDK, so it remains independent of your stack lifecycle.
  • You can also use a CfnCondition and a Parameter Store like this guy (link)

Hope it helps :)

EXPERT

answered 2 years ago

EXPERT

reviewed 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.