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
-
Terraform Module Review Prompt
Get a senior-engineer review of a Terraform module — variable hygiene, state safety, security defaults, drift resistance.
-
Terraform Moved & Import Blocks Prompt
Use declarative `moved` and `import` blocks to refactor and adopt resources without manual `terraform state mv`/`import` — keeping every change reviewable in a plan and reproducible in CI.
-
Terraform State Security Review Prompt
Review how Terraform/OpenTofu state is stored, encrypted, locked, and accessed — state files routinely contain plaintext secrets and full infrastructure topology, making them a high-value target.