Course contentsShow
← Cloud and Infrastructure
Lesson 743 of 2,98914. Terraform FundamentalsFree lesson

Resource Meta-Arguments: for_each

Use for_each to create resources based on a map or set, enabling more flexible multi-resource patterns.

Resource Meta-Arguments: for_each

What You'll Learn

You'll learn how to use for_each to create multiple similar resources from a map or set, giving you more control and flexibility than count.

Why for_each Matters

While count lets you create multiple copies of a resource using a numeric index, for_each uses keys instead of numbers. This makes your infrastructure code more maintainable and prevents Terraform from destroying and recreating resources when you add or remove items from the middle of a collection.

Think of it like labeling storage boxes: count labels them "Box 0, Box 1, Box 2" (shifting all labels if you remove Box 1), while for_each labels them "John's Box, Sarah's Box, Mike's Box" (keeping identities stable).

Using for_each with Maps

When you use for_each with a map, each resource instance gets a unique key:

resource "aws_instance" "servers" {
  for_each = {
    web  = "t2.micro"
    api  = "t2.small"
    db   = "t2.medium"
  }

  instance_type = each.value
  ami           = "ami-12345678"
  
  tags = {
    Name = "${each.key}-server"
  }
}

Inside the resource, each.key gives you the map key ("web", "api", "db") and each.value gives you the corresponding value.

Using for_each with Sets

You can also use a set of strings:

resource "aws_s3_bucket" "departments" {
  for_each = toset(["engineering", "marketing", "finance"])
  
  bucket = "${each.key}-data-bucket"
}

With sets, each.key and each.value are the same.

Why Choose for_each Over count?

Use for_each when each resource has a meaningful identifier beyond just its position in a list. This prevents unnecessary resource replacements when your collection changes.

Key Takeaway: for_each creates resources based on map keys or set values, giving each instance a stable identity that survives collection changes better than numeric indexing.