I’m trying to figure out how to escape double quotes in a variable of a terraform script.
Here is a more concrete example of what I’m trying to do that doesn’t work :
variable "authorized_ip_adress" {
description = "IP addresses that will be allowed to use the API"
default = "\"10.0.0.1\", \"10.0.0.2\", \"10.0.0.3\""
}
and I need that when I call the variable, the value contains the double quotes.
I also tried with triple backslashes but it didn’t work either :
variable "authorized_ip_adress" {
description = "IP addresses that will be allowed to use the API"
default = "\\\"10.0.0.1\\\", \\\"10.0.0.2\\\", \\\"10.0.0.3\\\""
}
What am I missing here, how and why does a local variable definition: locals { authorized_ip_adress = "\"10.0.0.1\", \"10.0.0.2\", \"10.0.0.3\"" }
Behave differently when dealing with escaping of double quotes: variable "authorized_ip_adress" { description = "IP addresses that will be allowed to use the API" default = "\"10.0.0.1\", \"10.0.0.2\", \"10.0.0.3\"" }
I think some participants in this discussion are confusing the way Terraform shows string values in the UI vs. how they are stored internally.
When Terraform shows you a string value in the UI it uses the same quoting and escaping syntax you’d write in your configuration, because otherwise the result would be ambiguous.
These backslashes are just part of showing the string value on-screen in an unambiguous way. The actual value of the string is literally this:
"10.0.0.1", "10.0.0.2", "10.0.0.3"
However, I think it’s also worth taking a step back here and asking why we’re writing lists of quoted strings like this in the first place. Terraform has support for collection types so that module authors can avoid exposing such an awkward interface to their users.
I would typically suggest the following instead:
variable "authorized_ip_addresses" {
type = set(string)
default = [
"10.0.0.1",
"10.0.0.2",
"10.0.0.3",
]
}
locals {
# If you need to construct that comma-separated quoted
# string syntax then you can do that systematically using
# an expression, rather than hand-writing it:
authorized_ip_addrs_raw = join(", ", [
# jsonencode of a string will add quotes, because that's
# how strings are represented in JSON.
for addr in var.authorized_ip_addresses : jsonencode(addrs)
])
}
With the above configuration the local.authorized_ip_addrs_raw value will still be the single string containing comma-separated quoted IP addresses, but we let Terraform worry about constructing that awkward syntax and instead just focus on providing the correct set of strings as input.