For_each vm and network_interface

Hi all!!!

I want to create a module for creating virtual machine using for_each looping.

I have a map like this:

Virtual machines

locals {
vm_flat = flatten([
for s in var.virtual_machines : [
for n in range(s.count) : {
name = s.name
size = s.size
username = s.username
password = s.password
index = n
}
]
])
}

virtual_machines = [

{
  name     = "central"
  size     = "Standard_F2"
  username = "xxxxx"
  password = "xxxx"
  count    =  1

  
},

{
  name     = "consumer"
  size     = "Standard_F8s"
  username = "admin"
  password = "xxxxx"
  count    =  1
  
},

]

So this is my module:

resource “azurerm_network_interface” “nic” {

count = length(var.virtual_machines)
name = “nic-${count.index}”
location = var.location
resource_group_name = var.resource_group.name
tags = var.names.tags

ip_configuration {
name = “internal”
subnet_id = var.subnet_id
private_ip_address_allocation = “Dynamic”
}
}

locals {
nics = list([for o in azurerm_network_interface.nic : { id = o.id, name = o.name}])
}

resource “azurerm_windows_virtual_machine” “vm” {
for_each = { for s in var.virtual_machines : format("%s%02d", s.name, s.index) => s }

name = each.value.name

location = var.location
resource_group_name = var.resource_group.name
tags = var.names.tags

size = each.value.size
admin_username = each.value.username
admin_password = each.value.password
network_interface_ids = “”

os_disk {
caching = “ReadWrite”
storage_account_type = “Standard_LRS”
}

source_image_reference {
publisher = “MicrosoftWindowsServer”
offer = “WindowsServer”
sku = “2016-Datacenter”
version = “latest”
}
}

The problem is that I don’t know how to build a map for join the network_interface created in the first step with the virtual machines. When I try to use something like this:

network_interface_ids = [
azurerm_network_interface.nic.*id
]

Each interface is joined to each virtual machine and I got an error because I cannot use the same network_interface in all virtual_machines. I need assign only and different one network_interface for virtual machines .

I would like to use for_each instead of count for creating virtual machines.

Can anybody help me please?