Using Terraform for_each to Dynamically Provision Similar Resources
Learn how Terraform's for_each meta-argument lets you create multiple similar resources from a map or set, reducing duplication and giving precise control over each instance.
28 Oct 2025, 18:44 UTC

The Problem: Repeating Similar Resources
When you need several AWS EC2 instances that differ only by a tag or a small attribute, writing a separate aws_instance block for each one leads to verbose configuration and a higher chance of drift.
How for_each Solves It
The for_each meta‑argument tells Terraform to create one resource instance for every key in a map or every element in a set. Terraform tracks each instance separately in the state file, so a change to one key affects only that instance and the plan shows a precise diff.
Worked Example: AWS EC2 Instances from a Map
Assume you want three t3.micro instances named web, app and db. Define a variable that maps a logical name to the desired tag:
variable "instance_names" {
type = map(string)
default = {
web = "web-server"
app = "app-server"
db = "database"
}
}
Then use for_each on the resource:
resource "aws_instance" "example" {
for_each = var.instance_names
ami = data.aws_ami.amazon_linux.id
instance_type = "t3.micro"
tags = {
Name = each.value
Role = each.key
}
}
Run terraform init and terraform plan in a directory with appropriate AWS provider configuration. The plan will list three resources addressed as aws_instance.example["web"], aws_instance.example["app"] and aws_instance.example["db"]. No changes are shown for existing keys if you later run terraform plan after applying.
To add a fourth instance, edit the map:
variable "instance_names" {
default = {
web = "web-server"
app = "app-server"
db = "database"
cache = "cache-node"
}
}
Considerations and Limitations
- The map or set supplied to
for_eachmust be known during the planning phase. Values that depend on apply‑time results (for example, an ID returned by another resource) will cause Terraform to fail with "invalid for_each argument". - Changing a key after resources are created forces Terraform to destroy the instance associated with the old key and create a new one with the new key, which may lead to downtime.
- Because each instance gets its own state address, the state file grows linearly with the number of entries. Very large maps (hundreds or thousands of items) can make planning slower.
Actionable Closing
If you find yourself copying and pasting resource blocks, try extracting the variable parts into a map or set and switch to for_each. Start with a small test, verify the plan shows the expected instances, and then adopt the pattern for other resource types such as security groups, Kubernetes deployments, or Azure virtual networks.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.