World map

 

BM: Baca dalam Bahasa Melayu

World T2: Inputs & Outputs

for_each: one per item

You will learn: to make one copy per item with for_each, named by the item, not a number.

Checked with OpenTofu 1.13 on 1 Nov 2026

The problem

With count, closing mee rebuilt roti’s file. You want each stall to keep its own place. What helps?

Pick one answer.

Watch

This blueprint uses for_each. Type tofu state list.

Blueprint (your .tf files)init done

  • local_file.stall["mee"]
  • local_file.stall["nasi"]
  • local_file.stall["roti"]

Built (the state file)state #1

  • local_file.stall["mee"]
  • local_file.stall["nasi"]
  • local_file.stall["roti"]
Blueprint: 3 resources. Built: 3.

Change a file, then run tofu plan to see what it means.

for_each: Make one copy per item of a map or set, named by its key: stall["nasi"]. makes one copy per item. Each copy is named by its key: stall["mee"].

Predict

You remove β€œmee” from the set. What does the plan do?

Pick one answer.

Try it

Check it. In variables.tf, remove "mee" from the list. Then type tofu plan.

Blueprint (your .tf files)init done

  • local_file.stall["mee"]
  • local_file.stall["nasi"]
  • local_file.stall["roti"]

Built (the state file)state #1

  • local_file.stall["mee"]
  • local_file.stall["nasi"]
  • local_file.stall["roti"]
Blueprint: 3 resources. Built: 3.

Change a file, then run tofu plan to see what it means.

Check

count or for_each?

Drag a card into a box. Or tap the card, then tap the box.

      Try it

      for_each takes a map too: each.key is the dish, each.value its price. Build the price tags: tofu apply, yes.

      Blueprint (your .tf files)init done

      • local_file.price["nasi"]not built yet
      • local_file.price["teh"]not built yet

      Built (the state file)

      Nothing built yet.

      Blueprint: 2 resources. Built: 0.

      Change a file, then run tofu plan to see what it means.

      resource "local_file" "price" {
        for_each = var.prices
        filename = "${each.key}-price.txt"
        content  = "${each.key}: RM${each.value}\n"
      }

      Check

      How do you name teh’s price file in a command?

      Pick one answer.

      You did it!

      You can now make one copy per item with for_each.

      Go deeper (optional)

      for_each takes a map or a set of strings. Turn a list into a set with toset(var.stalls). The keys must be known before apply, so they can’t come from random values. In a shell, quote addresses with brackets: tofu state show 'local_file.stall["mee"]'.