Ansible - Parse YAML using to_yaml or to_nice_yaml
by
Jeremy Canfield |
Updated: August 24 2023
| Ansible articles
Let's say you need to append YAML to a YAML file. This can be done using copy and to_yaml or to_nice_yaml. As a simple example, let's read YAML from a file and write the same YAML to a new file. For example, let's say original.yml contain the following.
domains:
foo:
alias: foo
region: us-east-1
bar.example.com:
alias: bar
region: us-east-2
- slurp is used to read the original YAML file
- b64decode is used to decode the original YAML file
- set_fact and from_yaml are used to create a variable that contains the YAML from the original file
- copy and to_yaml or to_nice_yaml are used to create new files that contain the YAML
---
- hosts: localhost
tasks:
- slurp:
path: /path/to/original.yml
register: slurp
- set_fact:
yaml: "{{ slurp.content | b64decode | from_yaml }}"
- copy:
dest: /path/to/to_yaml.yml
content: "{{ yaml | to_yaml }}"
- copy:
dest: /path/to/to_nice_yaml.yml
content: "{{ yaml | to_nice_yaml }}"
...
Notice that by default to_nice_yaml is properly formatted. Almost always, it makes sense to go with to_nice_yaml.
~]$ cat to_yaml.yml
domains:
bar.example.com: {alias: bar, region: us-east-2}
foo: {alias: foo, region: us-east-1}
~]$ cat to_nice_yaml.yml
domains:
bar.example.com:
alias: bar
region: us-east-2
foo:
alias: foo
region: us-east-1
By default, each key in the new file will be indented with 4 spaces. indent=2 can be used to indent each key with 2 spaces.
---
- hosts: localhost
tasks:
- slurp:
path: /path/to/foo.yml
register: slurp
- set_fact:
yaml: "{{ slurp.content | b64decode | from_yaml }}"
- copy:
dest: /path/to/to_nice_yaml.yml
content: "{{ yaml | to_nice_yaml(indent=2) }}"
...
Now the original YAML file and new YAML files have the same data, same format. The only difference is that the new YAML file is sorted alphabetically.
~]$ cat original.yml
domains:
foo:
alias: foo
region: us-east-1
bar.example.com:
alias: bar
region: us-east-2
~]$ cat to_nice_yaml.yml
domains:
bar.example.com:
alias: bar
region: us-east-2
foo:
alias: foo
region: us-east-1
Did you find this article helpful?
If so, consider buying me a coffee over at