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.
More on Loops, Conditionals, Dynamic Blocks and Functions
How does `count` work?BeginnerHow does `for_each` work?BeginnerWhen should you choose `for_each` over `count`?IntermediateHow do you use `for_each` with a list of objects?IntermediateWhat does "The for_each value depends on resource attributes that cannot be determined until apply" mean?AdvancedHow do you create a resource conditionally?Beginner