For Loops
When you need to create multiple similar resources (like several subnets or IAM users), you could copy‑paste, but that’s error‑prone. Terraform provides
count and for_each to iterate over lists and maps.Using
countThe
count meta‑argument creates a number of instances of a resource. You can access the index with count.index.variable "subnet_cidrs" {
type = list(string)
default = ["10.0.1.0/24", "10.0.2.0/24", "10.0.3.0/24"]
}
resource "aws_subnet" "main" {
count = length(var.subnet_cidrs)
cidr_block = var.subnet_cidrs[count.index]
vpc_id = aws_vpc.main.id
}Using
for_eachfor_each works with a map or set of strings. It creates one resource per item, and you can access the key and value with each.key and each.value. It’s more flexible than count when you need to delete specific items.variable "subnets" {
type = map(object({
cidr = string
az = string
}))
default = {
"subnet1" = { cidr = "10.0.1.0/24", az = "us-east-1a" }
"subnet2" = { cidr = "10.0.2.0/24", az = "us-east-1b" }
}
}
resource "aws_subnet" "main" {
for_each = var.subnets
cidr_block = each.value.cidr
availability_zone = each.value.az
vpc_id = aws_vpc.main.id
tags = { Name = each.key }
}for Expressions in LocalsYou can transform lists or maps using
for expressions.locals {
instance_names = [for i in range(3) : "web-${i}"]
# result: ["web-0", "web-1", "web-2"]
subnet_map = { for idx, cidr in var.subnet_cidrs : idx => cidr }
}When to Use Count vs For_Each
- count: When you need a simple list of identical resources and order matters.
- for_each: When resources have distinct identifiers (like subnet names) and you may need to remove individual items without affecting others.
Two Minute Drill
countcreates N copies; access withcount.index.for_eachiterates over maps/sets; access witheach.keyandeach.value.- Use
forexpressions to transform collections in locals. - Prefer
for_eachwhen resource identity matters for updates.
Need more clarification?
Drop us an email at career@quipoinfotech.com
