0
0
Terraformcloud~30 mins

Iterator variable in Terraform - Mini Project: Build & Apply

Choose your learning style9 modes available
Iterator Variable in Terraform
📖 Scenario: You are setting up a simple cloud infrastructure using Terraform. You want to create multiple virtual machines (VMs) with specific names and sizes.
🎯 Goal: Build a Terraform configuration that uses an iterator variable to create multiple VMs with different names and sizes.
📋 What You'll Learn
Create a variable called vm_specs as a list of maps with exact entries
Create a local variable called vm_names that extracts VM names from vm_specs
Use a for expression with an iterator variable spec to create a map of VM sizes keyed by VM names
Define a resource azurerm_virtual_machine using the iterator variable spec in a for_each block
💡 Why This Matters
🌍 Real World
This project shows how to use iterator variables in Terraform to manage multiple cloud resources efficiently.
💼 Career
Understanding iterator variables is essential for cloud engineers to write scalable and maintainable infrastructure code.
Progress0 / 4 steps
1
Create the VM specifications variable
Create a Terraform variable called vm_specs as a list of maps with these exact entries: { name = "vm1", size = "Standard_B1s" }, { name = "vm2", size = "Standard_B2s" }, and { name = "vm3", size = "Standard_B1ms" }.
Terraform
Need a hint?

Define a variable with type list of objects containing name and size keys.

2
Create a local variable for VM names
Create a local variable called vm_names that extracts the name from each element in the var.vm_specs list using a for expression with iterator variable spec.
Terraform
Need a hint?

Use a for expression with spec as iterator to get names.

3
Create a map of VM sizes keyed by VM names
Create a local variable called vm_sizes_map that uses a for expression with iterator variable spec over var.vm_specs to create a map where keys are spec.name and values are spec.size.
Terraform
Need a hint?

Use a for expression with spec to build a map of names to sizes.

4
Define VM resources using the iterator variable
Define a resource block resource "azurerm_virtual_machine" "example" that uses for_each = { for spec in var.vm_specs : spec.name => spec }. Inside the resource, set name = each.key and vm_size = each.value.size to use the iterator variable spec indirectly via each.
Terraform
Need a hint?

Use for_each with a map from spec.name to spec. Use each.key and each.value.size inside the resource.