Create a comma separated list of quoted strings on terraform

2 min read | by Jordi Prats

Some times we need to generate a quoted comma separated list of strings out of a variable that is list of strings, for example, to generate an IAM policy like this one:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetResourcePolicy",
        "secretsmanager:GetSecretValue",
        "secretsmanager:DescribeSecret",
        "secretsmanager:ListSecretVersionIds"
      ],
      "Resource": [ "arn:aws:secretsmanager:...", "arn:aws:secretsmanager:.." ]
    }
  ]
}

To do so we can take advantage of the jsonencode function that produces compact JSON that we will push into a template. So first we will have to create a template like this, on this example the ARN_LIST variable will hold the JSON object

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "secretsmanager:GetResourcePolicy",
        "secretsmanager:GetSecretValue",
        "secretsmanager:DescribeSecret",
        "secretsmanager:ListSecretVersionIds"
      ],
      "Resource": ${ARN_LIST}
    }
  ]
}

So now we'll have to create the policy like this:

resource "aws_iam_policy" "policy" {
  name   = "policy"
  path   = "/example/jsonencode/"
  policy = templatefile("${path.module}/iam_policies/external-secrets.json",
        {
          ARN_LIST = jsonencode(var.secretsmanager_arns)
        })
}

Thus, the ARN_LIST will hold a JSON object that will be translated to a string that will match what the policy expects, rendering the policy we wanted to generate in the first place


Posted on 03/11/2021

Categories