0
0
Terraformcloud~30 mins

Count vs for_each decision in Terraform - Hands-On Comparison

Choose your learning style9 modes available
Count vs for_each decision
📖 Scenario: You are setting up cloud resources using Terraform. You want to create multiple virtual machines (VMs) in a cloud environment. Some VMs are identical, and some have unique names and settings.
🎯 Goal: Learn when to use count and when to use for_each in Terraform to create multiple resources efficiently.
📋 What You'll Learn
Create a variable with a list of VM names
Create a variable with the number of identical VMs
Use count to create identical VMs
Use for_each to create uniquely named VMs
💡 Why This Matters
🌍 Real World
Cloud engineers often need to create multiple resources that are either identical or unique. Knowing when to use <code>count</code> or <code>for_each</code> helps manage infrastructure efficiently.
💼 Career
Understanding <code>count</code> and <code>for_each</code> is essential for Terraform users to write scalable and maintainable infrastructure code.
Progress0 / 4 steps
1
Create a list variable with VM names
Create a Terraform variable called vm_names with the list ["web1", "web2", "db1"].
Terraform
Need a hint?

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

2
Create a variable for identical VM count
Create a Terraform variable called vm_count with the default value 3.
Terraform
Need a hint?

Use a variable block with type = number and default = 3.

3
Use count to create identical VMs
Create a resource block resource "azurerm_virtual_machine" "identical_vm" that uses count = var.vm_count and sets name = "vm-${count.index + 1}".
Terraform
Need a hint?

Use count = var.vm_count and name = "vm-${count.index + 1}" inside the resource block.

4
Use for_each to create uniquely named VMs
Create a resource block resource "azurerm_virtual_machine" "unique_vm" that uses for_each = toset(var.vm_names) and sets name = each.key.
Terraform
Need a hint?

Use for_each = toset(var.vm_names) and name = each.key inside the resource block.