I’m new to Azure Terraform and is having issues setting public_ip_address_id correctly on this part of azurerm_network_interface resource. Can I request for advice. Thanks!
I’m creating 8 interface and trying to bind public ip on the first 3 interfaces. tried using try function to return and set public_ip_id on the first 3 interfaces and set null on the rest of the interfaces
resource "azurerm_network_interface" "virtual_network_interfaces" {
for_each = var.interfaces
location = var.location
resource_group_name = var.resource_group_name
name = "${var.device_name}_${var.instance_type}_${var.site_name}_${each.value.name}_Interface"
enable_ip_forwarding = true
enable_accelerated_networking = true
ip_configuration {
name = "${var.device_name}_${var.instance_type}_${var.site_name}_${each.value.name}_IP_Config"
private_ip_address = each.value.address_prefixes[0]
private_ip_address_allocation = "Static"
# set Management interface as primary vNIC
primary = each.value.name == "Management" ? true : false
subnet_id = try(
lookup(
{ for k, v in var.subnets : v.name => v.id },
each.value.name, null
), null
)
public_ip_address_id = try(
{
for k1, v1 in var.public_ips :
k1 => can(regex("${each.value.name}", v1.name)) ? v1.id : null
},
null)
}
}
2
Answers
Trying to understand more I created public_ip_address (3 object) and interface (8 object) name exact match. With 3 public IPs works.
null)
But with this code failed, both cases will match 1st 3 interface bind public IP rest returns null
Any idea, advise. thanks!
The current logic you’re using to set
public_ip_address_id
is to iterate overvar.public_ips
and, for each public IP, check if the current NIC’s name (fromvar.interfaces
) matches the name of the public IP. If it does, set thepublic_ip_address_id
to the ID of that public IP, otherwise set it tonull
.The issue with this approach is that the logic will always return the ID of the last matched public IP (or
null
if no match was found). This isn’t ideal because, if multiple public IPs match the NIC’s name, only the last one will be set.Moreover, the use of the
can(regex())
function here is not ideal. If you’re trying to bind the first 3 interfaces to public IPs, a more deterministic approach is recommended.I tried to achieve your requirement using my won configuration module changes which were mentioned as follows.
My terraform configuration:
main.tf:
variable.tf:
Output:
This configuration creates a virtual network, a subnet, 3 public IPs, and 8 network interfaces. The first 3 of those interfaces will be bound to the public IPs, while the rest will not have public IPs.