Last updated: Jan 26, 2024
Reading timeยท2 min
The reason we get the "There is already a Construct with name abc" error in
CDK is because we try to create multiple Constructs with the same id
prop in
the same scope.
export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps) { super(scope, id, props); // ๐ id = avatars-bucket const bucketOne = new s3.Bucket(this, 'avatars-bucket'); // ๐ id = avatars-bucket const bucketTwo = new s3.Bucket(this, 'avatars-bucket'); } }
I defined two S3 buckets in the same scope. Note that the id
prop is the
same for both buckets - avatars-bucket
.
Identifiers in CDK must be unique in the scope they are created in.
IDs in CDK don't have to be globally unique in the entire CDK application,
however, both of the buckets are defined in the scope of the stack and they both
have the same id
.
I'll try to synth
the code from the snippet.
npx aws-cdk synth
In order to solve the error we have to make the id
props we pass to
constructs unique within the same scope.
export class MyCdkStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props: cdk.StackProps) { super(scope, id, props); const bucketOne = new s3.Bucket(this, 'my-bucket'); const bucketTwo = new s3.Bucket(this, 'your-bucket'); } }
If I now run the cdk synth
command my CloudFormation template gets generated
successfully.
You might be receiving the same id
prop as a parameter and passing it on to
multiple constructs at the same scope. The concept is the same, you just have
to pass a different id
parameter to the constructs at the same scope.
You might also be trying to instantiate multiple Stacks with the same id
:
const app = new cdk.App(); new MyCdkStack(app, 'my-cdk-stack'); new MyCdkStack(app, 'my-cdk-stack');
The result is again:
If you want to read more on identifiers in CDK, I've written an article:
You can learn more about the related topics by checking out the following tutorials: