You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Terraform中嵌套对象映射编写正确的变量类型

Terraform虚拟机变量类型匹配问题

目标配置示例

用户期望的virtual_machines输入结构如下:

virtual_machines = {
  nodes = {
    app1_node1 = {
      "vm_name" = "app"
      "vm_num"  = "1"
      networks = {
        nic1 = {
          "nic_name" = "app-1"
          "subnet"   = "****"
        },
      }
    },
    service1_node1 = {
      "vm_name" = "service"
      "vm_num"  = "1"
      networks = {
        nic1 = {
          "nic_name" = "service-1"
          "subnet"   = "****"
        },
      }
    },
    db1_node1 = {
      "vm_name" = "db"
      "vm_num"  = "1"
      "as_name" = "app-avset"

      networks = {
        nic1 = {
          "nic_name" = "db-1-1"
          "subnet"   = "****"
        },
        nic2 = {
          "nic_name" = "db-1-2"
          "subnet"   = "/subscriptions/************/resourceGroups/pluto/providers/Microsoft.Network/virtualNetworks/pluto-infra/subnets/db-subnet"
        }
      }
    },
    db2_node2 = {
      "vm_name" = "db"
      "vm_num"  = "2"
      "as_name" = "app-avset"
      networks = {
        nic1 = {
          "nic_name" = "db-2-1"
          "subnet"   = "****"
        },
        nic2 = {
          "nic_name" = "db-2-2"
          "subnet"   = "/subscriptions/************/resourceGroups/pluto/providers/Microsoft.Network/virtualNetworks/pluto-infra/subnets/db-subnet"
        },
      }
    },
  }
}

错误的变量定义

用户最初编写的变量类型定义无法匹配上述结构:

variable "virtual_machines" {
  type = map(object({
    nodes = map(object({
      vm_name = string
      vm_num  = string
      as_name = optional(string)
      networks = map(object({
        nic_name = string
        subnet   = string
      }))
    }))
  }))
  default = {}
}

报错信息

执行时出现类型不匹配错误:

│ Error: Invalid value for input variable
│
│   on main.tf line 4, in module "virtualmachine":
│    4:   virtual_machines        = var.virtual_machines
│
│ The given value is not suitable for module.virtualmachine.var.virtual_machines declared at virtualmachine\variables.tf:6,1-28: element "nodes": attribute
│ "nodes" is required.

正确的变量类型定义

问题根源是原定义将virtual_machines声明为map类型,但实际输入是一个包含nodes键的单一对象。修正后的变量定义如下:

variable "virtual_machines" {
  type = object({
    nodes = optional(map(object({
      vm_name = string
      vm_num  = string
      as_name = optional(string)
      networks = map(object({
        nic_name = string
        subnet   = string
      }))
    })), {})
  })
  default = {}
}

关键修正点:

  • 将外层的map(object({...}))改为object({...}),匹配输入的单一对象结构
  • 对nodes属性标记为optional(...)并设置空map为默认值,支持无需创建虚拟机的场景
  • 保留as_name的可选性,适配部分节点无该属性的情况
  • 外层默认值设为空对象,完全支持空输入场景

内容的提问来源于stack exchange,提问作者Madhumitha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:43:12