You inherit this block, already applied with var.names = ["logs", "backups", "exports"]:
resource "aws_s3_bucket" "b" {
count = length(var.names)
bucket = "acme-${var.names[count.index]}"
}
A teammate deletes "logs" from the list and runs terraform plan. Walk me through what the plan shows, and why.
- Terraform re-indexes state automatically so only
acme-logsis destroyed. Terraform never re-addresses state on its own; that takesmovedblocks orterraform state mv. - The shifted buckets are renamed in place with a
~update. S3 bucket names are immutable, so a name change is a replacement (-/+) and the plan marks the line# forces replacement. -
aws_s3_bucket.b[2]is destroyed, and every instance whose index now maps to a different name is planned as-/+(destroy and recreate), because count addresses are positional andbucketis a force-new argument. Removing an element shifts every later name down one index; each shifted instance's bucket name changes, and bucket names cannot be changed in place, so Terraform replaces them. - Only the
acme-logsbucket is destroyed; the others are untouched because Terraform matches instances by name. count instances are tracked by index, not by any argument's value; only for_each tracks by key.
count tracks buckets by position, so removing one name shifts the rest and Terraform destroys and recreates the shifted buckets.
count gives instances positional addresses (b[0], b[1], ...). Deleting an element does not delete "that instance"; it shifts every later element to a lower index, so the configuration at b[1] now describes a different bucket than the state at b[1], and a force-new argument change means destroy-and-recreate. for_each = toset(var.names) keys instances by value (b["logs"]), so removing a name touches only that key. Converting an existing count resource to for_each needs moved blocks (from = aws_s3_bucket.b[0], to = aws_s3_bucket.b["logs"]) or the same cascade happens once during the conversion. Interviewers also listen for the blast-radius aside: destroying a non-empty bucket fails unless force_destroy = true, which is the only thing that would have stopped this apply.
Answering that only the removed bucket is destroyed, because you are matching by name in your head while Terraform matches by index; or recommending for_each without moved blocks, which recreates every bucket once on the way over.