Solving There is Already a Construct with Name Error in CDK

avatar
Borislav Hadzhiev

Last updated: Jan 26, 2024
2 min

banner

# There is Already a Construct with Name Error in AWS CDK

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.

shell
npx aws-cdk synth
There is already a Construct with name 'avatars-bucket' in MyCdkStack

already construct name

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.

# Other causes for There is already a Construct Error

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:

Error: There is already a Construct with name 'my-cdk-stack' in App

If you want to read more on identifiers in CDK, I've written an article:

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev