azure 从vNet获取子网ID

owfi6suc  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(185)

我在vNet资源块中创建了一个包含3个子网的虚拟网络,我想知道如何获取子网的ID?我知道是否使用azurerm_subnet分别创建了这些子网,然后在输出中使用它们,但如果子网是与vnet内联创建的,我就不确定了。

主文件.tf

resource "azurerm_virtual_network" "vnet" {
    name = var.vnet.name
    resource_group_name = azurerm_resource_group.rg.id
    location = azurerm_resource_group.rg.id
    address_space = var.vnet.address_space
    dns_servers = var.vnet.dns_servers

    subnet {
        name = var.subnet.key_vault.name
        address_prefix = var.subnet.key_vault.address_prefix
    }

    subnet {
        name = var.subnet.storage_account.name
        address_prefix = var.subnet.storage_account.address_prefix
    }

    subnet {
        name = var.subnet.hostpool1.name
        address_prefix = var.subnet.hostpool1.address_prefix
    }
}

输出.tf

output "subnet_id" {
    value = azurerm_virtual_network.vnet.subnet[*].id
}

错误消息

│ Error: Incorrect attribute value type
│ 
│   on session_hosts/main.tf line 31, in resource "azurerm_network_interface" "avd_nic":
│   31:       subnet_id = var.subnet_id
│     ├────────────────
│     │ var.subnet_id is list of string with 3 elements
│ 
│ Inappropriate value for attribute "subnet_id": string required.
unftdfkk

unftdfkk1#

我尝试重现,以输出子网ID,并得到以下代码的输出:

data "azurerm_resource_group" "example" {
  name     = "xxxxx"  
 //location = "westus2"
}

变量.tf

variable "Subnetlist" {
 type = list
  default = [
    {
      ip      = "10.0.1.0/24"
      name     = "subnet-1"
    },
    {
      ip      = "10.0.2.0/24"
      name     = "subnet-2"
    }
   ]
}

main.tf

resource "azurerm_virtual_network" "vnet" {
    name = "ka-vnetwk"
    resource_group_name = data.azurerm_resource_group.example.name
    location = data.azurerm_resource_group.example.location
    address_space = var.vnet.address_space
    dns_servers = var.vnet.dns_servers
 }
  

resource "azurerm_subnet" "SUBNETS" {
#for_each = var.Subnetlist
 for_each                  ={for idx, val in var.Subnetlist: idx => val}
name = each.value.name
address_prefixes=[each.value.ip]
  resource_group_name  = data.azurerm_resource_group.example.name
  virtual_network_name = azurerm_virtual_network.vnet.name
}

output "subnet_ids" {
   value = values(azurerm_subnet.SUBNETS)[*].id
}

请尝试以下面的方式循环,并对内联子网进行少量更正。

  • 循环遍历列表中的值,如〉value = values(azurerm_subnet.SUBNETS)[*].id
    *一月一日

相关问题