Ansible - Remove keys from a YAML file using ansible.utils.remove_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 (this article)
 - ansible.utils.keep_keys - to retain keys
 
And you want to remove the "foo" key and it's child elements from the YAML file. ansible.utils.remove_keys can be used to remove the "foo" key and it's child elements and copy and to_nice_yaml are used to append the adjusted YAML to a new file (or the original file could be overwritten).
---
- 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.remove_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.remove_keys and to_nice_yaml are used to create a new file that contain the YAML with the "foo" key removed
 
---
- 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.remove_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:
  bar.example.com:
    alias: bar
    region: us-east-2
Did you find this article helpful?
If so, consider buying me a coffee over at 