Azure Linux虚拟机Terraform Map变量配置错误求助
解决Terraform配置Azure Linux虚拟机时的变量类型错误
错误信息
"The given value is not suitable for var.vm_properties declared at variables.tf:147,1-25: element "os_disk": attributes "os_disk" and "source_image" are required."
问题根源
你的vm_properties变量被定义为map(object(...)),意味着它是一个键值对集合,每个值必须是包含os_disk和source_image的完整对象。但在terraform.tfvars中,你直接把os_disk和source_image作为了vm_properties的顶层键,导致Terraform无法识别出符合类型要求的结构。
修复方案
方案一:调整变量类型(适合单VM场景)
如果只需要配置一台虚拟机,修改variables.tf,将map(object(...))改为直接的object(...),让变量直接对应一组VM属性:
variable "vm_properties" { type = object({ os_disk = object({ name = string caching = string storage_account_type = string }) source_image = object({ publisher = string offer = string sku = string version = string }) }) }
修改后,terraform.tfvars和main.tf的代码无需调整,类型即可完全匹配。
方案二:调整tfvars结构(适合多VM批量创建)
如果需要通过该变量批量定义多台虚拟机,保持variables.tf的map(object(...))定义不变,修改terraform.tfvars给每个VM添加独立的顶层键:
vm_properties = { vm1 = { os_disk = { name = "myOsDisk" caching = "ReadWrite" storage_account_type = "Premium_LRS" } source_image = { publisher = "Canonical" offer = "UbuntuServer" sku = "18.04-LTS" version = "latest" } } # 可继续添加vm2、vm3等虚拟机配置 }
同时修改main.tf,用for_each遍历变量批量创建虚拟机:
resource "azurerm_linux_virtual_machine" "example" { for_each = var.vm_properties # 补充虚拟机必填属性(示例值需替换为实际内容) name = each.key resource_group_name = "your-resource-group" location = "your-location" size = "Standard_D2s_v3" admin_username = "adminuser" admin_ssh_key { username = "adminuser" public_key = file("~/.ssh/id_rsa.pub") } os_disk { name = each.value["os_disk"]["name"] caching = each.value["os_disk"]["caching"] storage_account_type = each.value["os_disk"]["storage_account_type"] } source_image_reference { publisher = each.value["source_image"]["publisher"] offer = each.value["source_image"]["offer"] sku = each.value["source_image"]["sku"] version = each.value["source_image"]["version"] } }
内容的提问来源于stack exchange,提问作者Susheel Bhatt
相关产品推荐
相关产品推荐

