Terraform looping differences between count and for_each

Boonyarit Kunchorn
2 min readJul 27, 2024

1. Looping with count

The count parameter allows you to create multiple instances of a resource. It's a simple integer-based loop that iterates a specified number of times.

Example with count

variable "instance_count" {
type = number
default = 3
}
resource "aws_instance" "example" {
count = var.instance_count
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "example-instance-${count.index}"
}
}

In this example:

  • The aws_instance resource will be created three times.
  • The count.index provides a unique index for each instance (0, 1, 2).

2. Looping with for_each

The for_each parameter allows you to iterate over a collection, such as a list or a map. This method is more flexible than count as it works with named elements rather than just indices.

Example with for_each (using a list)

variable "instance_names" {
type = list(string)
default = ["instance1", "instance2", "instance3"]
}
resource "aws_instance" "example" {
for_each = toset(var.instance_names)
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = each.key
}
}

In this example:

  • The aws_instance resource will be created for each item in the instance_names list.
  • The each.key provides the current item from the list, which is used as the instance name.

Example with for_each (using a map)

variable "instance_config" {
type = map(object({
instance_type = string
ami = string
}))
default = {
instance1 = { instance_type = "t2.micro", ami = "ami-0c55b159cbfafe1f0" }
instance2 = { instance_type = "t2.small", ami = "ami-0c55b159cbfafe1f0" }
}
}
resource "aws_instance" "example" {
for_each = var.instance_config
ami = each.value.ami
instance_type = each.value.instance_type
tags = {
Name = each.key
}
}

In this example:

  • The aws_instance resource will be created for each key-value pair in the instance_config map.
  • The each.key provides the key (e.g., "instance1", "instance2"), and each.value provides the value (the configuration object).

Key Differences

  • count: Uses an integer for iteration, which is straightforward but less flexible. Suitable for simple, repeated resource creation where only the index is needed.
  • for_each: Uses a collection (list, map, or set) for iteration, allowing for more complex and flexible resource creation. Useful when you need to handle named items or more complex configurations.

By choosing the appropriate looping method (count or for_each), you can create Terraform configurations that are more efficient, readable, and maintainable.

--

--