I have a string variable that’s asking the user to enter a path:
var1 = "\path\to\whatever"
Terraform throws an exception about valid escape characters, which makes sense so I escaped out of the backslash.
var1 = "\\path\\to\\whatever"
Now when I pass this variable into jsonencode, the escaped backslashes are again being escaped.
\"var1\":\"\\\\path\\\\to\\\\whatever\"
My expectation would be that Terraform would realize the initial string is just an escaped backslash and pass the single into jsonencode so that when it is decoded the json string has the single backslash that the system needs to use. Is there any way to tell terraform to use a literal string without escaping any values?
Terraform is using the correct number of backslashes.
The problem is that you have cut off the outer "{ }" when you pasted this into the forum message, which show that you’re actually dealing with a JSON string, that is itself embedded within a valid Terraform string literal:
"{\"var1\":\"\\\\path\\\\to\\\\whatever\"}"
When Terraform outputs values to the screen, it normally does so in a way so that special characters are written in such a way that you could copy/paste the value into a Terraform source file and have it parse correctly.
You would need to retrieve this value via terraform output -raw var1 if you were seeking to bypass this behaviour.
Interesting. I was expecting Terraform to output the raw value. Is there any way to accomplish that without -raw? I would like to output the raw json encoded string for the user since they may need to use it outside of Terraform.
There is no way to get the raw values shown by default.
JSON output variables printed at the end of terraform apply will be rendered slightly more usefully if, as a hack, you append a newline character to the value:
output "foobar" {
value = "${jsonencode({var1 = "\\path\\to\\whatever"})}\n"
}