Ansible - Retain keys from a YAML file using ansible.utils.keep_keys
by
Jeremy Canfield |
Updated: August 25 2023
| Ansible articles
Let's say you have a YAML file, perhaps something like this.
domains:
foo:
alias: foo
region: us-east-1
bar.example.com:
alias: bar
region: us-east-2
There are similar utilities:
- kwoodson.yedit - to add/change/remove keys
- ansible.utils.remove_keys - to remove keys
- ansible.utils.keep_keys - to retain keys (this article)
In this example, ansible.utils.keep_keys is used to keep the "foo" key and it's child elements and copy and to_nice_yaml are used to create a new YAML file that will contain the "foo" key and it's child elements.
---
- hosts: localhost
vars_files:
- /path/to/original.yml
tasks:
- name: the data variable should map to the top level key in the YAML file
set_fact:
data: "{{ domains }}"
- copy:
dest: /path/to/new.yml
content: "{{ output | to_nice_yaml(indent=2) }}"
vars:
output: "{{ {'domains': data | ansible.utils.keep_keys(target=['foo'])} }}"
...
Or like this, using:
- 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 ansible.utils.keep_keys and to_nice_yaml are used to create a new file that contain the YAML with the "foo" key
---
- hosts: localhost
tasks:
- slurp:
path: /path/to/original.yml
register: slurp
- set_fact:
yaml: "{{ slurp.content | b64decode | from_yaml }}"
- copy:
dest: /path/to/new.yml
content: "{{ yaml | ansible.utils.keep_keys(target=['foo']) | to_nice_yaml }}"
...
Now the new.yml file should contain the following, where the "foo" key and it's child elements were removed.
domains:
foo:
alias: foo
region: us-east-2
Did you find this article helpful?
If so, consider buying me a coffee over at