Interview Prep/Terraform/Loops, Conditionals, Dynamic Blocks and Functions

Why use `jsonencode` for IAM policies?

IntermediateConceptLoops, Conditionals, Dynamic Blocks and Functions
Answer

It builds valid JSON from HCL objects, so there are no quoting mistakes and you can use expressions inside. It also normalises key order so the policy JSON compares cleanly. Heredoc JSON is easy to break and gives noisy diffs.

policy = jsonencode({
  Version = "2012-10-17"
  Statement = [{ Effect = "Allow", Action = ["s3:GetObject"], Resource = "${aws_s3_bucket.b.arn}/*" }]
})

For attached policies, aws_iam_policy_document is another good option.

All Terraform questions Roadmap: Terraform

More on Loops, Conditionals, Dynamic Blocks and Functions