count and for_each

Intermediate · 10 min

Create many copies of a resource with count or for_each, and see why removing one item from the middle of a list quietly rewrites everything after it.

Before thisConditionals and for expressionsType constraints and complex variables

DevOps with Flavius · 10 min

count and for_each

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by DevOps with FlaviusReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `count = N` makes N copies addressed by position, `aws_x.name[0]`, `[1]` and so on. `for_each` makes one per key of a map or set, addressed by key, `aws_x.name["api"]`.
  • With `count`, removing an item from the middle of a list shifts every later index. Terraform sees the later items as changed.
  • With `for_each`, each instance has a stable address, so removing one key affects only that instance.
  • `for_each` needs a map or a set of strings, and its keys must be known at plan time. Use `toset()` to convert a list.
  • Use `count` for 'none or one' and identical copies. Use `for_each` for anything with names.

Three users, one removed

A team keeps an IAM user per engineer. Today that is a list: ["ana", "bo", "cy", "di"]. Writing four resource blocks is silly, so you write one with count = length(var.users). It works. Then Bo leaves, you delete "bo" from the list, run plan, and it says it will change two users and destroy one. Bo’s account was supposed to be the only thing touched.

Understanding why is the whole lesson. Both meta-arguments make many copies of a block. They differ in how they name them.

Two ways to name copies

count names by position:

resource "aws_iam_user" "u" {
  count = length(var.users)
  name  = var.users[count.index]
}

The instances are aws_iam_user.u[0], [1], [2] and [3]. count.index is the position.

for_each names by key:

resource "aws_iam_user" "u" {
  for_each = toset(var.users)
  name     = each.key
}

The instances are aws_iam_user.u["ana"], ["bo"] and so on. each.key is the key, and with a map, each.value is the value. Both blocks written from the Terraform docs. I did not run them, since there is no Terraform or AWS account here.

What happens on removal

I wrote a small stand-in that assigns each list item an address the way each form does, then compares before and after removing bo. It is my own code, not Terraform:

count     remove 'bo': destroy 1 ['aws_iam_user.u[3]'], update-in-place(name changes) 2 ['aws_iam_user.u[1]', 'aws_iam_user.u[2]'], create 0
for_each  remove 'bo': destroy 1 ['aws_iam_user.u["bo"]'], update-in-place(name changes) 0 [], create 0

With count, position 1 used to be bo and is now cy, position 2 used to be cy and is now di, and position 3 no longer exists. Terraform sees “instance 1 changed its name” and “instance 2 changed its name”, then destroys the last. For IAM users that is churn and risk. For something holding data, such as a database or a disk, “rename” can mean replace. With for_each, ["bo"] disappears and nothing else moves.

That is the central rule: an address should mean the same thing tomorrow as today. A list position does not, and a name does.

Rules for for_each

The Terraform docs state its limits:

  • It takes a map or a set of strings. A list is not converted for you, so use toset().
  • The keys must be known at plan time. If they depend on something Terraform learns during apply, such as the ID of a resource that does not exist yet, you get an error that the value cannot be determined before apply.
  • Sensitive values are not allowed, because Terraform shows keys in its output. A workaround is toset([for k, v in local.map : k]) when only the values are sensitive.
  • Impure functions like uuid() and timestamp() cannot build keys.
  • You cannot use both count and for_each on one block.

The docs’ own guidance: use for_each when instances need distinct argument values that cannot be derived from an integer, and count when you want nearly identical instances.

The map of objects pattern

The strongest form of for_each is a map of objects, which fits the type lesson you just finished:

variable "buckets" {
  type = map(object({
    versioning = optional(bool, false)
  }))
}

resource "aws_s3_bucket" "this" {
  for_each = var.buckets
  bucket   = "acme-${each.key}"
}

To add a bucket, add an entry to the map. To remove one, delete the entry. The plan touches only that bucket. This shape is why many modules take a map of objects instead of parallel lists. In the AWS VPC module’s main.tf I counted roughly 70 count lines against 7 for_each lines. Most of those count lines are the on-or-off idiom, which is the right use.

Where count is right

Use count for “zero or one”: count = var.create_log_bucket ? 1 : 0, as in the previous lesson. And use it when the copies are interchangeable and you will never remove one from the middle, such as a pool of identical workers where the number is the only parameter.

Changing your mind later

If you already have count instances and want to move to for_each, do not just edit the code. The addresses change, so Terraform would destroy [0] and create ["ana"]. Rename the objects in state with moved blocks first. That is the topic of moved blocks and safe refactoring, later in the state group.

About the video

The embed is all of DevOps with Flavius’s “Terraform For_Each vs Count: The Ultimate Comparison”, September 2024, about 10 minutes. Chapters are “Count” and “For_Each”. According to its description, it creates several Kubernetes resources in a local kind cluster, so no cloud cost is involved. I judged the content from the title, description and chapters, and did not check whether it shows the index-shift problem. That part of the lesson is my own run. Sanabria’s five-minute short in deeper covers the tradeoffs. English was judged from title, channel and the English auto-caption track.

Where this fits

Repeating a whole resource is one kind of repetition. Repeating a nested block inside one resource is another, and it has its own tool: dynamic blocks.

Check yourself

  1. 01You create three IAM users from a list with `count`, then delete the second name from the list. What does the plan do?

    It changes the second instance to the third name, changes the third to nothing and destroys it. Instances are tied to positions, so the shift touches everything after the removed item.

  2. 02What is the address of an instance made by `for_each` over `{ api = ..., web = ... }`?

    `aws_x.name["api"]` and `aws_x.name["web"]`. The key is part of the address, which is why it stays stable.

  3. 03Terraform complains that `for_each` has values that cannot be determined until apply. What causes that?

    The keys, or the set elements, depend on something that does not exist until apply, such as a generated ID. Keys must be known at plan time, so base them on inputs you control.

  4. 04When is `count` still the right tool?

    When there are either zero or one of something, as in `count = var.enabled ? 1 : 0`, or when you truly want identical, interchangeable copies.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark