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


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
         - /boot
         - /home
         - /opt
         - /var
         - /bin
         - /usr

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

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

When I execute the playbook I get this

ok: [[email protected]] => {
    "mount_point": [

/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.


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:
    start_regex: "{{ whitelist | map('regex_escape') | join('|') }}"
    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