### variable
variable "vm-subnets" {
type = list(string)
default = ["7.0.1.0/24","7.0.2.0/24","7.0.3.0/24"]
}
### subnet
resource "azurerm_subnet" "task_subnet" {
name = "subnet-${format("%02d",count.index)}"
resource_group_name = azurerm_resource_group.task.name
virtual_network_name = azurerm_virtual_network.task_vnet.name
network_security_group_id = azurerm_network_security_group.task_nsg.id
address_prefix = var.vm-subnets[count.index]
count = length(var.vm-subnets)
}
### NIC
resource "azurerm_network_interface" "vm_nic" {
name = "nic--${format("%02d",count.index)}"
location = var.region
resource_group_name = azurerm_resource_group.task.name
count = var.vm-count
ip_configuration {
name = "${var.resource_prefix}-${format("%02d",count.index)}-ip"
subnet_id = azurerm_subnet.task_subnet.*.id[count.index]
private_ip_address_allocation = "dynamic"
public_ip_address_id = azurerm_public_ip.task_public_ip.*.id[count.index]
}<br>
}
I need to 7 VM into 3 subnet for like subnet-A = 2VMs ,subnet-B=2VMs, subnet-C = 3VMs or randomly `` ERROR: Error: Invalid index
on vm-network.tf line 11, in resource "azurerm_network_interface" "vm_nic": 11: subnet_id = azurerm_subnet.task_subnet.*.id[count.index] |---------------- | azurerm_subnet.task_subnet is tuple with 3 elements | count.index is 4
The given key does not identify an element in this collection value.
Error: Invalid index
on vm-network.tf line 11, in resource "azurerm_network_interface" "vm_nic": 11: subnet_id = azurerm_subnet.task_subnet.*.id[count.index] |---------------- | azurerm_subnet.task_subnet is tuple with 3 elements | count.index is 3
The given key does not identify an element in this collection value.
What modification can be done to resolve it and how can I assign different/random subnet on each vm rather then count loop.
I also try to do it using random_shuffle and set-product function but not get the desired output .. please Help
After 2 days of logical struggle i finally able to find a solution or the questions that I create : USING element function https://www.terraform.io/docs/configuration/functions/element.html
resource "azurerm_network_interface" "vm_nic" {
name = "nic--${format("%02d",count.index)}"
location = var.region
resource_group_name = azurerm_resource_group.task.name
count = var.vm-count
ip_configuration {
name = "${var.resource_prefix}-${format("%02d",count.index)}-ip"
subnet_id = element(azurerm_subnet.task_subnet.*.id, count.index)
private_ip_address_allocation = "dynamic"
public_ip_address_id = azurerm_public_ip.task_public_ip.*.id[count.index]
}
}
subnet_id = element(azurerm_subnet.task_subnet.*.id, count.index)
using element function ["7.0.1.0/24","7.0.2.0/24","7.0.3.0/24"] at vm count.index = 3 it goes back to subnet index = 0 so that how it works and tested it at vm.count = 5, 7 , 10. ✌🏻