0
0
Terraformcloud~5 mins

Iterator variable in Terraform - Commands & Configuration

Choose your learning style9 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.