Problem:
Spaces at the end of lines cause \n to appear in plan output when using the yamlencode() function.
Scenario: yamlencode()'s behavior is important to understand when used it in places like aws_instance user_data where changes will cause replacement of the whole instance.
Example:
variable "yaml_no_space" {
default = <<EOF
one
two
EOF
}
variable "yaml_space" {
default = <<EOF
one
two
EOF
}
output "yaml_no_space" {
value = yamlencode({
name = var.yaml_no_space
})
}
output "yaml_space" {
value = yamlencode({
name = var.yaml_space
})
}
$ terraform apply
Output:
Changes to Outputs:
+ yaml_no_space = <<-EOT
"name": |2
one
two
EOT
+ yaml_space = <<-EOT
"name": " one \n two\n"
EOT
In the above example yaml_space has space characters after one and two. This causes the rendering to abandon literal newlines for \n and place everything on one line. The YAML encoder used by Terraform is a mechanical Go port of the C library libyaml, and libyaml behaves like that.
Related docs:
https://www.terraform.io/language/functions/yamlencode