Reputation: 175
I'm creating several VMs through for_each, but only one must have a public IP address. How can I do that? It is understandable how that can be done with count, but what is the way for for_each?
main.tf
variable "vms" {}
resource "azurerm_network_interface" "nics" {
for_each = var.vms
name = each.value.nic
location = var.resource_location
resource_group_name = azurerm_resource_group.rg.name
ip_configuration {
name = "nic-${each.value.name}"
subnet_id = lookup(azurerm_subnet.subnets, each.value["subnet_id"], null)["id"]
private_ip_address_allocation = "Dynamic"
public_ip_address_id = azurerm_public_ip.ext_ip.id (BUT ONLY FOR THE FIRST VM IN LIST)
}
}
terraform.tfvars
vms = {
vm1 = {
disk_size = "30"
name = "vm1"
nic = "nic-1"
sku = "7_9"
subnet_id = "snet1"
username = "centos"
vm_size = "Standard_B1ms"
}
vm2 = {
disk_size = "35"
name = "vm2"
nic = "nic-2"
sku = "7_9"
subnet_id = "snet2"
username = "centos"
vm_size = "Standard_B1ls"
}
}
Upvotes: 1
Views: 840
Reputation: 8116
With the following approach, you can prepare a map of conditional public ip's and then create the resource based on that.
variables.tf
variable "vms" {
type = map(object({
#...
public_ip = optional(bool)
}))
}
locals.tf
pips = { for k, vm in var.vms : k => {
# add required attributes to generate public ip resource
} if vm.public_ip == true
}
main.tf
resource "azurerm_public_ip" "public_ip" {
for_each = local.pips
# ...
}
resource "azurerm_network_interface" "nics" {
for_each = var.vms
# ...
ip_configuration {
#...
public_ip_address_id = try(azurerm_public_ip.public_ip[each.key].id,null)
}
}
Upvotes: 1