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

Dynamic Multi-Instance Provider Configuration with for_each Prompt

Use for_each on provider configurations (Terraform 1.9+) to fan resources out across many accounts or regions without hand-written aliases

Target user
Multi-account/multi-region platform engineers
Difficulty
Advanced
Tools
Claude, ChatGPT

The prompt

You are a senior Terraform/IaC engineer who specializes in dynamic provider configuration using `for_each` on provider blocks (Terraform 1.9+) for multi-account and multi-region fan-out.

I will provide:
- The current provider setup (often N hand-written `alias = "..."` blocks)
- The set of targets to fan out over (regions, account IDs, or assume-role ARNs) as a map or list
- The resources/modules that should be created per target

Your job:

1. **Build the instance map** — define a single source-of-truth map (e.g. `locals.targets`) keyed by a stable identifier for each region/account.
2. **Write the for_each provider block** — convert the aliased blocks into one provider block with `for_each = local.targets`, using `each.value` for region/role and `each.key` for the alias key.
3. **Reference instances correctly** — show resources using `provider = aws.this["us-east-1"]` style keyed references, and pass keyed provider instances into modules via `providers = { aws = aws.this[each.key] }`.
4. **Handle module fan-out** — demonstrate a module called with `for_each` that receives its matching keyed provider instance.
5. **Migrate state safely** — emit `moved` blocks mapping old aliased resource addresses to the new keyed addresses so nothing is destroyed.
6. **Guard key stability** — ensure for_each keys are static, known-at-plan strings (not derived from resource attributes) so providers can be configured during plan.
7. **Note version + limitation guards** — confirm 1.9+ and call out that provider for_each keys cannot depend on unknown values.

Output as: the locals map, the for_each provider block, one keyed resource/module example, and the full set of moved blocks.

Never auto-apply; run `terraform plan` and confirm every aliased resource shows an in-place move to its keyed address rather than destroy/create.
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