Solving There is Already a Construct with Name Error in CDK

avatar

Borislav Hadzhiev

Sat Apr 17 20212 min read

banner

Photo by Isac Ciobota

To solve the "There is Already a Construct with Name" error we have to only provide unique IDs to constructs in the same scope.

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 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee