Back to Packer

`yamlencode` Function

website/content/docs/templates/hcl_templates/functions/encoding/yamlencode.mdx

1.15.33.5 KB
Original Source

⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️

[!IMPORTANT]
Documentation Update: Product documentation previously located in /website has moved to the hashicorp/web-unified-docs repository, where all product documentation is now centralized. Please make contributions directly to web-unified-docs, since changes to /website in this repository will not appear on developer.hashicorp.com. ⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️

yamlencode Function

yamlencode encodes a given value to a string using YAML 1.2 block syntax.

~> Warning: This function is currently experimental and its exact result format may change in future versions of Packer, based on feedback. Do not use yamldecode to construct a value for any resource argument where changes to the result would be disruptive. To get a consistent string representation of a value use jsonencode instead; its results are also valid YAML because YAML is a JSON superset.

<!-- The condition for removing the above warning is that the underlying go-cty-yaml folder makes a stable release with a commitment to guarantee that the representation of particular input will not change without a major release. It is not making that commitment at the time of writing to allow for responding to user feedback about its output format, since YAML is a very flexible format and its initial decisions may prove to be sub-optimal when generating YAML intended for specific external consumers. -->

This function maps Packer language values to YAML tags in the following way:

Packer typeYAML type
string!!str
number!!float or !!int
bool!!bool
list(...)!!seq
set(...)!!seq
tuple(...)!!seq
map(...)!!map
object(...)!!map
Null value!!null

yamlencode uses the implied syntax for all of the above types, so it does not generate explicit YAML tags.

Because the YAML format cannot fully represent all of the Packer language types, passing the yamlencode result to yamldecode will not produce an identical value, but the Packer language automatic type conversion rules mean that this is rarely a problem in practice.

Examples

shell-session
> yamlencode({"a":"b", "c":"d"})
"a": "b"
"c": "d"

> yamlencode({"foo":[1, 2, 3], "bar": "baz"})
"bar": "baz"
"foo":
- 1
- 2
- 3

> yamlencode({"foo":[1, {"a":"b","c":"d"}, 3], "bar": "baz"})
"bar": "baz"
"foo":
- 1
- "a": "b"
  "c": "d"
- 3

yamlencode always uses YAML's "block style" for mappings and sequences, unless the mapping or sequence is empty. To generate flow-style YAML, use jsonencode instead: YAML flow-style is a superset of JSON syntax.

  • jsonencode is a similar operation using JSON instead of YAML.
  • yamldecode performs the opposite operation, decoding a YAML string to obtain its represented value.