Can't assign list value to json policy in Terraform

Viewed 1773

I have in Terraform this policy :

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "execute-api:Invoke",
        "Resource": "*",
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": "${source_ip}"
            }
        }
      }
    ]
  }

and i have a variable authorized_ip defined like this :

variable "authorized_ip" {
  default = [
    "x.x.x.x/x",
    "x.x.x.x/x",
  ]
}

Now i'm calling the Json policy this way :

data "template_file" "apigw_policy" {
  template = "${file("${path.module}/template/apigateway_policy.json.template")}"

   vars = {
      source_ip = "${var.authorized_ip}"
   }
}

But i'm getting this error :

Inappropriate value for attribute "vars": element "source_ip": string required.

So Terraform is expecting a String instead of the list. How to transform the list to String to be able to have a result like that :

"IpAddress": {
   "aws:SourceIp": [
      "x.x.x.x/x",
      "x.x.x.x/x"
    ]
 }
2 Answers

You can use the jsonencode function here:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": "*",
            "Action": "execute-api:Invoke",
            "Resource": "*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": "${jsonencode(source_ip)}"
                }
            }
        }
    ]
}

Try

"aws:SourceIp": ["${join(", ", source_ip)}"]

Note that "[" and "]" are outside of the interpolated value to define a list within the policy, but do not represent a Terraoform list type.

Edit: Fixed typo as mentioned in comment below.

Related