loading...

Terraform: use for_each instead of count

drewmullen profile image drewmullen Updated on ・1 min read

For a long time I've used the count meta-argument to create multiple instances of a resource. One of the problems with this is ordering. Since count is managing a list, if any objects in the list change position terraform wants to destroy/re-create that object. This can cause obvious problems; at the very least heart burn.

Example using count:

locals {
  user_list = [
  {
    email = "drew@nebulaworks.com",
    display_name = "Drew Mullen"
  },
  {
    email = "ldong@nebulaworks.com",
    display_name = "Lynn Dong"
  }
  ]
}

resource "azuread_user" "user_template" {
  count = length(local.user_list)
  user_principal_name = lower(local.user_list[count.index].email)
  display_name        = local.user_list[count.index].display_name
  password            = "SuperPassword123"
  force_password_change = true
}

Example using for_each:

variable "nwi_users" {
    description = "NWI users for Azure. Key is the displayed name, value is the login name (your email)."
    type = map
    default = {
        "Lynn Dong" = "ldong@nebulaworks.com",
        "Drew Mullen" = "drew@nebulaworks.com"
    }
}

resource "azuread_user" "user_template" {
  for_each = var.nwi_users

  user_principal_name = lower(each.value)
  display_name        = each.key
  password            = "SuperPassword123"
  force_password_change = true
}

Note: It is annoying that the Azure provider requires a static password, however, terraform is smart enough to not bork your password when its updated.

The above code builds the same resources but is cleaner to read and also is no longer effected by the order of the variable's values!

Posted on by:

drewmullen profile

drewmullen

@drewmullen

Full-stack YAML engineer

Discussion

pic
Editor guide
 

Helpful simple example. thanks.