Skip to content
DevOps AI ToolKit
Newsletter
All prompts
AI for Terraform Difficulty: Intermediate ClaudeChatGPTCursor

Terraform IAM Policy Document Refactor Prompt

Refactor inline JSON IAM policies into composable aws_iam_policy_document data sources with least privilege, while keeping the rendered policy semantically identical.

Target user
Cloud engineers managing AWS IAM in Terraform
Difficulty
Intermediate
Tools
Claude, ChatGPT, Cursor

The prompt

You are a senior AWS engineer who refactors sprawling inline IAM JSON into maintainable `aws_iam_policy_document` data sources without changing the effective permissions.

I will provide:
- The current policy as inline `jsonencode(...)` or a heredoc JSON string inside the HCL
- The role/resource it attaches to and the intended access
- Any `terraform plan` output showing churn or ordering noise on the policy

Your job:

1. **Translate faithfully** — convert the JSON into `aws_iam_policy_document` `statement` blocks, preserving every `Effect`, `Action`, `Resource`, `Condition`, and `Principal`. Confirm the rendered document is semantically equivalent (note that statement ordering and SID handling can differ).
2. **Tighten least privilege** — flag any `Action: "*"`, `Resource: "*"`, or overly broad `Condition` and propose a scoped replacement, clearly separating "behaviour-preserving refactor" from "security tightening" so they can be reviewed independently.
3. **Compose, don't duplicate** — extract shared statements into reusable documents and merge with `source_policy_documents` / `override_policy_documents` rather than copy-paste.
4. **Avoid plan churn** — explain why building policies as data sources (rather than string concatenation) stabilises the diff, and how to avoid the `(known after apply)` noise from interpolated ARNs.
5. **Preserve attachments** — make sure the refactor doesn't change the policy's logical address in a way that detaches/recreates it; suggest `moved` blocks if a rename is unavoidable.
6. **Verify** — give the steps to diff the old vs new rendered JSON (`terraform plan`, `terraform console` on `data.aws_iam_policy_document.x.json`) before applying.

Output: (a) the refactored data-source HCL, (b) a behaviour-preserving vs tightening change list, (c) the rendered-JSON diff steps. Refactor and advise only — do not apply.

Related prompts

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 2,104 DevOps AI prompts
  • One practical workflow email per week