通过Terraform使用For_Each循环创建Azure VM

时间:2020-10-21 16:29:10

标签: azure terraform terraform-provider-azure

我试图通过terrform使用for_each创建多个Azure VM,我能够创建2个NIC卡,但是在zurerm_windows_virtual_machine块中定义NIC ID时,两个VM都在选择相同的NIC卡(最后一个,索引1),结果是仅创建VM,其他VM失败。 (network_interface_ids = azurerm_network_interface.az_nic [*]。id)的逻辑是,第一个虚拟机将选择第一个NIC,第二个将选择第一个NIC。

#---------------为Windows VM创建网络接口---------------

resource "azurerm_network_interface" "az_nic" {
  count               = length(var.vm_names)
  name                = "${var.vm_names[count.index]}_nic"
  location            = var.location
  resource_group_name = data.azurerm_resource_group.Resource_group.name


  ip_configuration {
    name                          = var.vm_names[count.index]
    subnet_id                     = data.azurerm_subnet.subnet.id
    private_ip_address_allocation = "Dynamic"
  }
}

resource "azurerm_windows_virtual_machine" "myvm" {
  for_each              = toset(var.vm_names)
  name                  = each.value
  resource_group_name   = data.azurerm_resource_group.Resource_group.name
  location              = var.location
  size                  = "Standard_D2s_v3"
  admin_username        = "abc"
  admin_password        = "uejehrikch123"
  network_interface_ids = azurerm_network_interface.az_nic[*].id
       
 
  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2016-Datacenter"
    version   = "latest"
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }

1 个答案:

答案 0 :(得分:1)

您可以在count中添加resource "azurerm_windows_virtual_machine"参数,而不必混合使用countfor_each

假设你有

variable "vm_names" {
  default = ["vm1", "vm2"]
}

然后您可以像这样更改资源.tf文件:

resource "azurerm_windows_virtual_machine" "myvm" {
  count                 = length(var.vm_names)
  name                  = element(var.vm_names,count.index)
  resource_group_name   = data.azurerm_resource_group.Resource_group.name
  location              = var.location
  size                  = "Standard_D2s_v3"
  admin_username        = "abc"
  admin_password        = "uejehrikch123"
  network_interface_ids =  [element(azurerm_network_interface.az_nic.*.id, count.index)]
       
 
  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2016-Datacenter"
    version   = "latest"
  }

  os_disk {
    caching              = "ReadWrite"
    storage_account_type = "Standard_LRS"
  }