How to flatten a tuple of subnet ids to a string in Terraform

Viewed 2464

I am trying to flatten a tuple to a string as follows

network_acls {
default_action             = "Deny"
bypass                     = "AzureServices"
virtual_network_subnet_ids = ["${data.azurerm_subnet.blah_snet.id}", "${join("\",\"", azurerm_subnet.subnets.*.id)}"]

}

This is very similar to How to flatten a tuple of server ids to a string?, however it's not working for me.

The result is: "*subnetid1*\",\"*subnetid2*" - where \",\" should be properly escaped and result as ","

I can't figure out why this isn't working. I've tried many variations of escaping this to no benefit

2 Answers

This is a potential solution using Terraform 12 syntax (it looks like the splat syntax wasn't supported for non-count resources until TF12 so your mileage may vary depending on your version).

The local item approximates the attribute structure of a data.azurerm_subnet.

Note the use of both the \\ to escape the single \ literal or the simple "," since I couldn't quite tell what the desired output string was meant to be.

locals {
  subnets = [
  {
    id = 12345,
    name = "item1"
  },
  {
    id = 9354,
    name = "item2"
  }
  ]
}

output "comma_and_escape_char_for_literal" {
  value = "${join("\\,", local.subnets.*.id)}"
}

output "comma_only" {
  value = "${join(",", local.subnets.*.id)}"
}

This is an expression which has varying Terraform 0.11.x and Terraform 0.12.x outcomes:

["${data.azurerm_subnet.blah_snet.id}", "${join("\",\"", azurerm_subnet.subnets.*.id)}"]

In Terraform 0.11.x, it will result in a concatenation as you shown with "," separating the subnet IDs. In Terraform 0.12.x, it will be a type-error and fail to apply. FWIW, Terraform 0.12.x is correct here.

If you are using Terraform 0.12.x, the following should work:

virtual_network_subnet_ids = join(",", concat(
  [data.azurerm_subnet.blah_snet.id], azurerm_subnet.subnets[*].id
)

If you are using Terraform 0.11.x, the following should work:

virtual_network_subnet_ids = "${join(",", concat(
  [data.azurerm_subnet.blah_snet.id], azurerm_subnet.subnets[*].id
)}"
Related