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
- Extract
sdb,sdc,.. fromfacter_disks - Convert it to a list
- Loop on this list to extract the path to attribute
size_bytes - Sum up the values
- (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