0
0
Terraformcloud~30 mins

For_each for map-based instances in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
For_each for map-based instances
📖 Scenario: You are setting up multiple virtual machines (instances) in the cloud. Each instance has a unique name and a specific size. You want to create these instances efficiently using Terraform.
🎯 Goal: Create a Terraform configuration that uses for_each to deploy multiple instances from a map of instance names and sizes.
📋 What You'll Learn
Define a map variable with instance names as keys and sizes as values
Use for_each in the resource block to create instances from the map
Assign the instance name and size from the map values
Output the instance IDs after creation
💡 Why This Matters
🌍 Real World
Cloud engineers often need to deploy multiple similar resources with different configurations. Using for_each with maps helps manage these resources efficiently.
💼 Career
Understanding for_each with maps in Terraform is essential for infrastructure as code roles, enabling scalable and maintainable cloud deployments.
Progress0 / 4 steps
1
Define the instances map variable
Create a Terraform variable called instances of type map(string) with these exact entries: "web1" = "small", "web2" = "medium", "db1" = "large".
Terraform
Need a hint?

Use variable block with type = map(string) and set default to the given map.

2
Add a local variable for instance configuration
Create a local variable called instance_config that references the var.instances variable.
Terraform
Need a hint?

Use a locals block to assign instance_config to var.instances.

3
Create instances using for_each
Create a resource block resource "aws_instance" "example" that uses for_each = local.instance_config. Set the instance_type to each.value and the tags with a Name key set to each.key.
Terraform
Need a hint?

Use for_each with local.instance_config. Set instance_type to each.value and tag the instance with Name = each.key.

4
Output the instance IDs
Create an output called instance_ids that outputs a map of instance names to their IDs using aws_instance.example and for_each.
Terraform
Need a hint?

Use an output block with a for expression to map instance names to their IDs.