Create many resources from one block. Use count for simple numbered copies, for_each for a keyed set, and conditional creation to turn a resource on or off.
Why: count makes N identical-ish copies of a resource from a single block. Inside, count.index is the current number (starting at 0), so each copy can differ. The resources become a list — local_file.page[0], local_file.page[1], and so on.
resource "local_file" "page" {
count = 3
filename = "page-${count.index}.txt"
content = "This is page number ${count.index}"
}Why: count addresses by position, which breaks badly when you remove a middle item — everything after it shifts and gets recreated. for_each addresses by KEY instead, over a map or set. Removing one entry touches only that one. Prefer for_each whenever the items have natural identifiers. each.key and each.value give the current pair.
resource "local_file" "config" {
for_each = {
web = "port=80"
api = "port=8080"
db = "port=5432"
}
filename = "${each.key}.conf"
content = each.value
}Note: the rule of thumb. Use count for a simple number of interchangeable copies, or to toggle a resource on/off. Use for_each when each instance has a stable identity — a name, an environment, a region — so adding or removing one does not disturb the others.
count ──▶ ordered list, addressed by INDEX [0], [1], [2]
──▶ removing a middle item shifts & recreates the rest
for_each ──▶ keyed map, addressed by KEY ["web"], ["api"]
──▶ removing one item touches only that oneWhy: a common pattern uses count with a bool to create a resource only when wanted — count = 1 to make it, 0 to skip it. This is how you make optional infrastructure that a variable turns on or off, without commenting code in and out.
variable "create_backup" {
type = bool
default = false
}
resource "local_file" "backup" {
count = var.create_backup ? 1 : 0 # 1 = create, 0 = skip
filename = "backup.txt"
content = "backup enabled"
}