0
0
Terraformcloud~3 mins

Why For_each for map-based instances in Terraform? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could create dozens of servers with one simple list instead of dozens of repeated blocks?

The Scenario

Imagine you need to create multiple cloud servers, each with different names and settings. You write each server's setup by hand, copying and changing details for every one.

The Problem

This manual way is slow and tiring. If you want to add or change a server, you must edit many places. Mistakes happen easily, like using the wrong name or forgetting a setting.

The Solution

Using for_each with a map lets you write one block of code that automatically creates all servers. You just list the servers and their details once, and Terraform handles the rest safely and quickly.

Before vs After
Before
resource "aws_instance" "server1" {
  name = "app1"
}
resource "aws_instance" "server2" {
  name = "app2"
}
After
resource "aws_instance" "servers" {
  for_each = {
    app1 = "details1",
    app2 = "details2"
  }
  name = each.key
}
What It Enables

You can manage many cloud resources easily and reliably by changing just one map, saving time and avoiding errors.

Real Life Example

A company needs to launch servers in different regions with unique names. Using for_each with a map, they define all servers once and deploy them all at once without repeating code.

Key Takeaways

Manual setup is slow and error-prone.

for_each with maps automates resource creation.

It makes managing many instances simple and safe.