Skip to main content
InterviewHubPRO
Section Overview
Q12

Question 12 of 50

Part 1: Terraform Core Architecture, HCL & Providers (1 - 15)

24%
Terraform & IaC (50 Qs)•Part 1: Terraform Core Architecture, HCL & Providers (1 - 15)

Compare Meta-Arguments: `count` vs. `for_each` (Why is `for_each` preferred for dynamic resources)?

senior LevelCode ExampleFormsCI/CD & DevOpsSystem Design

In Simple Words:

  • count: Creates resources indexed by integer: aws_subnet.public[0], [1], [2].
    • Severe Risk: If you remove an item from the middle of a list, Terraform shifts array indexes, causing unnecessary destructions and recreations of existing resources!
  • for_each: Iterates over maps or sets: aws_subnet.public["us-east-1a"].
    • Resources are keyed by immutable identifiers. Adding or removing elements only modifies that specific key, leaving all other resources untouched.
hcl
# Preferred: for_each with a map
variable "subnets" {
  type = map(string)
  default = {
    "subnet-a" = "10.0.1.0/24"
    "subnet-b" = "10.0.2.0/24"
  }
}

resource "aws_subnet" "app" {
  for_each          = var.subnets
  vpc_id            = aws_vpc.main.id
  cidr_block        = each.value
  availability_zone = "us-east-1a"
  tags              = { Name = each.key }
}