November 13, 2026 路 #58
Remove one bucket, replace three
Someone removed "staging" from the list. The plan now wants to destroy and recreate the buckets after it. Which line causes it?
variable "envs" {
default = ["dev", "staging", "qa", "prod"]
}
resource "aws_s3_bucket" "logs" {
count = length(var.envs)
bucket = "acme-logs-${var.envs[count.index]}"
}Next puzzle in UTC
One try. The first answer sticks.
How to fix it
The buckets live at logs[0] to logs[3]. Remove staging and qa moves to index 1 with a new name, so Terraform replaces it, and prod too. Key them with for_each.
Terraform tracks count resources by number. Before the change, logs[1] is staging, logs[2] is qa, logs[3] is prod. After removing staging, logs[1] should be qa and logs[2] should be prod. Bucket names cannot change in place, so Terraform plans to replace logs[1] and logs[2] and destroy logs[3]: it deletes the existing staging, qa, and prod buckets and creates new qa and prod buckets. With a non-empty bucket the destroy fails, and with force_destroy it deletes logs.
Fix
resource "aws_s3_bucket" "logs" {
for_each = toset(var.envs)
bucket = "acme-logs-${each.key}"
}
Addresses become logs["qa"], stable no matter the order. Migrate existing ones with moved blocks, for example from = aws_s3_bucket.logs[2] and to = aws_s3_bucket.logs["qa"], so the switch is a no-op plan.