0
0
Terraformcloud~5 mins

For_each for map-based instances in Terraform - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you want to create multiple similar resources in Terraform, you can use for_each with a map to define each instance with a unique key and specific values. This helps manage resources efficiently without repeating code.
When you need to create multiple virtual machines with different names and settings in one configuration file.
When you want to manage several cloud storage buckets, each with unique properties, using a single resource block.
When you want to deploy multiple network interfaces with different IP addresses using one resource definition.
When you want to update or delete specific instances easily by referring to their keys in the map.
When you want to keep your Terraform code clean and avoid duplication by looping over a map of configurations.
Config File - main.tf
main.tf
variable "servers" {
  type = map(object({
    instance_type = string
    ami           = string
  }))
  default = {
    server1 = {
      instance_type = "t2.micro"
      ami           = "ami-0c55b159cbfafe1f0"
    }
    server2 = {
      instance_type = "t2.small"
      ami           = "ami-0c55b159cbfafe1f0"
    }
  }
}

resource "aws_instance" "example" {
  for_each = var.servers

  ami           = each.value.ami
  instance_type = each.value.instance_type
  tags = {
    Name = each.key
  }
}

This Terraform file defines a variable servers as a map where each key is a server name and the value is an object with instance details.

The aws_instance resource uses for_each to create one instance per map entry.

each.key is the server name, and each.value holds the instance properties like AMI and instance type.

Commands
This command initializes the Terraform working directory, downloads 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 create or change based on the configuration, without making any actual changes yet.
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["server1"] will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.micro" + tags = { + "Name" = "server1" } } # aws_instance.example["server2"] will be created + resource "aws_instance" "example" { + ami = "ami-0c55b159cbfafe1f0" + instance_type = "t2.small" + tags = { + "Name" = "server2" } } Plan: 2 to add, 0 to change, 0 to destroy.
This command applies the planned changes and creates the resources defined in the configuration automatically without asking for confirmation.
Terminal
terraform apply -auto-approve
Expected OutputExpected
aws_instance.example["server1"]: Creating... aws_instance.example["server2"]: Creating... aws_instance.example["server1"]: Creation complete after 10s [id=i-0abcd1234efgh5678] aws_instance.example["server2"]: Creation complete after 12s [id=i-0abcd1234efgh5679] Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
-auto-approve - Skips interactive approval before applying changes
This command lists all resources currently tracked in Terraform's state, showing the created instances with their keys.
Terminal
terraform state list
Expected OutputExpected
aws_instance.example["server1"] aws_instance.example["server2"]
Key Concept

If you remember nothing else from this pattern, remember: using for_each with a map lets you create multiple uniquely named resources from one block by looping over keys and values.

Common Mistakes
Using a list instead of a map with for_each when unique keys are needed
Lists use numeric indexes which can cause resource replacement if order changes, making management harder.
Use a map with meaningful keys to ensure stable resource identities and easier updates.
Trying to access each.key or each.value outside a for_each resource block
each.key and each.value only exist inside the resource using for_each, so referencing them elsewhere causes errors.
Use these expressions only inside the resource block that has for_each defined.
Summary
Define a map variable with keys as resource names and values as their properties.
Use for_each in the resource block to loop over the map and create one resource per key.
Run terraform init, plan, and apply to deploy all instances with unique names and settings.