Problem
When using the yamlencode() function on a multi-line string, the terraform plan output unexpectedly contains \n newline characters, rendering the value as a single-line string instead of a formatted YAML literal block. This behavior can cause unintended resource updates, especially for sensitive arguments like user_data on an aws_instance.
Cause
This issue occurs when the lines in the input string contain trailing whitespace (spaces or tabs). The YAML encoder used by Terraform, which is based on the libyaml library, interprets this whitespace as significant. As a result, it changes its output format from a multi-line literal block to a quoted string with escaped newlines (\n) to preserve the trailing spaces.
Solution
To ensure yamlencode() produces a clean, multi-line YAML block, you must remove all trailing whitespace from each line within the input string.
Example
This example demonstrates the difference in output between a string with trailing whitespace and one without. Note the trailing spaces after one and two in the yaml_space variable.
Update your Terraform configuration to remove any trailing spaces.
variable "yaml_no_space" {
default = <<EOF
one
two
EOF
}
variable "yaml_space" {
## Note the trailing spaces on the next two lines.
default = <<EOF
one
two
EOF
}
output "yaml_no_space_output" {
description = "Correctly formatted YAML without trailing spaces."
value = yamlencode({
name = var.yaml_no_space
})
}
output "yaml_space_output" {
description = "Incorrectly formatted YAML due to trailing spaces."
value = yamlencode({
name = var.yaml_space
})
}Run terraform apply to observe the difference in the outputs.
$ terraform apply -auto-approve
The output shows that yaml_no_space_output renders as a proper YAML block, while yaml_space_output is formatted as a single-line string with \n characters.
Outputs: yaml_no_space_output = <<EOT "name": |- one two EOT yaml_space_output = "\"name\": \"one \\n_two_\\n\"\n"
Additional Information
For more details on this function, please refer to the official Terraform yamlencode() function documentation.