Bird
Raised Fist0
Terraformcloud~10 mins

Iterator variable in Terraform - Step-by-Step Execution

Choose your learning style10 modes available
Process Flow - Iterator variable
Start with collection
↓
Pick next item as iterator variable
↓
Use iterator variable in block
↓
More items?
Yes→Repeat pick next item
No↓
End iteration
Terraform loops over each item in a collection, assigning it to an iterator variable to use inside the loop block.
Execution Sample
Terraform
locals {
  names = ["app1", "app2", "app3"]
}

resource "null_resource" "example" {
  for_each = toset(local.names)
  triggers = {
    name = each.key
  }
}
This code loops over a list of names, using each name as an iterator variable to create resources.
Process Table
StepIterator Variable (each.key)ActionResource Created
1"app1"Assign first item to iterator variablenull_resource.example["app1"]
2"app2"Assign second item to iterator variablenull_resource.example["app2"]
3"app3"Assign third item to iterator variablenull_resource.example["app3"]
4N/ANo more items, iteration endsNo new resource
💡 All items in the set processed, iteration stops.
Status Tracker
VariableStartAfter 1After 2After 3Final
each.keyN/A"app1""app2""app3"N/A
Key Moments - 2 Insights
Why does the iterator variable change each step?
Because Terraform assigns each item from the collection to the iterator variable in order, as shown in execution_table steps 1 to 3.
What happens when all items are processed?
Iteration stops, no more resources are created, as shown in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the iterator variable value at step 2?
A"app2"
B"app1"
C"app3"
DN/A
💡 Hint
Check the 'Iterator Variable (each.key)' column at step 2 in the execution_table.
At which step does the iteration end?
AStep 3
BStep 2
CStep 4
DStep 1
💡 Hint
Look for the step where 'No more items, iteration ends' is noted in the Action column.
If the list had 4 names instead of 3, how would the execution table change?
AThere would still be 4 steps, no change.
BThere would be 5 steps, with the 4th step assigning the new name.
CThere would be 3 steps only.
DThe iteration would never end.
💡 Hint
Refer to the pattern in execution_table rows for each item processed.
Concept Snapshot
Terraform iterator variable:
- Loops over each item in a collection
- Assigns current item to iterator variable (e.g., each.key)
- Use iterator variable inside resource or block
- Iteration ends when all items processed
- Enables dynamic resource creation
Full Transcript
In Terraform, an iterator variable is used to loop over a collection like a list or set. Each item in the collection is assigned to the iterator variable one by one. This variable can then be used inside resource blocks to create multiple resources dynamically. The process continues until all items are processed, then the iteration stops. For example, looping over a list of names assigns each name to the iterator variable 'each.key' in turn, creating a resource for each name.

Practice

(1/5)
1. What is the role of an iterator variable in a Terraform for expression?
easy
A. It represents each item in the list or map during iteration.
B. It defines the output type of the expression.
C. It sets the maximum number of iterations.
D. It stores the final result of the iteration.

Solution

  1. Step 1: Understand the iterator variable concept

    The iterator variable is a placeholder that takes each value from the list or map one by one during the loop.
  2. Step 2: Identify its role in the for expression

    It allows Terraform to perform actions on each item individually, making the code reusable and clean.
  3. Final Answer:

    It represents each item in the list or map during iteration. -> Option A
  4. Quick Check:

    Iterator variable = item placeholder [OK]
Hint: Think of iterator as the 'current item' in a loop [OK]
Common Mistakes:
  • Confusing iterator with output variable
  • Assuming iterator sets iteration count
  • Thinking iterator stores final results
2. Which of the following is the correct syntax for using an iterator variable item in a Terraform for expression over a list var.names?
easy
A. for item in var.names : item
B. [for item var.names : item]
C. [for item in var.names : item]
D. for (item in var.names) { item }

Solution

  1. Step 1: Recall Terraform for expression syntax

    Terraform uses square brackets with for item in list : expression to create a new list.
  2. Step 2: Match the correct syntax

    [for item in var.names : item] matches the correct syntax: [for item in var.names : item].
  3. Final Answer:

    [for item in var.names : item] -> Option C
  4. Quick Check:

    Correct for expression syntax = [for item in var.names : item] [OK]
Hint: Remember: Terraform for expressions use square brackets [OK]
Common Mistakes:
  • Omitting square brackets
  • Using parentheses instead of brackets
  • Missing 'in' keyword
3. Given the Terraform expression:
[for num in [1, 2, 3] : num * 2]

What is the resulting list?
medium
A. [1, 2, 3]
B. [2, 4, 6]
C. [3, 4, 5]
D. [2, 3, 4]

Solution

  1. Step 1: Identify the iterator and list

    The iterator variable is num, iterating over the list [1, 2, 3].
  2. Step 2: Calculate each iteration's output

    Each num is multiplied by 2: 1*2=2, 2*2=4, 3*2=6.
  3. Final Answer:

    [2, 4, 6] -> Option B
  4. Quick Check:

    Multiply each item by 2 = [2, 4, 6] [OK]
Hint: Apply the operation to each item in the list [OK]
Common Mistakes:
  • Confusing multiplication with addition
  • Returning original list without changes
  • Misreading the iterator variable
4. Identify the error in this Terraform for expression:
[for i var.list : i * 3]
medium
A. Missing 'in' keyword between iterator and list.
B. Iterator variable should be a string, not 'i'.
C. Square brackets are not allowed around for expressions.
D. The multiplication operator '*' is invalid here.

Solution

  1. Step 1: Check for correct for expression syntax

    The correct syntax requires the keyword 'in' between the iterator and the list.
  2. Step 2: Identify the missing keyword

    The expression misses 'in' after 'i', causing a syntax error.
  3. Final Answer:

    Missing 'in' keyword between iterator and list. -> Option A
  4. Quick Check:

    For expressions need 'in' keyword [OK]
Hint: Always include 'in' between iterator and collection [OK]
Common Mistakes:
  • Forgetting 'in' keyword
  • Using wrong brackets
  • Misplacing operators
5. You want to create a map from a list of server names var.servers = ["web", "db", "cache"] where each key is the server name and the value is the server port starting at 8000 incremented by 1. Which Terraform expression correctly uses an iterator variable to achieve this?
hard
A. { for srv in var.servers : srv => 8000 }
B. { for srv in var.servers : 8000 => srv }
C. [for srv in var.servers : { srv = 8000 }]
D. { for idx, srv in var.servers : srv => 8000 + idx }

Solution

  1. Step 1: Understand the requirement

    Create a map where keys are server names and values are ports starting at 8000 incremented by 1.
  2. Step 2: Analyze options for correct iterator usage

    { for idx, srv in var.servers : srv => 8000 + idx } uses for idx, srv in var.servers to get index and server name, then maps srv => 8000 + idx, correctly incrementing ports.
  3. Final Answer:

    { for idx, srv in var.servers : srv => 8000 + idx } -> Option D
  4. Quick Check:

    Use index and value in for map expression [OK]
Hint: Use index and value in for map to increment ports [OK]
Common Mistakes:
  • Using list syntax instead of map
  • Not using index to increment port
  • Swapping key and value positions
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