分配给单个虚拟机的多个网络接口的 Terraform azure 输出

Terraform azure output of multiple network interfaces assigning to a single vm

不确定以前是否有人遇到过这个问题,我有多个网络接口需要附加到 Azure 中的虚拟机,我将网络接口详细信息作为地图传递。我需要使用网络接口的输出并将其应用于 vm 资源中的 network_interface_ids。我当前分配 network_interface_ids 的代码似乎没有从 azurerm_network_interface 的输出中获取网络接口 ID。这是我拥有的代码的简短快照:

 resource "azurerm_network_interface" "vmNic" {
  for_each = var.network_interfaces

  name                = each.value.name
  resource_group_name = var.resource_group_name
  location            = var.resource_group_location

  ip_configuration {
    name                          = "${each.value.name}-ip"
    subnet_id                     = each.value.subnet_id
    private_ip_address_allocation = "Static"
    private_ip_address            = each.value.private_ip
  }  
}

resource "azurerm_virtual_machine" "vm" {   
  count = length(azurerm_network_interface.vmNic)
  name                = var.vm_name
  location            = var.resource_group_location
  resource_group_name = var.resource_group_name
  network_interface_ids = try(azurerm_network_interface.vmNic.*.id[count.index], null)

知道我在分配 network_interface_ids 时做错了什么吗?

您似乎想创建多个 NIC 并将它们附加到单个 VM,变量 network_interfaces 看起来像一个包含对象元素的列表。所以如果我是对的。您可以这样更改代码:

resource "azurerm_network_interface" "vmNic" {
  count               = length(var.network_interfaces)

  name                = element(var.network_interfaces, count.index)["name"]
  resource_group_name = var.resource_group_name
  location            = var.resource_group_location

  ip_configuration {
    name                          = "${element(var.network_interfaces, count.index)["name"]}-ip"
    subnet_id                     = element(var.network_interfaces, count.index)["subnet_id"]
    private_ip_address_allocation = "Static"
    private_ip_address            = element(var.network_interfaces, count.index)["private_ip"]
  }  
}

resource "azurerm_virtual_machine" "vm" {   
  count = length(azurerm_network_interface.vmNic)
  name                = var.vm_name
  location            = var.resource_group_location
  resource_group_name = var.resource_group_name
  network_interface_ids = azurerm_network_interface.vmNic.*.id

此处的变量network_interfaces如下所示:

variable "network_interfaces" {
    default = [
        {
            name = "test1",
            subnet_id = "xxxxxx",
            private_ip = "x.x.x.x"
        },
        {
            name = "test2",
            subnet_id = "xxxxxx",
            private_ip = "x.x.x.x"
        }
    ]
}