As asked
You need to create one S3 bucket per environment from a list. Compare count and for_each. Which do you use and why? What breaks if you use count and then remove an item from the middle of the list?
Sample answer outline
Candidate must explain that count uses integer indices so removing an item from the middle shifts all subsequent indices, causing Terraform to plan destroy-and-recreate for every resource after the removed one. for_each uses map keys as stable identifiers so removing one key only destroys that resource. Always prefer for_each when the set of items may change.
Reference implementation (hcl)
variable "environments" {
default = ["dev", "staging", "prod"]
}
# count approach - fragile
resource "aws_s3_bucket" "env_bucket_count" {
count = length(var.environments)
bucket = "myapp-${var.environments[count.index]}"
}
# for_each approach - stable
resource "aws_s3_bucket" "env_bucket" {
for_each = toset(var.environments)
bucket = "myapp-${each.key}"
}Expect these follow-ups
- How do you convert a list to a set for use with for_each?
- What does toset() do and when is it needed?