Ansible Playbook to Check Disk Space for Windows & Linux Part -III

solutionamardba
2 min readMar 16, 2023

--

Here’s an updated Ansible playbook that checks the disk space on Linux CentOS, Ubuntu, and Windows in a detailed manner and writes the output to a CSV file:

- name: Check disk space and write to CSV
hosts: all
become: true

tasks:
- name: Check disk space on Linux
block:
- name: Check if the system is CentOS
set_fact:
is_centos: "{{ ansible_distribution | lower == 'centos' }}"
ignore_errors: true
- name: Check if the system is Ubuntu
set_fact:
is_ubuntu: "{{ ansible_distribution | lower == 'ubuntu' }}"
ignore_errors: true
- name: Check disk space on CentOS
command: df -hT
when: is_centos | bool
register: centos_disk_space
- name: Check disk space on Ubuntu
command: df -hT
when: is_ubuntu | bool
register: ubuntu_disk_space
- name: Print disk space on CentOS
debug:
msg: "{{ centos_disk_space.stdout_lines }}"
when: is_centos | bool
- name: Print disk space on Ubuntu
debug:
msg: "{{ ubuntu_disk_space.stdout_lines }}"
when: is_ubuntu | bool
- name: Write disk space to CSV file on CentOS
when: is_centos | bool
local_action:
module: csv_writer
path: "{{ inventory_hostname }}-disk-space.csv"
headers: ['Filesystem', 'Type', 'Size', 'Used', 'Available', 'Use%', 'Mounted on']
content: "{{ centos_disk_space.stdout_lines[1:] }}"
- name: Write disk space to CSV file on Ubuntu
when: is_ubuntu | bool
local_action:
module: csv_writer
path: "{{ inventory_hostname }}-disk-space.csv"
headers: ['Filesystem', 'Type', 'Size', 'Used', 'Available', 'Use%', 'Mounted on']
content: "{{ ubuntu_disk_space.stdout_lines[1:] }}"
when: "ansible_os_family == 'RedHat' or ansible_os_family == 'Debian'"

- name: Check disk space on Windows
block:
- name: Check disk space on Windows
win_shell: Get-Volume | Select-Object -Property DriveLetter, FileSystemLabel, FileSystem, SizeRemaining, Size | ConvertTo-Csv -NoTypeInformation
register: windows_disk_space
- name: Print disk space on Windows
debug:
msg: "{{ windows_disk_space.stdout_lines }}"
- name: Write disk space to CSV file on Windows
local_action:
module: copy
content: "{{ windows_disk_space.stdout }}"
dest: "{{ inventory_hostname }}-disk-space.csv"
when: ansible_os_family == 'Windows'

Here’s what’s changed in this playbook:

  • We added two new tasks to write the disk space information to a CSV file using the csv_writer module (for Linux) and copy module (for Windows).
  • We added a headers option to specify the headers for the CSV file.
  • We removed the ignore_errors option from the set_fact tasks since we want them to fail if the distribution is not CentOS or Ubuntu.

Note that the CSV file will be created in the same directory where you run the Ansible playbook from. You can modify the path option to specify a different directory if needed.

--

--