Interview Prep/Terraform/Resources Variables and Expressions

You need three identical web servers. How do you declare them, and what is the catch with `count`?

BeginnerScenarioResources Variables and Expressions
Answer

Situation read → Simple repetition, but index-based identity is fragile.

What I'd do →

  1. Use count = 3 and reference instances as aws_instance.web[0].
  2. Prefer for_each if instances need individual identities.
resource "aws_instance" "web" {
  count         = 3
  ami           = data.aws_ami.al2023.id
  instance_type = "t3.micro"
  tags          = { Name = "web-${count.index}" }
}

Why → With count, removing item 1 from a list shifts later indexes, so Terraform wants to destroy and recreate resources that didn't really change.

Interview tip → "Count for N identical things, for_each for named things."

All Terraform questions Roadmap: Terraform

More on Resources Variables and Expressions