For the last week or so I have been working on a Terraform module for deploying tasks to ECS. One of the most interesting problems that I came across while working on it was around creating IAM profiles. Each task that gets deployed needs to have a minimum set of permissions in their IAM profile, but some need to have more than others. After thinking about various ways to solve my problem, I decided to give dynamic blocks a try.
When writing IAM policies in Terraform, I prefer to do it in an aws_iam_policy_document
data block rather than in pure JSON or a template file since Terraform can validate the syntax in a data block. A typical policy might look something like this:
The above policy is an example of something that I may want to attach to every task I launch so that it can update itself with a load balancer. So for me to be able to add a statement through my tfvars, I added a dynamic statement block to the bottom:
This configuration allows me to configure a variable task_iam_policies
that contains any additional policy statements that I need to add:
Now I can add as many statements as I need to my task when I deploy it.
Comments