Interview Infrastructure as Code (Terraform, Ansible)

What problem does for_each solve that count creates when removing items?

Infrastructure as Code (Terraform, Ansible) · Basic level

Answer

for_each solves the index-shift problem caused by count. With count, removing item 1 from a list can shift every later index and cause unnecessary replacement. With for_each, each object is addressed by a stable key, so removing one key does not rename the rest.

Technical explanation

Index shifts are especially dangerous for IAM users, security group rules, subnets, and DNS records.

Maps with stable keys express identity better than positional lists.

If migrating from count to for_each, use moved blocks or state moves to avoid replacement.

Keep Terraform's ownership boundary clear: one state should own a resource or field, and other tools should consume published outputs instead of modifying it.

Use fmt, validate, linting, policy checks, plan review, and state locking before production applies.

Design for small blast radius by splitting state around lifecycle, permissions, and recovery boundaries.

Hands-on example

1. Model repeated resources for: What problem does for_each solve that count creates when removing items?

2. Prefer stable keys with for_each:

variable "subnets" {

type = map(object({ cidr = string, az = string }))

}

resource "aws_subnet" "private" {

for_each = var.subnets

vpc_id = aws_vpc.main.id

cidr_block = each.value.cidr

availability_zone = each.value.az

tags = { Name = "private-${each.key}" }

}

3. For nested blocks, use dynamic only when the input list genuinely drives repeated nested configuration:

dynamic "ingress" {

for_each = var.ingress_rules

content { from_port = ingress.value.port to_port = ingress.value.port protocol = "tcp" cidr_blocks = ingress.value.cidrs }

}

4. Remove one key and run plan; confirm only that keyed instance is affected rather than later list indexes shifting.

Preparing for an interview?

Check how well your resume matches the role with our free resume checker— match score, ATS check, and the skills you're missing.

More Infrastructure as Code (Terraform, Ansible) interview questions

← All Infrastructure as Code (Terraform, Ansible) questions