How to output multiple public IPs?

Hello all,

I’m kinda new to Terraform, and I have a project where we need to use count to create multiple resources based on an input of a variable. In the end I’d like to output all Public IPs provisioned but I’m not being able to do this as we are using count.

I’ve learned that Public IP Addresses aren’t allocated until they’re attached to a device and here is an example on how to fetch a public IP of a new allocated VM. But I can’t get it to work when using count.

Here is the relevant code that I have so far:

data "azurerm_public_ip" "FEs-PIP" {
  name                = azurerm_public_ip.pip-coaching.*.name
  resource_group_name = azurerm_virtual_machine.vm-coaching.*.resource_group_name
}

resource "azurerm_public_ip" "pip-coaching" {
  count                   = var.coaching-persons * 3
  name                    = "Pip-Coaching-${count.index}"
  location                = var.location
  resource_group_name     = azurerm_resource_group.rg-coaching.name
  allocation_method       = "Dynamic"
  idle_timeout_in_minutes = 30
}

resource "azurerm_network_interface" "nic-coaching" {
  count               = var.coaching-persons * 3
  name                = "Nic-${count.index}-Coaching"
  location            = var.location
  resource_group_name = azurerm_resource_group.rg-coaching.name

  ip_configuration {
    name                          = "Nic-${count.index}-Coaching-ipconfig"
    subnet_id                     = azurerm_subnet.snet-coaching.id
    private_ip_address_allocation = "Dynamic"
    public_ip_address_id          = azurerm_public_ip.pip-coaching["${count.index}"].id
  }
}


resource "azurerm_virtual_machine" "vm-coaching" {
  count                            = var.coaching-persons * 3
  name                             = "VM-${count.index}-Coaching"
  network_interface_ids            = [azurerm_network_interface.nic-coaching["${count.index}"].id]
...}


output "FEs-IPs" {
  description = "IPs of all FEs provisoned."
  value       = azurerm_virtual_machine.vm-coaching.*.public_ip_address
}

The ultimate goal is to display a list of all provisioned Public IPs after running terraform apply
I can’t get it to work like this. If you guys could point me in the right direction I’d be thankful.

1 Like

So I ended up finding the solution.

Here it goes in case someone needs in the future:

data "azurerm_public_ip" "FEs-PIP" {
  count               = var.coaching-persons * 3
  name                = azurerm_public_ip.pip-coaching[count.index].name
  resource_group_name = azurerm_virtual_machine.vm-coaching[count.index].resource_group_name
}

output "FEs-IPs" {
  description = "IPs of all FEs provisoned."
  value       = data.azurerm_public_ip.FEs-PIP.*.ip_address
}

Cheers.

4 Likes