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

Terraform中如何正确引用映射类型变量值并创建Azure VNET?

解决Terraform变量类型错误并指定Dev环境地址空间创建VNET

一、修复变量类型错误

报错根源是output.tfvars.json中传入的vnet_address_space是列表类型(用[]包裹),但变量定义要求是map(list(string))(键值对结构)。只需修改output.tfvars.json的格式,使其符合map结构:

"vnet_address_space": {
  "Dev": [
    "xx.xx.0.0/24",
    "xx.xx.0.0/20",
    "xx.xx.0.0/24",
    "xx.xx.0.0/20"
  ]
}

如果需要保留多环境配置,直接补充Stage、Prod的键值对即可,和variables.tf里的default结构保持一致。

二、优化VNET资源配置,正确取用Dev地址空间

方案1:用for_each灵活适配多环境(推荐)

当前代码已通过for_each过滤出Dev环境,但address_space硬编码var.vnet_address_space.Dev不够灵活,改用each.value可直接获取当前环境的地址空间,同时调整资源名称避免重复:

resource "azurerm_virtual_network" "vnet" {
  name                = "${var.hub_vnet_name}-${each.key}"
  location            = azurerm_resource_group.rg[0].location
  resource_group_name = azurerm_resource_group.rg[0].name
  for_each            = { for k, v in var.vnet_address_space : k => v if k == "Dev" }
  address_space       = each.value
  dns_servers         = var.dns_servers
  tags = {
    environment = each.key
    costcentre  = "14500"
  }
  dynamic "ddos_protection_plan" {
    for_each = local.if_ddos_enabled
    content {
      id     = azurerm_network_ddos_protection_plan.ddos[0].id
      enable = false
    }
  }
}

方案2:直接指定Dev环境(无需for_each)

如果仅需创建Dev环境的VNET,可简化代码直接引用var.vnet_address_space["Dev"]:

resource "azurerm_virtual_network" "vnet" {
  name                = var.hub_vnet_name
  location            = azurerm_resource_group.rg[0].location
  resource_group_name = azurerm_resource_group.rg[0].name
  address_space       = var.vnet_address_space["Dev"]
  dns_servers         = var.dns_servers
  tags = {
    environment = "Dev"
    costcentre  = "14500"
  }
  dynamic "ddos_protection_plan" {
    for_each = local.if_ddos_enabled
    content {
      id     = azurerm_network_ddos_protection_plan.ddos[0].id
      enable = false
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:15:32