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?
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`'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With