Skip to content
🎉 Launch sale:50% off everything over $22 — automatically applied at checkout· ends Aug 2Shop the sale →
DevOps AI ToolKit
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.

Run this prompt with AI

Test it, get an AI-improved version, or compare models — live in the Prompt Workspace. No copy-paste.

Related prompts

More Terraform prompts & error guides

Browse every Terraform prompt and troubleshooting guide in one place.

Free download · 368-page PDF

Reading prompts? Get all 500 in one free PDF

500 battle-tested, copy-paste AI prompts engineered by a senior systems engineer — every one with fill-in placeholders and safety/back-out notes. Drop your email and it's yours.

  • 500 prompts: Linux · Kubernetes · Terraform · OpenStack · GitLab · Docker · Monitoring · Incident Response
  • Instant PDF download — yours free, forever
  • Plus one practical AI-workflow email a week (no spam)

Single opt-in · unsubscribe anytime · no spam.