- Newest
- Most votes
- Most comments
The error you're encountering is likely due to S3 bucket names that already exist, as S3 bucket names must be globally unique across all AWS accounts. When creating multiple S3 buckets in a single CDK stack, you need to ensure each bucket has a unique name.
Here's the correct approach to create multiple S3 buckets in a single CDK stack:
import * as cdk from 'aws-cdk-lib'; import * as s3 from 'aws-cdk-lib/aws-s3'; import { Construct } from 'constructs'; export class MyS3Stack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // Create multiple S3 buckets with different construct IDs const backendAppBucket = new s3.Bucket(this, 'BackendAppBucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, // Let CDK auto-generate unique bucket names, or specify unique names }); const backendQueueBucket = new s3.Bucket(this, 'BackendQueueBucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); const backendCostBucket = new s3.Bucket(this, 'BackendCostBucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); const backendDataBucket = new s3.Bucket(this, 'BackendDataBucket', { removalPolicy: cdk.RemovalPolicy.DESTROY, }); // Output bucket names for reference new cdk.CfnOutput(this, 'BackendAppBucketName', { value: backendAppBucket.bucketName, description: 'Backend App Bucket Name', }); new cdk.CfnOutput(this, 'BackendQueueBucketName', { value: backendQueueBucket.bucketName, description: 'Backend Queue Bucket Name', }); } }
Key points to resolve your error:
-
Ensure unique construct IDs: Each bucket must have a unique construct ID (the second parameter in
new s3.Bucket()) -
Let CDK auto-generate names: By not specifying a
bucketNameproperty, CDK will automatically generate globally unique bucket names -
If previous buckets exist: You need to manually delete any conflicting S3 buckets from the AWS console before redeploying
-
Use RemovalPolicy.DESTROY: This ensures buckets can be deleted when the stack is destroyed (useful for development environments)
The error you're seeing indicates that buckets with those names already exist in your AWS account or globally. Either let CDK auto-generate the names or ensure your custom names are truly unique.
Sources
aws-cdk-lib.aws_s3 module · AWS CDK
Problem: "S3 bucket name already exists" error - Landing Zone Accelerator on AWS
'AWS CDK deploy' action YAML - Amazon CodeCatalyst
