I am trying to write an ansible playbook that checks for disk space on multiple servers.
This is my Ansible playbook so far:
---
- hosts: all
become: yes
tasks:
- name: Check / freespace
shell: df -h / | awk '{if($5 > 85)print (IP}'s
Basically what I want to do is as soon as the shell condition is met, I want to retrieve the IPs of all those servers that exceed 85%.
I’d recommend using Ansible fact ansible_mounts
to get the list of mounted devices and their details.
This fact will give us:
- total space in
size_total
- free space in
size_available
So we can get the percentage of free space with:
size_available / size_total x 100 = free space
The example task below will show the device if free space is less than 15%:
# Use this task if "gather_facts" is disabled
- name: collect ansible_mounts facts
setup:
filter: ansible_mounts
- name: Show Devices having less than 15% free space
debug:
msg: "Device with > 85% use: {{ item.device }}"
when: item.size_available / item.size_total * 100 < 15
loop: "{{ ansible_mounts }}"
loop_control:
label: "{{ item.mount }}"
Update:
If you’d like to filter out the local device mounts, you could use regex_search
filter like not item.device | regex_search('^/dev')
in the when
condition additionally.