What is count and for_each in Terraform?
Answer
count and for_each are meta-arguments for creating multiple instances of a resource. count: create N identical resources. resource "aws_instance" "web" { count = 3; ... }. Reference by index: aws_instance.web[0].id. Problem: if you remove an item from the middle, all subsequent resources are renamed and recreated. for_each: create resources from a map or set. for_each = { "web" = "t3.micro", "db" = "t3.large" }. Reference by key: aws_instance.servers["web"].id. each.key and each.value are available inside the block. Advantage over count: removing one item from the map only affects that specific resource. Prefer for_each over count when resources have meaningful identities. Use count only for truly homogeneous resources (like N identical replicas).