⚡ ~/naveed Interview Prep
⚡ Portfolio Home 👤 About Naveed Bio & Credentials 📫 Contact Naveed Get In Touch ✍️ Engineering Blog Deep Dives 🎯 Interview Hub 1,000+ Scenarios ☸️ Kubernetes Mastery Hub 24 Modules 🎮 DevOps Arcade & Quizzes Subnet Blitz ⚡ 🗺️ DevOps Roadmaps PDFs & Guides 🤖 Morpheus Analysis AI Quant ↗ 🛠️ Developer Tools Utilities 🧪 Labs & Experiments 📄 Interactive CV & Certs 🔗 All Links & Socials ⚡ Join The Dispatch (Weekly SRE Newsletter) →
← Back to All Terraform & IaC Interview Questions Scenario 64 of 120 in Terraform & IaC
Senior DevOps / SRE [L2] Terraform Terraform Modules & State Production Scenario [L2]
🎯 Target Role / Context: Terraform Scenario #59 (L2) · Use VPC ID from another module

Q: How do you use Terraform to create IAM policies without hardcoding JSON?

Use the aws_iam_policy_document data source:

#Terraform #L2 #IaC #Cloud Infrastructure #S3
🎙️ Candidate Opening & Architectural Context
"To create <strong>IAM policies without hardcoding JSON</strong> in Terraform, use the <code>aws_iam_policy_document</code> data source, which builds policy JSON from HCL blocks, or <code>jsonencode()</code> on a native map. Both let you use variables, resource references and conditions instead of fragile heredoc strings. Interviewers ask because hardcoded JSON hides typos, ignores dependencies and tends to be over-permissive. A strong answer shows composition, least privilege, trust policies, validation with Access Analyzer, and how to avoid permissions drift."
Advertisement
⚡ Recommended Practice Lab

Want to master this scenario in a live sandbox? KodeKloud's HashiCorp Certified Terraform Associate (003) Interactive Labs covers this exact problem with hands-on terminal drills.

🛠️ Production Runbook & Step-by-Step Resolution

Direct Answer: To create <strong>IAM policies without hardcoding JSON</strong> in Terraform, use the <code>aws_iam_policy_document</code> data source, which builds policy JSON from HCL blocks, or <code>jsonencode()</code> on a native map. Both let you use variables, resource references and conditions instead of fragile heredoc strings. Interviewers ask because hardcoded JSON hides typos, ignores dependencies and tends to be over-permissive. A strong answer shows composition, least privilege, trust policies, validation with Access Analyzer, and how to avoid permissions drift.

1️⃣

Mental model: HCL in, valid policy JSON out

The data source does not call AWS; it is a pure renderer that converts blocks into a JSON string you pass to a policy resource.

  • Data source: data "aws_iam_policy_document" exposes a .json attribute containing the rendered policy.
  • Dependency aware: referencing aws_s3_bucket.data.arn inside the document creates an implicit dependency, so the policy follows the bucket rename or replacement.
  • Typed fields: actions, resources, principals and condition are lists and blocks, so Terraform catches shape errors at validate time rather than IAM catching them at apply.
  • Alternative: jsonencode({ Version = ..., Statement = [...] }) is valid too and good for short policies, but offers no merge helpers.
  • Why not heredocs: a heredoc is just a string, so Terraform cannot check structure, cannot track the references inside it, and shows any whitespace change as a diff. The data source removes all three problems.
2️⃣

Hands-on: IAM policies without hardcoding JSON

Build a least-privilege identity policy for an application role and attach it.

data "aws_iam_policy_document" "app" {
  statement {
    sid       = "ReadObjects"
    actions   = ["s3:GetObject"]
    resources = ["${aws_s3_bucket.data.arn}/*"]
  }
  statement {
    sid       = "ListBucket"
    actions   = ["s3:ListBucket"]
    resources = [aws_s3_bucket.data.arn]
  }
}

resource "aws_iam_policy" "app" {
  name   = "my-app-s3-read"
  policy = data.aws_iam_policy_document.app.json
}
  • Statements: give each statement a sid for readability and for override merging.
  • Resource scoping: list the bucket ARN for bucket-level actions and "${arn}/*" for object-level actions, a distinction that many hand-written policies get wrong.
  • Conditions: add condition blocks (for example aws:SourceVpce or aws:PrincipalOrgID) to narrow the grant further.
  • Attach: pass data.aws_iam_policy_document.app.json to aws_iam_policy or aws_iam_role_policy.
  • Variables for scope: accept a list of ARNs as an input variable and splat them into resources, so callers choose the scope while the module owns the actions.
  • Partition and account: build ARNs with data.aws_partition.current.partition and data.aws_caller_identity.current.account_id rather than hardcoding arn:aws or an account number.
Advertisement
3️⃣

Trust policies, merging and dynamic statements

Role trust policies and reusable policy fragments use the same data source.

data "aws_iam_policy_document" "assume" {
  statement {
    actions = ["sts:AssumeRole"]
    principals {
      type        = "Service"
      identifiers = ["ecs-tasks.amazonaws.com"]
    }
  }
}

resource "aws_iam_role" "app" {
  name               = "my-app-task"
  assume_role_policy = data.aws_iam_policy_document.assume.json
}

data "aws_iam_policy_document" "combined" {
  source_policy_documents = [
    data.aws_iam_policy_document.app.json,
    data.aws_iam_policy_document.extra.json,
  ]
}
  • Trust policy: use a principals block with type = "Service" and identifiers = ["ecs-tasks.amazonaws.com"], then pass the JSON to assume_role_policy.
  • source_policy_documents: merge several documents into one, so a base policy plus a team-specific add-on composes cleanly.
  • override_policy_documents: later documents replace statements with the same sid, giving environment-specific overrides.
  • dynamic statements: loop over a map of buckets with a dynamic "statement" block to generate one statement per entry from a variable.
4️⃣

Verification: validate and simulate before apply

A rendered policy can be syntactically valid and still be wrong; check it.

terraform show -json tfplan \
  | jq -r '.resource_changes[] | select(.type=="aws_iam_policy") | .change.after.policy' \
  > policy.json

aws accessanalyzer validate-policy \
  --policy-document file://policy.json \
  --policy-type IDENTITY_POLICY

aws iam simulate-principal-policy \
  --policy-source-arn arn:aws:iam::123456789012:role/my-app-task \
  --action-names s3:GetObject \
  --resource-arns arn:aws:s3:::my-data-bucket/file.txt
  • Plan review: read the planned policy JSON in the plan output; it is deterministic and reviewable in a PR.
  • Access Analyzer: run aws accessanalyzer validate-policy on the rendered JSON to catch security warnings and errors such as overly broad wildcards.
  • Simulate: use aws iam simulate-principal-policy after apply to confirm that an action is allowed or denied for the role.
  • Static analysis: run tflint, checkov or trivy config in CI to flag Action: * and Resource: *.
  • Review in PRs: because the plan prints the rendered policy, reviewers can read the exact permissions being granted, which is not possible when the JSON is assembled in a script.
5️⃣

Failure modes and production practice

Know what goes wrong with generated policies, and how teams keep them tidy.

  • Perpetual diff: mixing heredoc JSON with reordered keys causes diffs on every plan. The data source emits canonical ordering, which avoids that.
  • Size limits: managed policies and inline policies have size limits (check current IAM quotas). Split policies by function instead of one giant document.
  • Wildcard creep: use variables for actions with validation, and require reviewers for any *.
  • Modules: publish a small internal module that takes a list of bucket ARNs and returns a policy JSON, so every team gets the same least-privilege shape.
  • Boundaries: for roles created by application teams, attach a permissions boundary policy, also rendered from aws_iam_policy_document, so even a mistaken statement cannot exceed the approved ceiling. Pair it with service control policies at the organization level for defence in depth.
💡 The Senior SRE Gold Nugget (Key Architectural Takeaway)
"Pro-Tip: Render policies with <code>aws_iam_policy_document</code>, split object-level and bucket-level resources correctly, and validate the output with <code>aws accessanalyzer validate-policy</code> in CI before it reaches an account."
⚡ 60-Second Elevator Pitch Talking Points
  • I use <code>aws_iam_policy_document</code> to generate IAM JSON from HCL, referencing real resource ARNs so dependencies are tracked.
  • I compose policies with <code>source_policy_documents</code> and validate the rendered JSON with Access Analyzer and a policy scanner in CI.
  • I keep trust policies and permissions as separate documents and review the planned policy in every pull request.
⛔ Critical Candidate Mistakes to Avoid in This Scenario

Senior hiring managers and bar raisers evaluate how you prioritize during outages. Avoid these common anti-patterns:

  1. Writing policy heredocs with literal ARNs They break when a bucket is renamed and hide typos until an access denied appears in production.
  2. Using <code>"${bucket_arn}/*"</code> for <code>s3:ListBucket</code> List actions apply to the bucket ARN, while object actions need the <code>/*</code> form; mixing them yields silent denials.
  3. Granting <code>Action: "*"</code> or <code>Resource: "*"</code> for convenience It defeats least privilege and fails most policy scanners.
  4. Assuming a valid policy is a correct policy The data source does not check semantics; use Access Analyzer and simulation to confirm the effect.
Advertisement
Want more Terraform & IaC scenarios?
Explore our complete collection of scenario-based Terraform & IaC interview runbooks.
Browse All Terraform & IaC Questions →