使用Terraform模块为路由表添加额外路由运行成功但未生效
问题根因
- 模块内路由资源的创建条件判断错误
你在module.tf中定义aws_route资源的count参数时,判断逻辑为length(var.ExtraRoutes.publicRoute) > 1时才创建路由,但你实际传入的publicRoute/privateRoute每个都只有1个条目,判断条件不成立,count最终为0,路由资源根本不会被创建。 - 主配置中模块调用的索引逻辑错误
顶层ExtraRoutes变量是长度为2的列表,你将模块的count设为length(var.ExtraRoutes)(值为2),同时用count.index + 1取值:
- 当
count.index = 1时,索引值为2,超出列表有效索引范围(仅0、1),会触发索引越界错误 - 如果你仅需要使用列表的第二个条目(索引为1),不需要给模块设置count=2循环调用
- 模块变量类型不匹配
module_var.tf中将ExtraRoutes定义为通用map类型,和实际传入的object结构存在隐式转换,可能引发不可预期的类型问题。
修复方案
第一步:修改module.tf的count判断逻辑
将路由创建的长度判断从>1改为>=1,匹配你单条路由的使用场景:
resource "aws_route" "public_routes" { count = length(var.ExtraRoutes.publicRoute) >= 1 ? length(var.ExtraRoutes.publicRoute) : 0 route_table_id = aws_route_table.VPCPublicSubnetRouteTable[0].id destination_cidr_block = length(regexall("^[0-9].*.[0-9].*",var.ExtraRoutes.publicRoute[count.index].destination)) != 0 ? var.ExtraRoutes.publicRoute[count.index].destination : null gateway_id = length(regexall("^igw-.*",var.ExtraRoutes.publicRoute[count.index].target)) != 0 ? var.ExtraRoutes.publicRoute[count.index].target : null } resource "aws_route" "private_routes" { count = length(var.ExtraRoutes.privateRoute) >= 1 ? length(var.ExtraRoutes.privateRoute) : 0 route_table_id = aws_route_table.VPCPrivateSubnetRouteTable[0].id destination_cidr_block = length(regexall("^[0-9].*.[0-9].*",var.ExtraRoutes.privateRoute[count.index].destination)) != 0 ? var.ExtraRoutes.privateRoute[count.index].destination : null gateway_id = length(regexall("^igw-.*",var.ExtraRoutes.privateRoute[count.index].target)) != 0 ? var.ExtraRoutes.privateRoute[count.index].target : null }
第二步:修正main.tf的模块调用逻辑
如果你只需要使用ExtraRoutes的第二个条目,去掉循环调用,直接指定索引即可:
module "ExtraVPCs" { source = "./modules/VPC" ExtraRoutes = { publicRoute = var.ExtraRoutes[1].publicRoute privateRoute = var.ExtraRoutes[1].privateRoute } }
如果确实需要循环调用所有除第一个外的条目,将count改为length(var.ExtraRoutes) -1,对应索引调整为count.index +1:
module "ExtraVPCs" { source = "./modules/VPC" count = length(var.ExtraRoutes) - 1 ExtraRoutes = { publicRoute = var.ExtraRoutes[count.index + 1].publicRoute privateRoute = var.ExtraRoutes[count.index + 1].privateRoute } }
第三步:修正module_var.tf的变量类型
将变量类型改为和传入结构匹配的object类型,避免隐式转换:
variable "ExtraRoutes" { type = object({ publicRoute = list(object({ destination = string target = string })) privateRoute = list(object({ destination = string target = string })) }) default = { publicRoute = [] privateRoute = [] } }
修改完成后执行terraform plan确认资源创建计划符合预期,再执行terraform apply即可正常添加路由。
内容的提问来源于stack exchange,提问作者Maya Ray
相关产品推荐
相关产品推荐

