Managing IAM Policy Documents in HCL with Terraform

IAM Policy Documents are ubiquitous in AWS - they are used not only for standalone policies you might attach to users or roles, but also for S3 bucket policies, SNS topic policies and more. Unfortunately, the JSON syntax can be error prone to hand write, and the default mechanism for creating policies in many configuration management tools is template rendering.

Terraform 0.7 introduced the concept of data sources, one of which allows definition of policy documents in Terraform's native HCL configuration format which is designed for humans to read and write.

Let's take an IAM Role as an example. Previously, we would have written the configuration like this:

Note that the meat of this resources is contained in a HEREDOC. We could improve this slightly, using an indented HEREDOC, by using the <<-EOF form, but Terraform has no way to ensure the JSON is valid. Instead, we can use the aws_iam_policy_document data source, like this:

We use the DSL in order to write policies that can then be associated to the iam_role. Terraform renders the JSON from our HCL, so we can interpolate into the aws_iam_role resource. This means that policy documents can be reused without duplication, as is common for role assumption policies for example: