Hi,
I’m building a set of VM’s in a module based on the content of a nested object that is provided to the module. I want to be able to build as many VM’s as are passed.
Because the VM and Interfaces are different resources, I’m struggling to get them associated correctly.
An example of my object and how I’m using it to build the Interfaces:
Input object:
machines = {
machine1 = {
size = "standard"
zone = "1"
network = {
nic1 = {
subnet = "subnet_a"
ip_addr = "10.0.0.1"
},
nic2 = {
subnet = "subnet_b"
ip_addr = "192.168.0.8"
}
}
},
machine2 = {
size = "standard"
zone = "1"
network = {
nic1 = {
subnet = "subnet_b"
ip_addr = "10.0.0.1"
}
}
}
Building interfaces:
locals {
nic_config = flatten([
for vm_key, vm in var.machines: [
for nic_key, nic in vm.network :{
vm = vm_key
nic = nic_key
subnet = nic.subnet
ip = nic.ip_address
}
]
])
}
# Lookup subnet ID
data "azurerm_subnet" "vm" {
for_each = {
for nic in local.nic_config : "${nic.vm}.${nic.subnet}" => nic
}
name = each.value.subnet
virtual_network_name = var.vnet
resource_group_name = var.resource_group
}
# Build interfaces for all VM's
resource "azurerm_network_interface" "vm" {
for_each = {
for nic in local.nic_config : "${nic.vm}.${nic.nic}" => nic
}
name = "${each.value.nic}-${each.value.vm}"
location = data.azurerm_resource_group.vm.location
resource_group_name = data.azurerm_resource_group.vm.name
ip_configuration {
name = "conf_${each.value.nic}"
subnet_id = data.azurerm_subnet.vm["${each.value.vm}.${each.value.subnet}"].id
private_ip_address_allocation = "static"
private_ip_address = each.value.ip
}
}
This all works OK but I’m not struggling when I’m building the azure_linux_virtual_machine resource to provide each VM with a list of only the relevant Interface ID’s to the attribute “network_interface_ids” which expects a list of ID’s. I need to somehow grab the ID’s from the interface resources but only those that relate to the specific VM I’m iterating over in my next loop.
Any ideas on how I could change my approach to make this easier?
Thanks