Problem:
If you attempt to use a multi-lined JSON string, the AWS API will return an error because of white spaces in the string.
Solution:
As of Terraform 0.12, you can produce minified JSON using a round-trip through jsondecode and jsonencode, because jsonencode always produces minimal JSON. A data source or resource may produce a JSON string as an attribute that is not minified, and if needs to be used elsewhere minified, an expression like jsonencode(jsondecode(data.some_data_source.json)) will do this.
Example:
Write the template itself to use jsonencode so that you can use the full Terraform expression language to produce your result and not have to deal with finicky JSON formatting concerns:
variable "json_text" {
default = <<EOF
{
"foo": "bar",
"baz": [
"qux"
]
}
EOF
}
output "not_minified" {
value = var.json_text
}
output "minified" {
value = jsonencode(jsondecode(var.json_text))
}
Terraform apply
Outputs:
minified = "{\"baz\":[\"qux\"],\"foo\":\"bar\"}"
not_minified = <<EOT
{
"foo": "bar",
"baz": [
"qux"
]
}
The result of output "minified" will automatically be minified because, as noted above, jsonencode always produces minimal JSON. Terraform's expression language permits things that JSON alone does not, such as inline comments, trailing commas on the last item in an object or array, direct references to template variables, and for expressions for constructing arrays and objects dynamically.
Additional Documentation:
https://www.terraform.io/language/functions/jsonencode