Search code examples
amazon-web-servicesterraformdevopsstring-interpolationinfrastructure-as-code

Covert terraform custom variable to some specific format issue


The below is the custom variable that will use for specific AWS resource creation

INPUT Variable:

VAR = {
        "commonPolicy" = [
            "DenyRootUser",
            "denyIamAccessKeyCreation"
        ]
        "extraPolicy" = [
            "denyGlobalService",
            "denyBillingModify"
        ]
}

The interpolation/modification method i am using below to modify the value using Terraform console.

Method:

> { for i,j in var.VAR  : "${i}" =>  [ for k in j : "file('policies/${k}.json')}" ] }

Through this method i am able to get this value when i parse value from specific key:

Like this:

> { for i,j in var.VAR  : "${i}" =>  [ for k in j : "file('policies/${k}.json')}" ] }["commonPolicy"]

OUTPUT:

[
  "file('policies/DenyRootUser.json')}",
  "file('policies/denyIamAccessKeyCreation.json')}",
]

But the following value i want from interpolation method

Expected Output:

[
  file("policies/DenyRootUser.json")},
  file("policies/denyIamAccessKeyCreation.json")},
]

NOTE:

  • The difference between output & expected output is that i want list of values without doube quotes.
  • under file function, the location/path should be under double quotes.

Solution

  • You can use it as below which will yield the result as follows:

    locals {
        a = ["a.json","b.json"]
        test = [for i in local.a: file("${i}")]
    }
    
    
    data "aws_iam_policy_document" "b" {
      source_policy_documents =  local.test
    }
    
    
    terraform  console
    
    > data.aws_iam_policy_document.b.json
    <<EOT
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Sid": "",
          "Effect": "Allow",
          "Action": "ec2:*",
          "Resource": "*"
        },
        {
          "Sid": "UniqueSidOne",
          "Effect": "Allow",
          "Action": "s3:*",
          "Resource": "*"
        },
        {
          "Sid": "UniqueSidTwo",
          "Effect": "Allow",
          "Action": "iam:*",
          "Resource": "*"
        },
        {
          "Sid": "",
          "Effect": "Allow",
          "Action": "lambda:*",
          "Resource": "*"
        },
        {
          "Sid": "",
          "Effect": "Allow",
          "Action": "ec3:*",
          "Resource": "*"
        },
        {
          "Sid": "uu",
          "Effect": "Allow",
          "Action": "s4:*",
          "Resource": "*"
        },
        {
          "Sid": "rr",
          "Effect": "Allow",
          "Action": "iamm:*",
          "Resource": "*"
        },
        {
          "Sid": "",
          "Effect": "Allow",
          "Action": "scp:*",
          "Resource": "*"
        }
      ]
    }
    EOT
    

    Is this the expected output?