📖 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
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
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
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
Hint
Use for_each = toset(var.vm_names) and name = each.key inside the resource block.
Practice
(1/5)
1. Which Terraform argument should you use when you want to create 3 identical resources without unique identifiers?
easy
A. count = 3
B. for_each = {}
C. for_each = toset(["a", "b", "c"])
D. count = 0
Solution
Step 1: Understand the purpose of count
count creates multiple copies of a resource by number, perfect for identical resources.
Step 2: Compare with for_each
for_each is used when you want unique keys or values to identify each resource, not just copies.
Final Answer:
count = 3 -> Option A
Quick Check:
Simple copies = count [OK]
Hint: Use count for number copies, for_each for unique keys [OK]
Common Mistakes:
Using for_each when only number copies are needed
Setting count to zero expecting resources
Confusing sets with counts
2. Which of the following is the correct syntax to create resources using for_each with a map in Terraform?
easy
A. resource "aws_instance" "example" { for_each = ["a", "b"] }
B. resource "aws_instance" "example" { for_each = "string" }
C. resource "aws_instance" "example" { count = 2 }