DEV Community

drewmullen
drewmullen

Posted on • Updated on

Terraform: use for_each instead of count

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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!

Update: Although we disagree on when to use count vs for_each, Spacelift has written up a good long-form blog on these meta arguments! Find their blog for added context and explanation here.

Top comments (1)

Collapse
 
yeahsmaggy profile image
Andy Welch

Helpful simple example. thanks.