Bootstrap FreeKB - Ansible - Retain keys from a YAML file using ansible.utils.keep_keys
Ansible - Retain keys from a YAML file using ansible.utils.keep_keys

Updated:   |  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:

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 Buy Me A Coffee



Comments


Add a Comment


Please enter d959de in the box below so that we can be sure you are a human.