thedevopscat blog

Thoughts, observations and learnings of the devopscat...

Terraform Count Index

2022-12-22 2 min read Terraform

As a quick summary, a count index can be used (but probably shouldn’t, for_each is more flexible) to create multiple resource instances of the same type from one block of code, for example lets say you want a spin up multiple vm’s behind a load balancer for some fault tolerance.

The benefit here is you would have one block of code which would be automatically processed multiple times, as specified by your count variable/local, (it can also be set 1 or even zero, but more on this another time…).

Our (truncated) code snippet would look something like this:

locals {
  windows_vm_count = 3  # How many VM's do you want to create?
}

resource "azurerm_windows_virtual_machine" "windows_vm" {
  count                 = local.windows_vm_count
  name                  = join("-", ["vm", (count.index + 1)]) 
...

Key points here are:

  • terraform automatically handles the uniqueness of the state file labels by adding a bracketed number of the end, e.g. windows_vm[0], windows_vm[1] etc.
  • the resource name obviously needs to be unique for each instance, so you need to incorporate the count index into the name argment value to increment a number to achieve uniqueness, or you could randomise.
  • the count index starts at 0, so as per this example, if you want 3x vm’s named vm-1, vm-2 and vm-3, you would need to add 1 to the count index for the naming.
  • all other dependancies also need to be counted in exactly the same manner, e.g. the nic, nic association etc.

Be Careful: If you name you vm’s: vm-1 and vm-2 (etc), they will be referenced in state as: vm[0] and vm[1], hence named vm-2 = vm[1] in state (so don’t go deleting the wrong one! - or just align your readble names from zero if you can handle it…)

On the face of it very useful, but you soon need to get creative to overcome the limitations of making everything alike! See the next blog where we explore the limitations and some elegant solutions.