Labs · DevOps
Lab: Create Three Copies with count, Remove the Middle One and See the Index Shift, Then Fix It with for_each
Course: DevOps · Chapter 36: Terraform count for_each dynamic lifecycle and depends_on · Lesson: 36.2 for_each: named copies that survive edits
Chapter 36 explains count, for_each, dynamic and lifecycle; this lab shows the classic count trap with zero cloud cost.
Chala mitrano! count vaaparla ani madhla ek item kaadhla tar Terraform baakiche pan badalto. Aaj he dolyaane baghuya.
Suppose we are…
Suppose we are on an Instagram-style team that keeps one S3 bucket per region in a list. Someone removes the middle region from the list, and the plan suddenly wants to destroy and re-create a bucket full of data. That is the count index shift.
In this lab we reproduce the trap with harmless local files, then fix it with for_each, where each copy has a name instead of a position.
Goal of this lab
By the end you will have:
- Three files from a
countlist, and a plan that shows the index shift. - The same three files from
for_each, and a plan that touches only the removed one. - A clear one-line rule for when to use each.
What you need
- Terraform 1.6+. No cloud account needed.
- 30 minutes.
Part 1: The count trap
Create a folder and
main.tf:main.tf
variable "regions" { type = list(string) default = ["mumbai", "hyderabad", "singapore"] } resource "local_file" "by_count" { count = length(var.regions) filename = "${path.module}/count-${count.index}.txt" content = "bucket for ${var.regions[count.index]}\n" }mkdir tf-foreach && cd tf-foreachInit and apply:
terraform init terraform apply -auto-approve terraform state listWhat you should see:
local_file.by_count[0],[1]and[2].Remove
"hyderabad"from the list and plan:terraform plan -var 'regions=["mumbai","singapore"]'What you should see: index
[1]is replaced (its content changes from hyderabad to singapore) and[2]is destroyed: two resources touched to remove one. With real buckets, that is data loss.
Part 2: Fix it with for_each
Destroy the count version, then replace the whole
main.tfwith a for_each version:main.tf
variable "regions" { type = set(string) default = ["mumbai", "hyderabad", "singapore"] } resource "local_file" "by_name" { for_each = var.regions filename = "${path.module}/each-${each.key}.txt" content = "bucket for ${each.key}\n" }terraform destroy -auto-approveApply and list:
terraform apply -auto-approve terraform state listWhat you should see:
local_file.by_name["hyderabad"],["mumbai"],["singapore"].Remove hyderabad again and plan:
terraform plan -var 'regions=["mumbai","singapore"]'What you should see:
Plan: 0 to add, 0 to change, 1 to destroy.Only["hyderabad"]is touched.
Clean up: destroy everything
Delete everything this lab created. Type
yeswhen asked:terraform destroy -auto-approveWhat you should see:
Destroy complete! Resources: 3 destroyed.
Ravindra Bagale's Tip
Use count for "N identical copies" or an on/off switch (count = var.enabled ? 1 : 0). Use for_each whenever the copies have names.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
for_each over a list | The given "for_each" argument value is unsuitable | Use toset(var.list) or a map |
| Keys that are known only after apply | Invalid for_each argument | Use static keys such as names |
| Switching count to for_each on live resources without reading the plan | Everything destroyed and re-created | Add moved blocks from [0] to ["name"] |
Self-check checklist
0 of 4 done
Try-at-home challenge
Recreate the count version, apply, then switch to for_each and write moved blocks (from = local_file.by_count[0], to = local_file.by_name["mumbai"], and so on). Keep the filenames the same and get a plan with no destroys.
Samajla ka? Names survive edits, positions do not. Aata pudhe jaauya remote state.