How to iterate over multiple subnets in Route Table Associations with AWS CDK?

0

Issue

I have a list of subnets that I would want to iterate into my public and private route table. Here is an example of my function for my public RT:

// This will grab the public RT and associate all public subnets to the RT.
props.pubSubnetId.forEach((public_subnets) => {
  const publicRTAssoc = new ec2.CfnSubnetRouteTableAssociation(this, "publicRTAssoc", {
    routeTableId: props.pubRouteTableId,
    subnetId: public_subnets
  });
});

I see nothing wrong with my code but when I run cdk synth, I get this error:

Error: There is already a Construct with name 'publicRTAssoc' in CloudformationArchStack [CloudformationArchStack]

I believe the iteration is interfering with the id in my function. Would appreciate any help in solving this problem.

Solution

Your suspicions were correct. You just need to give each route table association construct a unique id:

// This will grab the public RT and associate all public subnets to the RT.
props.pubSubnetId.forEach((public_subnets) => {
  const publicRTAssoc = new ec2.CfnSubnetRouteTableAssociation(this, `publicRTAssoc_${public_subnets}`, {
    routeTableId: props.pubRouteTableId,
    subnetId: public_subnets
  });
});

Answered By – fedonev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More