Filter data using JSON query in Ansible to extract data from an ansible_fact

Issue

I have created this playbook to extract all mount points starting with any element in the variable whitelist matching the type= ext2, ext3, ext4.

The problem is that I can get all mount_points but I am not able to filter the result with the variables.

- hosts: all
  gather_facts: True
  become: True
  vars:
     whitelist:
         - /boot
         - /home
         - /opt
         - /var
         - /bin
         - /usr

  tasks:
  - name: extract mount_points 
    set_fact:
      mount_point: "{{ansible_facts.mounts | selectattr('fstype', 'in', ['ext2', 'ext3', 'ext4']) | map(attribute='mount') | list }}"

  - debug:
      var: mount_point
    vars:
      query: "[?starts_with(mount, whitelist)].mount"

When I execute the playbook I get this

ok: [[email protected]] => {
    "mount_point": [
        "/", 
        "/boot", 
        "/tmp", 
        "/home", 
        "/var", 
        "/var/opt", 
        "/var/tmp", 
        "/var/log", 
        "/var/log/audit", 
        "/opt", 
    ]
}

/tmp is included which means that query: "[?starts_with(mount, whitelist)].mount" was skipped and I don’t know how to achieve the playbook goal.

Solution

You don’t really need a json query here IMO. An easy way is to filter the list with match and construct a regex containing all possible prefixes:

- name: show my filtered mountpoints:
  vars:
    start_regex: "{{ whitelist | map('regex_escape') | join('|') }}"
  degug:
    msg: "{{ {{ansible_facts.mounts | selectattr('fstype', 'in', ['ext2', 'ext3', 'ext4'])
          | map(attribute='mount') | select('match', start_regex) | list }}"
   

Answered By – Zeitounator

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published