Solving There is Already a Construct with Name Error in CDK

avatar

Borislav Hadzhiev

Last updated: Apr 14, 2022

banner

Check out my new book

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'); } }

In the code snippet I've 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 - What is an identifier (id) in AWS CDK.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.