Ansible to check diskspace for mounts mentioned as variable

Viewed 39827

I am new to ansible and currently working on a play which will see if disk space of remote machines has reached 70% threshold. If they have reached it should throw error.

i found a good example at : Using ansible to manage disk space

but at this example the mount names are hard coded. And my requirement is to pass them dynamically. So i wrote below code which seems to not work:

    name: test for available disk space
    assert:
    that: 
    - not {{ item.mount == '{{mountname}}' and ( item.size_available < 
    item.size_total - ( item.size_total|float * 0.7 ) ) }}
    with_items: '{{ansible_mounts}}'
    ignore_errors: yes
    register: disk_free

    name: Fail the play
    fail: msg="disk space has reached 70% threshold"
    when: disk_free|failed

This play works when i use:

item.mount == '/var/app'

Is there any way to enter mountname dynamically ? and can i enter multiple mount names ??

I am using ansible 2.3 on rhel

Thanks in advance :)

3 Answers

For those who cannot use selectattr (like me), here is a variant of the first answer using when and with_items to select the mount point to check.

name: 'Ensure that free space on {{ mountname }} is grater than 30%'
assert:
  that: item.size_available > item.size_total|float * 0.3
  msg: 'disk space has reached 70% threshold'
when: item.mount == mountname
with_items: '{{ ansible_mounts }}'

Note: To be able to use the variable {{ ansible_mounts }} you need to turn gather_facts to yes that can be limited to gather_subset=!all,hardware.

I'm running Ansible 2.5 and was able to get Konstantin Suvorov's solution to work with a slight mod by adding with_items. Sample code below:

- name: Ensure that free space on the tested volume is greater than 15%
  assert:
    that:
      - mount.size_available > mount.size_total|float * 0.15
    msg: Disk space has reached 85% threshold
  vars:
    mount: "{{ ansible_mounts | selectattr('mount','equalto',item.mount) | list | first }}"
  with_items:
    - "{{ ansible_mounts }}"
Related