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

问题描述

不确定以前是否有人遇到过这个问题,我有多个网络接口需要附加到 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",private_ip = "x.x.x.x"
        }
    ]
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...