When we use heredoc syntax to assign a JSON string to an argument in Terraform, we may want to dynamically interpolate a list of values (e.g. from a .csv or .tfvars) into the JSON string.

We have to insert the double quotes " and the comma , in the right places, including avoiding the extra comma , at the end of the list.

Example with defect

If we simply use join() function

1
2
3
4
5
6
<<-EXAMPLE
{
  "type": "IP",
  "values": ["${join("\",\"", var.ip_list)}"]
}
EXAMPLE

When var.ip_list is empty, the result will be

1
2
3
4
{
  "type": "IP",
  "values": [""]
}

which is a valid JSON but with an extra empty string "" in the list.

Solution 1

Use for and if string template.

1
2
3
4
5
6
7
8
9
10
<<-EXAMPLE
{
  "type": "IP",
  "values": [
%{ for index, ip in var.ip_list[*] ~}
    "${ip}"%{ if index < length(var.ip_list) - 1 },%{ endif }
%{ endfor ~}
  ]
}
EXAMPLE

Solution 2

Use jsonencode() function.

1
2
3
4
jsonencode({
  "type" = "IP",
  "values" = var.ip_list
})

Heredoc syntax is not needed here.


Creative Commons License Licensed under CC BY-SA 4.0

Comments