Bird
Raised Fist0
Terraformcloud~10 mins

Count vs for_each decision in Terraform - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Process Flow - Count vs for_each decision
Start: Define resource
↓
Choose between count or for_each
↓
count
↓
Create N instances
↓
Access by index
↓
End
This flow shows deciding between using count or for_each to create multiple resources in Terraform, then how instances are accessed.
Execution Sample
Terraform
resource "aws_instance" "example" {
  count = 3
  ami = "ami-123456"
  instance_type = "t2.micro"
}

resource "aws_instance" "example_map" {
  for_each = {a=1, b=2}
  ami = "ami-123456"
  instance_type = "t2.micro"
}
Creates 3 instances using count and 2 instances using for_each with keys 'a' and 'b'.
Process Table
StepResourceCount/for_each ValueInstances CreatedAccess MethodNotes
1aws_instance.examplecount=33 instances (index 0,1,2)By index (example[0])Creates 3 identical instances
2aws_instance.example_mapfor_each={a=1,b=2}2 instances (keys 'a','b')By key (example_map["a"])Creates instances with keys
3aws_instance.exampleAccess example[1]Instance at index 1Index accessAccess second instance
4aws_instance.example_mapAccess example_map["b"]Instance with key 'b'Key accessAccess instance with key 'b'
5DecisionUse count if identical instancesN/AN/ACount is simpler for identical resources
6DecisionUse for_each if unique keys neededN/AN/Afor_each allows mapping keys to instances
7EndN/AN/AN/AResource creation complete
💡 All instances created and accessible by their respective methods; decision depends on use case.
Status Tracker
VariableStartAfter Step 1After Step 2Final
countundefined333
for_eachundefinedundefined{"a":1,"b":2}{"a":1,"b":2}
instances_count0333
instances_for_each0022
Key Moments - 3 Insights
Why can't I use count with a map or set to create uniquely keyed resources?
Count creates instances by number only, so it can't assign unique keys. See execution_table rows 1 and 2 where count creates indexed instances but for_each creates keyed instances.
How do I access a specific instance created with for_each?
You access it by its key, like example_map["a"]. This is shown in execution_table row 4, unlike count which uses numeric indexes.
When should I prefer count over for_each?
Use count when you want multiple identical resources without unique keys. This is explained in execution_table row 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, how many instances does aws_instance.example create?
A2
B1
C3
D0
💡 Hint
Check execution_table row 1 under 'Instances Created'
At which step do we see accessing an instance by key?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at execution_table row 4 under 'Access Method'
If you want to create 5 identical instances, which method is simpler according to the table?
Acount = 5
Bfor_each with 5 keys
Cfor_each with a map of 3 keys
Dcount = 3
💡 Hint
Refer to execution_table row 5 about when to use count
Concept Snapshot
Terraform lets you create multiple resources using count or for_each.
Use count when you want N identical copies, accessed by index.
Use for_each when you want to create resources with unique keys, accessed by those keys.
Count uses a number; for_each uses a map or set.
Choose based on whether you need simple copies or keyed instances.
Full Transcript
This visual execution shows how Terraform decides between count and for_each to create multiple resources. Count creates a fixed number of identical instances accessed by numeric index. For_each creates instances based on keys from a map or set, accessed by those keys. The execution table traces creation and access steps, showing count creates 3 instances indexed 0 to 2, while for_each creates 2 instances with keys 'a' and 'b'. Variable tracking shows how count and for_each values change. Key moments clarify common confusions about access methods and when to use each. The quiz tests understanding of instance counts, access methods, and decision criteria. The snapshot summarizes the key differences and usage rules.

Practice

(1/5)
1. Which Terraform argument should you use when you want to create 3 identical resources without unique identifiers?
easy
A. count = 3
B. for_each = {}
C. for_each = toset(["a", "b", "c"])
D. count = 0

Solution

  1. Step 1: Understand the purpose of count

    count creates multiple copies of a resource by number, perfect for identical resources.
  2. Step 2: Compare with for_each

    for_each is used when you want unique keys or values to identify each resource, not just copies.
  3. Final Answer:

    count = 3 -> Option A
  4. Quick Check:

    Simple copies = count [OK]
Hint: Use count for number copies, for_each for unique keys [OK]
Common Mistakes:
  • Using for_each when only number copies are needed
  • Setting count to zero expecting resources
  • Confusing sets with counts
2. Which of the following is the correct syntax to create resources using for_each with a map in Terraform?
easy
A. resource "aws_instance" "example" { for_each = ["a", "b"] }
B. resource "aws_instance" "example" { for_each = "string" }
C. resource "aws_instance" "example" { count = 2 }
D. resource "aws_instance" "example" { for_each = { key1 = "val1", key2 = "val2" } }

Solution

  1. Step 1: Identify valid for_each types

    for_each accepts maps or sets, not lists or strings directly.
  2. Step 2: Check each option

    resource "aws_instance" "example" { for_each = { key1 = "val1", key2 = "val2" } } uses a map with keys and values, which is valid syntax for for_each.
  3. Final Answer:

    resource with for_each map -> Option D
  4. Quick Check:

    for_each needs map or set [OK]
Hint: for_each needs map or set, not list or string [OK]
Common Mistakes:
  • Using list instead of map/set for for_each
  • Confusing count with for_each syntax
  • Passing string directly to for_each
3. Given this Terraform snippet:
resource "aws_s3_bucket" "buckets" {
  for_each = { bucket1 = "private", bucket2 = "public-read" }
  bucket = each.key
  acl = each.value
}

What will be the names of the created buckets?
medium
A. ["each.key", "each.value"]
B. ["private", "public-read"]
C. ["bucket1", "bucket2"]
D. No buckets created due to syntax error

Solution

  1. Step 1: Understand for_each map keys and values

    The keys are bucket1 and bucket2, values are ACL values.
  2. Step 2: Check bucket assignment

    The bucket name is set to each.key, so buckets named "bucket1" and "bucket2" are created.
  3. Final Answer:

    ["bucket1", "bucket2"] -> Option C
  4. Quick Check:

    Bucket names = map keys [OK]
Hint: for_each keys become resource identifiers [OK]
Common Mistakes:
  • Using values as bucket names instead of keys
  • Assuming syntax error without checking
  • Confusing each.key with each.value
4. You wrote this Terraform resource:
resource "aws_instance" "example" {
  count = length(var.instances)
  name  = var.instances[count.index]
}

But Terraform throws an error about count.index. What is the likely cause?
medium
A. count is used but for_each should be used for maps
B. var.instances is a map, but count expects a list
C. You cannot use count.index inside resource blocks
D. count must be a fixed number, not a variable

Solution

  1. Step 1: Identify variable type mismatch

    var.instances is likely a map, but count works with numbers and lists indexed by numbers.
  2. Step 2: Choose correct iterator

    For maps, for_each is the correct choice to iterate over keys and values.
  3. Final Answer:

    Use for_each for maps, not count -> Option A
  4. Quick Check:

    Maps need for_each, not count [OK]
Hint: Use for_each for maps, count for lists [OK]
Common Mistakes:
  • Using count.index with maps
  • Assuming count must be fixed number
  • Ignoring variable data type
5. You want to create multiple AWS IAM users with unique usernames and policies from this map:
users = {
  alice = "admin",
  bob = "read-only",
  carol = "power-user"
}

Which Terraform resource block correctly uses count or for_each to create these users with unique names?
hard
A.
resource "aws_iam_user" "user" {
  count = length(keys(var.users))
  name  = keys(var.users)[count.index]
  policy = var.users[name]
}
B.
resource "aws_iam_user" "user" {
  for_each = var.users
  name     = each.key
  policy   = each.value
}
C.
resource "aws_iam_user" "user" {
  count = 3
  name  = var.users[count.index]
  policy = var.users[count.index]
}
D.
resource "aws_iam_user" "user" {
  for_each = toset(var.users)
  name     = each.value
  policy   = each.key
}

Solution

  1. Step 1: Analyze data structure

    The users variable is a map with usernames as keys and policies as values.
  2. Step 2: Match iteration method

    for_each works well with maps to create uniquely identified resources using keys and values.
  3. Step 3: Check each option

    resource "aws_iam_user" "user" {
      for_each = var.users
      name     = each.key
      policy   = each.value
    }
    correctly uses for_each = var.users and assigns name = each.key and policy = each.value.
  4. Final Answer:

    Use for_each with map for unique users -> Option B
  5. Quick Check:

    Unique keys need for_each [OK]
Hint: Use for_each with maps for unique resource keys [OK]
Common Mistakes:
  • Using count with maps incorrectly
  • Mixing keys and values in wrong order
  • Using toset on maps causing errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard