title: How do you dynamically create an AWS IAM policy document with a variable number of resource blocks using terraform?
body: <p>In my current terraform configuration I am using a static JSON file and importing into terraform using the file function to create an AWS IAM policy.</p>
  
  <p>Terraform code:</p>
  
  <pre><code>resource "aws_iam_policy" "example" {
    policy = "${file("policy.json")}"
  }
  </code></pre>
  
  <p>AWS IAM Policy definition in JSON file (policy.json):</p>
  
  <pre><code>{
      "Version": "2012-10-17",
      "Id": "key-consolepolicy-2",
      "Statement": [
          {
              "Sid": "Enable IAM User Permissions",
              "Effect": "Allow",
              "Principal": {
                  "AWS": "arn:aws:iam::111122223333:root"
              },
              "Action": "kms:*",
              "Resource": "*"
          },
          {
              "Sid": "Allow use of the key",
              "Effect": "Allow",
              "Principal": {
                  "AWS": [
                      "arn:aws:iam::777788889999:root"
                  ]
              },
              "Action": [
                  "kms:Decrypt"
              ],
              "Resource": "*"
          },
          {
              "Sid": "Allow use of the key",
              "Effect": "Allow",
              "Principal": {
                  "AWS": [
                      "arn:aws:iam::444455556666:root"
                  ]
              },
              "Action": [
                  "kms:Decrypt"
              ],
              "Resource": "*"
          }
      ]
  }
  </code></pre>
  
  <p>My goal is to use a list of account numbers stored in a terraform variable and use that to dynamically build the aws_iam_policy resource in terraform. My first idea was to try and use the terraform jsonencode function. However, it looks like there might be a way to implement this using the new terraform dynamic expressions foreach loop.</p>
  
  <p>The sticking point seems to be appending a variable number of resource blocks in the IAM policy. </p>
  
  <p>Pseudo code below:</p>
  
  <pre><code>var account_number_list = ["123","456","789"]
  policy = {"Statement":[]}
  for each account_number in account_number_list:
      policy["Statement"].append(policy block with account_number var reference)
  </code></pre>
  
  <p>Any help is appreciated.</p>
  
  <p>Best,
  Andrew</p>