AWS CDK路由表关联如何迭代多个子网并解决构造ID重复报错
错误原因
AWS CDK要求同一Stack作用域下所有Construct的第二个入参(逻辑ID)必须全局唯一,你在循环中为每个子网路由表关联资源都使用了固定的publicRTAssoc作为逻辑ID,第二次循环创建资源时就会触发ID重复冲突。
解决方案
将循环中的逻辑ID修改为动态值,保证每个关联资源的ID唯一即可,推荐两种修改方式:
方式1:拼接子网ID生成唯一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 }); });
方式2:拼接循环索引生成唯一ID
如果担心子网ID过长不符合命名规则,可直接用循环索引拼接:
// This will grab the public RT and associate all public subnets to the RT. props.pubSubnetId.forEach((public_subnets, index) => { const publicRTAssoc = new ec2.CfnSubnetRouteTableAssociation(this, `publicRTAssoc-${index}`, { routeTableId: props.pubRouteTableId, subnetId: public_subnets }); });
私有路由表的关联逻辑按照同样规则修改即可,避免使用固定逻辑ID。
内容的提问来源于stack exchange,提问作者Dylan
相关产品推荐
相关产品推荐

