创建绑定NIC的两台VM时遭遇Terraform属性类型错误求助
问题解决:Terraform Azure VM关联NIC时的类型错误
错误原因
- 类型不匹配:
network_interface_ids属性要求传入字符串列表(list(string)),但你当前用format()返回的是单个字符串,不符合类型要求。 - 资源引用错误:关联VM和NIC需要用NIC的资源ID,而不是自定义的名称字符串。
- 属性赋值错误:
resource_group_name和location参数搞反了,会导致资源部署位置错误。 - 冗余变量传递:模块调用时传入的
nics变量完全多余,因为compute模块内已经自行创建了NIC资源。
修正后的代码
1. 修正compute模块内的main.tf
resource "azurerm_linux_virtual_machine" "web_linuxvm" { count = var.vm-count name = "linuxvm-${count.index}" resource_group_name = var.resource_group_name # 修正:传入资源组名称 location = var.location # 修正:传入区域位置 size = "Standard_DS1_v2" admin_username = "azureuser" # 修正:用列表包裹NIC的ID,直接引用模块内创建的NIC资源 network_interface_ids = [azurerm_network_interface.network-interface[count.index].id] admin_ssh_key { username = "azureuser" public_key = file("${path.module}/ssh-keys/vm-ssh.pub") } os_disk { caching = "ReadWrite" storage_account_type = "Standard_LRS" } source_image_reference { publisher = "RedHat" offer = "RHEL" sku = "83-gen2" version = "latest" } custom_data = base64encode(local.vm_custom_data) } resource "azurerm_network_interface" "network-interface" { count = var.vm-count name = "nic-${count.index}" location = var.location resource_group_name = var.resource_group_name ip_configuration { name = "vm-${count.index}" subnet_id = azurerm_subnet.subnet.id private_ip_address_allocation = "Dynamic" } }
2. 修正模块调用代码
去掉冗余的nics变量传递:
module "compute" { source = "../module/compute" vm-count = var.vm-count resource_group_name = azurerm_resource_group.rg.name location = var.region }
关键说明
network_interface_ids = [azurerm_network_interface.network-interface[count.index].id]:用列表语法包裹NIC的ID,满足属性的类型要求,同时直接引用模块内创建的NIC资源ID,确保关联正确。- 修正
resource_group_name和location的赋值,避免资源部署到错误的位置。 - 移除不必要的
nics变量,因为模块内已经通过count创建了对应数量的NIC,直接引用即可。
内容的提问来源于stack exchange,提问作者Pallab
相关产品推荐
相关产品推荐

