如何在Terraform其他模块中引用count.index生成的子网ID
问题原因
- 你
subnet模块的subnet_id输出用了splat表达式azurerm_subnet.module-spoke-subnet.*.id,返回的是所有子网ID组成的列表(tuple),不是单个字符串 - 你直接把整个列表传给了
subnet_association模块的subnet_id参数,而关联资源azurerm_subnet_route_table_association的subnet_id属性要求传入单个字符串类型的子网ID,因此类型不匹配报错 - 同时你部署了2个子网,需要为每个子网都创建对应的路由表关联,因此关联侧也需要搭配
count循环创建资源
修复步骤
1. 修改subnet_association模块定义(Modules/subnet_association/main.tf)
调整参数类型,给关联资源加上count循环,逐个匹配子网ID:
# 调整参数定义,明确接收子网ID列表 variable "subnet_ids" { type = list(string) description = "需要关联路由表的所有子网ID列表" } variable "route_table_id" { type = string } resource "azurerm_subnet_route_table_association" "module-subnet-association" { count = length(var.subnet_ids) subnet_id = var.subnet_ids[count.index] route_table_id = var.route_table_id }
2. 修改根目录main.tf的模块调用参数
匹配调整后的参数名,传入子网ID列表即可:
module "subnet_association" { source = "../../Modules/subnet_association" subid = var.subid subnet_ids = module.subnet.subnet_id route_table_id = module.route_table.route_table_id }
内容的提问来源于stack exchange,提问作者Azure T
相关产品推荐
相关产品推荐

