Ansible: summing the data disk space

The context

On each host, I want to calculate the volume occupied by the OS and data disks. The OS is always installed on sda. The data disks are sdb, sdc, ...
facter_disks provides info on the disks. I use the attribute size_bytes.
The size of OS is easy to get: facter_disks.sda.size_bytes.
However, it's less obvious to sum up the other disks since you don't know how many disks you have. Remember Ansible does not allow nested loops. Well, at least explicitely...

The solution

  1. Extract sdb, sdc,.. from facter_disks
  2. Convert it to a list
  3. Loop on this list to extract the path to attribute size_bytes
  4. Sum up the values
  5. (optional) Add the sum to facts
- hosts: all
  gather_facts: true
  become: yes
  become_method: sudo
  ignore_errors: yes

  tasks:
    - set_fact:
        os_disk_total_size_gb: "{{facter_disks.sda.size_bytes/1073741824}}"
        data_disks_total_size_gb: "{{ facter_disks | map('regex_search', 'sd[b-z]+') | select('string') | list | map('extract', facter_disks, 'size_bytes') | sum / 1073741824 }}"

    - debug:
        msg: "{{ os_disk_total_size_gb }}, {{ data_disks_total_size_gb }}"

Comments

Popular Posts