Terraform: configurable output format for yamlencode

Created on 8 Nov 2019  路  8Comments  路  Source: hashicorp/terraform

Current Terraform Version

Terraform v0.12.13
+ provider.null v2.1.2

Use-cases


I want to use terraform to generate yaml formatted configuration files for an ansible based installation.

Attempted Solutions


Currently we dump a jsonencode(${var.some_map_var}) file to the target system, and then use remote-exec that runs a Python script that parses the .json file to generate the desired config.yaml

With a map of

some_map_var = {
  foo = ["bar", "baz"]
  dofoo = true
}

This will generate a nice yaml that Ansible can use, i.e.

foo:
- bar
- baz

dofoo: true

Having discovered the yamlencode function in 0.12 this seems like a really nice option to avoid the escape hatch of the remote-exec python script and stay truer to Terraform native end-to-end.

However, the current yamlencode function seems to produce a file like this

"foo":
- "bar"
- "baz"
"dofoo": true

where all the keys are quoted (I guess because they are strings), rather than giving us a nice UTF-8 unquoted yaml file as we get with our Python parser.
This seems to create some issues for Ansible.

Proposal

Allow (at least a config switch) to generate yaml files what does not quote keys and values

References

enhancement

Most helpful comment

+1. Want to be able to create config maps from terraform maps.

All 8 comments

+1, I think we should produce some nice looking YAML :)

Ran into this problem today. The quotations are causing weird issues with Kubernetes config maps (I have to embed a YAML into a config map key)

+1. Want to be able to create config maps from terraform maps.

This causes problems in a number of environments where downstream applications consume YAML but dislike the "quote everything" + "alphabetical sorted" output of the yamlencode function.

Yes, it would be nice to keep the original ordering of fields in the template file + remove the quotes. You could use a beautifier for that within Terraform after converting to YAML.

+1, encountered this issue just now

+1, Also encountered this issue today

I have a workaround for this. It's working for me, but beware; It's kinda hacky.

Having this variable:

some_map_var = {
  foo = ["bar", "baz"]
  dofoo = true
}

Wrap it with a regex replace function:

replace(yamlencode(var.some_map_var), "/((?:^|\n)[\\s-]*)\"([\\w-]+)\":/", "$1$2:")

Results in this output:

foo:
- "bar"
- "baz"
dofoo: true
Was this page helpful?
0 / 5 - 0 ratings