Skip to content
CloudOps
Newsletter
All prompts
AI for Terraform Difficulty: Intermediate ClaudeChatGPT

Terraform for_each Key Stability Audit Prompt

Diagnose why a for_each resource is destroying and recreating instances on every plan because its map keys are unstable or derived from computed values.

Target user
Terraform engineers debugging churn in for_each resources
Difficulty
Intermediate
Tools
Claude, ChatGPT

The prompt

You are a senior Terraform engineer who has debugged dozens of for_each loops that thrash state because their keys are not stable across plans.

I will provide:
- The resource block using for_each
- The variable or local feeding for_each
- A snippet of terraform plan showing the destroy/create churn

Your job:

1. **Identify the key source** — determine whether for_each iterates a map, a set of strings, or a list run through toset(); explain that the map key (or set element) becomes the resource instance address.
2. **Find instability** — flag keys derived from computed/"known after apply" values, list indices, timestamps, random ids, or interpolated attributes that shift between runs.
3. **Explain the churn** — show how a changed key forces Terraform to plan a destroy of the old address and a create of the new one, even when the underlying resource is logically identical.
4. **Propose stable keys** — recommend deterministic, human-meaningful keys (e.g. names, slugs) and refactor the input so keys never depend on apply-time data.
5. **Plan the migration** — write `moved` blocks (or `terraform state mv` commands as a fallback) to re-key existing instances WITHOUT destroying them.
6. **Verify with plan** — instruct me to run `terraform plan` and confirm the result is a no-op or pure move, never a destroy/create.
7. **Guardrails** — note where set-of-objects vs map-of-objects changes behavior.

Output as: (a) root-cause explanation, (b) corrected HCL, (c) moved blocks, (d) the exact plan output I should expect.

Do not apply anything until the plan shows zero unintended destroys; if a destroy is unavoidable, stop and ask me first.
Newsletter

Free: the DevOps AI Incident-Triage Cheat Sheet

Subscribe and we’ll send you the one-page cheat sheet — plus weekly AI prompts, automation ideas, and tool reviews for infrastructure engineers. One email a week. No spam, unsubscribe anytime.

  • AI Incident-Triage Cheat Sheet (PDF)
  • Access to 1,603 DevOps AI prompts
  • One practical workflow email per week