Terraform引用带count的子网模块创建AKS集群时类型报错求助
问题解决:Terraform AKS子网ID类型不匹配错误
问题场景
通过Terraform模块创建3个AKS子网(测试/预发布/生产),模块调用代码:
# AKS Subnet - Test / Staging / Production module "aks_vpn_subnets" { source = "./modules/subnets" count = 3 azure_subnet_name = var.aks_azure_subnet_names[count.index] rg_name = module.rg.rg_name network_name = module.network.name subnet_address_prefixes = [var.aks_subnet_address_prefixes[count.index]] }
子网模块的main.tf和outputs.tf:
# ./modules/subnets/main.tf resource "azurerm_subnet" "subnet" { name = var.azure_subnet_name resource_group_name = var.rg_name virtual_network_name = var.network_name address_prefixes = var.subnet_address_prefixes } # ./modules/subnets/outputs.tf output "subnet_id" { description = "ID of the subnet" value = azurerm_subnet.subnet.*.id }
尝试创建1个AKS集群并引用第一个子网,代码:
# AKS cluster only create in the first subnet created? module "aks_cluster" { source = "./modules/aks" count = 1 . . . vnet_subnet_id = module.aks_vpn_subnets[count.index].subnet_id . . . depends_on = [ module.aks_vpn_subnets ] }
出现错误:
The given value is not suitable for module.aks_cluster[0].var.vnet_subnet_id declared at
│ modules/aks/variables.tf:47,1-26: string required.
AKS模块的变量定义:
variable "vnet_subnet_id" { type = string description = "The ID of a Subnet where the Kubernetes Node Pool should exist" }
错误原因
- 子网模块的
subnet_id输出使用了azurerm_subnet.subnet.*.id语法,这会返回列表类型(即使每个模块实例只创建1个子网,*会把单个资源的属性包装成列表) - AKS模块的
vnet_subnet_id变量要求的是字符串类型,类型不匹配导致报错
解决方案
1. 修正子网模块的输出
修改./modules/subnets/outputs.tf,去掉*语法,直接返回单个子网ID的字符串:
output "subnet_id" { description = "ID of the subnet" value = azurerm_subnet.subnet.id }
2. 修正AKS模块的子网引用
因为module.aks_vpn_subnets是包含3个实例的列表,直接通过索引[0]引用第一个子网的ID即可。如果只创建1个AKS集群,也可以去掉count = 1让代码更简洁:
保留count的写法
module "aks_cluster" { source = "./modules/aks" count = 1 . . . vnet_subnet_id = module.aks_vpn_subnets[0].subnet_id . . . depends_on = [ module.aks_vpn_subnets ] }
去掉count的简洁写法
module "aks_cluster" { source = "./modules/aks" . . . vnet_subnet_id = module.aks_vpn_subnets[0].subnet_id . . . depends_on = [ module.aks_vpn_subnets ] }
内容的提问来源于stack exchange,提问作者Jananath Banuka
相关产品推荐
相关产品推荐

