Issue with creating multiple vm's using separate modules for NIC and VM (for_each).. please help!

Hi All,

I have two NIC’s creating in one module and got two virtual machines configured in another module …

in the nic module am defining the output of the Nic id and in the Virtual machine module am referring to the nic module output (nic.id) …the issue is, the first virtual machine that gets created gets both the nics assigned and the second vm gets failed due to unavailability of nic.
is there a way to map the individual nic id (output) from nic module to the individual vm in the vm module …
my code below

main.tf

module “nic” {
source = “./Nic”
resource_group_name = module.vnet1mod.rgnameout
location = module.vnet1mod.rglocationout
subnet_id = module.vnet1mod.subnetout
}

module “vnet1mod” {
source = “./vnetmodule”

}

module “virtualmachine” {
source = “./VirtualMachine”
resource_group_name = module.vnet1mod.rgnameout
location = module.vnet1mod.rglocationout
network_interface_ids = module.nic.netinterfaceoutput

}

Nic module

resource “azurerm_network_interface” “nic1” {
for_each = var.vmdetails
name = each.value.vmnic
location = var.location
resource_group_name = var.resource_group_name

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

}

output “netinterfaceoutput” {
value = tomap({ for k, s in azurerm_network_interface.nic1 : k => s.id })
}

vm module

resource “azurerm_windows_virtual_machine” “vm1” {
for_each = var.vmdetails
name = each.value.vmname
resource_group_name = var.resource_group_name
location = var.location
size = var.vmsize
admin_username = var.adminusername
admin_password = var.adminpassword
network_interface_ids = var.network_interface_ids

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

source_image_reference {
publisher = var.publisher
offer = var.offer
sku = var.sku
version = var.Osversion
}

}

variable “vmdetails” {
type = map(any)

default = {
“vm1” = {
vmname = “vmA-1”
vmnic = “vmnicA-1”

}

"vm2" = {
  vmname = "vmA-2"
  vmnic = "vmnicA-2"

  
}

}
}

vnet module

resource “azurerm_virtual_network” “vnet1” {
name = var.vnet_name
location = var.location_name
resource_group_name = var.resourcegroup1_name
address_space = var.vnet_address

}

resource “azurerm_subnet” “subnet1” {
name = var.subnet_name
resource_group_name = var.resourcegroup1_name
virtual_network_name = azurerm_virtual_network.vnet1.name
address_prefixes = var.subnet_address
}

output “rgnameout” {
value = azurerm_virtual_network.vnet1.resource_group_name

}

output “rglocationout” {
value = azurerm_virtual_network.vnet1.location
}

output “subnetout” {
value = azurerm_subnet.subnet1.id

}