Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible compare two list variables

Tags:

ansible

I have to check if a list of mount points are available on the system.
So, I defined a variable with the list of mount points then extracted the available mount points from Ansible facts.

---
- hosts: all
  vars:
    required_mounts:
      - /prom/data
      - /prom/logs

  tasks:
    - name: debug mountpoint
      set_fact:
        mount_points: "{{ ansible_mounts|json_query('[].mount') }}"

    - name: check fs
      fail:
        msg: 'mount point not found'
      when: required_mounts not in mount_points

I am stuck here, I don't know how to compare the variable required_mounts with existing mount points.
If any item in required_mounts is not in the existing mount points the task should fail.

The task check fs always fail, even if the mount points are present.

Do I have to loop one by one? And compare item by item? If so, how can I achieve this?

like image 698
danidar Avatar asked Mar 11 '26 01:03

danidar


1 Answers

You can use the set theory for this, since what you are looking for is simply the difference between the required_mounts and the ansible_mounts.

Also, there is no need for a JMESPath query here, this simple requirement can be achieved with a simple map.

So, this can be achieved with the task alone:

- fail:
    msg: "Missing mounts: `{{ missing_mounts | join(', ') }}`" 
  when:  missing_mounts | length > 0
  vars:
    missing_mounts: >-
      {{ 
        required_mounts 
          | difference(
            ansible_mounts | map(attribute='mount')
          ) 
      }}

Given the playbook:

- hosts: localhost
  gather_facts: yes
  vars:
    required_mounts:
      - /etc/hostname
      - /etc/hosts
      - /tmp/not_an_actual_mount
      - /tmp/not_a_mount_either

  tasks:
    - fail:
        msg: "Missing mounts: `{{ missing_mounts | join(', ') }}`" 
      when:  missing_mounts | length > 0
      vars:
        missing_mounts: >-
          {{ 
            required_mounts 
              | difference(
                ansible_mounts | map(attribute='mount')
              ) 
          }}

This yields:

TASK [Gathering Facts] *******************************************************
ok: [localhost]

TASK [fail] ******************************************************************
fatal: [localhost]: FAILED! => changed=false 
  msg: 'Missing mounts: `/tmp/not_an_actual_mount, /tmp/not_a_mount_either`'
like image 170
β.εηοιτ.βε Avatar answered Mar 14 '26 20:03

β.εηοιτ.βε