Ravindra BagaleCourses & study guides Track your progress

Labs · DevOps

Lab: Create Three Copies with count, Remove the Middle One and See the Index Shift, Then Fix It with for_each

Beginner30 minTerraform 1.6+ · Terminal

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 count list, 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

  1. 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-foreach
    
  2. Init and apply:

    terraform init
    terraform apply -auto-approve
    terraform state list
    

    What you should see: local_file.by_count[0], [1] and [2].

  3. 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

  1. Destroy the count version, then replace the whole main.tf with 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-approve
    
  2. Apply and list:

    terraform apply -auto-approve
    terraform state list
    

    What you should see: local_file.by_name["hyderabad"], ["mumbai"], ["singapore"].

  3. 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

  1. Delete everything this lab created. Type yes when asked:

    terraform destroy -auto-approve
    

    What 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

MistakeWhat happensFix
for_each over a listThe given "for_each" argument value is unsuitableUse toset(var.list) or a map
Keys that are known only after applyInvalid for_each argumentUse static keys such as names
Switching count to for_each on live resources without reading the planEverything destroyed and re-createdAdd 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.