Bird
Raised Fist0
Terraformcloud~5 mins

Iterator variable in Terraform - Commands & Configuration

Choose your learning style10 modes available
Introduction
When you want to create multiple similar resources in Terraform without repeating code, you use an iterator variable. It helps you loop over a list or map and create resources dynamically.
When you need to create several virtual machines with similar settings but different names.
When you want to create multiple storage buckets with different configurations in one go.
When you have a list of subnets and want to create a resource for each subnet automatically.
When you want to avoid copying and pasting resource blocks for each item in a list.
When you want to manage infrastructure efficiently by writing less code.
Config File - main.tf
main.tf
variable "server_names" {
  type    = list(string)
  default = ["app-server-1", "app-server-2", "app-server-3"]
}

resource "aws_instance" "example" {
  for_each = toset(var.server_names)

  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  tags = {
    Name = each.value
  }
}

This Terraform file defines a variable server_names as a list of server names. The aws_instance resource uses for_each to loop over each server name. The iterator variable each.value represents the current server name in the loop and is used to set the tag Name for each instance.

Commands
This command initializes the Terraform working directory. It downloads the necessary provider plugins and prepares the environment for deployment.
Terminal
terraform init
Expected OutputExpected
Initializing the backend... Initializing provider plugins... - Finding latest version of hashicorp/aws... - Installing hashicorp/aws v4.0.0... - Installed hashicorp/aws v4.0.0 (signed by HashiCorp) Terraform has been successfully initialized! You may now begin working with Terraform. Try running "terraform plan" to see any changes that are required for your infrastructure.
This command shows what Terraform will do before applying changes. It previews the creation of multiple AWS instances using the iterator variable.
Terminal
terraform plan
Expected OutputExpected
An execution plan has been generated and is shown below. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # aws_instance.example["app-server-1"] will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + tags = { + "Name" = "app-server-1" } } # aws_instance.example["app-server-2"] will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + tags = { + "Name" = "app-server-2" } } # aws_instance.example["app-server-3"] will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + tags = { + "Name" = "app-server-3" } } Plan: 3 to add, 0 to change, 0 to destroy.
This command applies the planned changes and creates the AWS instances. The flag -auto-approve skips the confirmation prompt for faster deployment.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example["app-server-1"]: Creating... aws_instance.example["app-server-2"]: Creating... aws_instance.example["app-server-3"]: Creating... aws_instance.example["app-server-1"]: Creation complete after 10s [id=i-0123456789abcdef0] aws_instance.example["app-server-2"]: Creation complete after 10s [id=i-0123456789abcdef1] aws_instance.example["app-server-3"]: Creation complete after 10s [id=i-0123456789abcdef2] Apply complete! Resources: 3 added, 0 changed, 0 destroyed.
→
-auto-approve - Automatically approve the apply without asking for confirmation
This command lists all resources currently managed by Terraform. It shows the three instances created using the iterator variable.
Terminal
terraform state list
Expected OutputExpected
aws_instance.example["app-server-1"] aws_instance.example["app-server-2"] aws_instance.example["app-server-3"]
Key Concept

If you remember nothing else from this pattern, remember: the iterator variable 'each' lets you loop over collections to create multiple resources efficiently in Terraform.

Common Mistakes
Using 'count' instead of 'for_each' when resource names need to be unique.
'count' creates resources indexed by number, which can make unique naming harder and less readable.
Use 'for_each' with a set or map and use 'each.key' for unique resource identification.
Trying to use 'each' outside of a 'for_each' or 'count' block.
The 'each' variable only exists inside resources using 'for_each' or 'count'. Using it elsewhere causes errors.
Only use 'each' inside resource blocks that have 'for_each' or 'count' defined.
Using a list directly in 'for_each' without converting to a set.
'for_each' requires a set or map for unique keys; using a list directly can cause errors.
Convert lists to sets using 'toset()' before using them in 'for_each'.
Summary
Define a list variable with the names or identifiers for your resources.
Use 'for_each' in the resource block to loop over the list converted to a set.
Use 'each.key' or 'each.value' inside the resource to access the current item in the loop.
Run 'terraform init' to prepare the environment, 'terraform plan' to preview changes, and 'terraform apply' to create resources.
Use 'terraform state list' to verify the created resources.

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