qtime67
qtime67

Reputation: 317

How to interpolate COUNT in Terraform?

I am creating a number of VMs in Azure with corrosponding NICs and PublicIPs.

I can create unique names for the VMs no problem:

resource "azurerm_virtual_machine" "workernode" {
    count = "${var.nodeCount}"
    name = "workernode-${count.index +1}"

and the public IPs:

resource "azurerm_public_ip" "AliasworkerPubIP" {
    count = "${var.nodeCount}"
    name = "workerpubip${count.index +1}"

and the NIC:

resource "azurerm_network_interface" "workerNIC" {
    count = "${var.nodeCount}"
    name = "workerNIC.${count.index +1}"  

but I cant work out how to get it to work for then connecting the NIC to the PublicIP just created ...

Have tried various different ways and nothing is clicking ... I know I missing something or not understanding interpolation parsing correctly, but what?!

examples I have tried:

public_ip_address_id = "${azurerm_public_ip}.${format("Alias_WorkerIP%d.id", count.index +1)}" 

public_ip_address_id = "${format("Alias_WorkerIP%d.id", count.index +1)}"

public_ip_address_id = "${format("azurerm_public_ip.workerpubip.%s.id", count.index +1)}" 

any ideas of where I am going wrong?

Upvotes: 0

Views: 1671

Answers (3)

passionatedevops
passionatedevops

Reputation: 533

try this in azurerm_network_interface module

 public_ip_address_id          = "${element(azurerm_public_ip.main-rg__vm-ip.*.id, count.index)}"

in azurerm_public_ip module

resource azurerm_public_ip main-rg__vm-ip {
  count               = "${var.vm_count}"
  name                = "${var.environment}-vm${count.index+1}-ip"
  location            = "${var.location}"
  resource_group_name = "${azurerm_resource_group.main-rg.name}"
  sku                 = "Basic"
  allocation_method   = "Dynamic"


}

Upvotes: 0

Martin Atkins
Martin Atkins

Reputation: 74574

The current recommended way to express this is:

public_ip_address_id = "${azurerm_public_ip.workerpubip.*.id[count.index]}"

Using this index operator ([ ... ]) allows Terraform to understand better the dependency this implies, so that if only one of the public IP instances needs to be replaced it can understand that only the one corresponding azurerm_network_interface needs to be updated.

When using the element function Terraform only "sees" the azurerm_public_ip.workerpubip.*.id expression and assumes, conservatively, that there is a dependency on all of the azurerm_public_ip ids.

Upvotes: 3

qtime67
qtime67

Reputation: 317

This is how I solved it:

public_ip_address_id = "${element(azurerm_public_ip.workerpubip.*.id,count.index)}"

Upvotes: 2

Related Questions