A resource uses count = length(var.queue_names) with ["orders", "billing", "audit"]. After billing is removed from the list, the plan replaces the audit queue and destroys another instance. Why does this happen, and what prevents it?
Select an answer to reveal the explanation.
Short Explanation
count numbers your instances like seats in a row: pull someone out of seat 1 and everyone after them shuffles down. for_each puts names on the seats so nobody moves. The trap is thinking you can fix it with a lifecycle setting when the real problem is how the instances are addressed.
Full Explanation
With count, instances are identified by integer index, so orders, billing and audit live at [0], [1] and [2]. Removing billing shifts audit to [1]; Terraform compares [1] in state, which is billing, with the new configuration, which is audit, and plans a change, here a replacement because the name forces a new queue, and it then destroys [2], which no longer exists in configuration. Switching to for_each over toset(var.queue_names) keys each instance by its name, so removing billing plans exactly one destroy and leaves the other queues untouched; moved blocks can migrate existing indexed instances to the new keys without recreating them. Terraform does not sort list elements for count; it uses them in their given order. Changing the count value adds or removes instances at the end; it does not by itself replace every instance. create_before_destroy changes the ordering of a replacement, not whether one is needed. ignore_changes on the name would hide the mismatch and leave each queue configured with the wrong name rather than fix the addressing. Exam caveat: count remains appropriate for identical, interchangeable instances. Operational check: after converting, run terraform plan and confirm it proposes moves or no changes for queues that remain.