How can I convert a list to a string in Terraform?

Conversion from list to string always requires an explicit decision about how the result will be formatted: which character (if any) will delimit the individual items, which delimiters (if any) will mark each item, which markers will be included at the start and end (if any) to explicitly mark the result as a list.

The syntax example you showed looks like JSON. If that is your goal then the easiest answer is to use jsonencode to convert the list directly to JSON syntax:

jsonencode(var.names)

This function produces compact JSON, so the result would be the following:

["ben","linda","john"]

Terraform provides a ready-to-use function for JSON because its a common need. If you need more control over the above decisions then you’d need to use more complex techniques to describe to Terraform what you need. For example, to produce a string where each input string is in quotes, the items are separated by commas, and the entire result is delimited by [ and ] markers, there are three steps:

  • Transform the list to add the quotes: [for s in var.names : format("%q", s)]
  • Join that result using , as the delimiter: join(", ", [for s in var.names : format("%q", s)])
  • Add the leading and trailing markers: "[ ${join(",", [for s in var.names : format("%q", s)])} ]"

The above makes the same decisions as the JSON encoding of a list, so there’s no real reason to do exactly what I’ve shown above, but I’m showing the individual steps here as an example so that those who want to produce a different list serialization have a starting point to work from.

For example, if the spaces after the commas were important then you could adjust the first argument to join in the above to include a space:

"[ ${join(", ", [for s in var.names : format("%q", s)])} ]"

Leave a Comment