--- - name: Analyze Disk Space and Identify Large Directories hosts: all gather_facts: true vars: scan_paths: - "/" - "/var" - "/home" - "/opt" - "/usr" - "/tmp" max_depth: 5 size_threshold_gb: 1 output_file: "/tmp/disk_space_report_{{ ansible_date_time.iso8601_basic_short }}.json" tasks: - name: Get overall disk usage command: df -h register: df_output changed_when: false - name: Get inode usage command: df -i register: df_inode_output changed_when: false - name: Analyze directory sizes shell: >- du -h -d{{ max_depth }} {{ item }} 2>/dev/null | grep -E '^[0-9]+\.?[0-9]*G' | awk '{print $1 "\t" $2}' | sort -hr loop: "{{ scan_paths }}" register: dir_sizes changed_when: false failed_when: false - name: Find files larger than threshold find: paths: "{{ item }}" size: "{{ (size_threshold_gb * 1024 * 1024 * 1024) | int }}" recurse: true loop: "{{ scan_paths }}" register: large_files failed_when: false - name: Generate disk space report copy: dest: "{{ output_file }}" content: >- { "hostname": "{{ ansible_hostname }}", "ip_address": "{{ ansible_default_ipv4.address | default(ansible_ssh_host | default('unknown')) }}", "os": "{{ ansible_distribution }} {{ ansible_distribution_version }}", "analysis_date": "{{ ansible_date_time.iso8601 }}", "disk_usage_output": "{{ df_output.stdout | default('') }}", "inode_usage_output": "{{ df_inode_output.stdout | default('') }}", "scan_parameters": { "paths": {{ scan_paths | to_json }}, "max_depth": {{ max_depth }}, "size_threshold_gb": {{ size_threshold_gb }} }, "summary": { "scan_paths_count": {{ scan_paths | length }}, "large_files_count": {{ large_files.results | sum(attribute='matched') | default(0) }} } } mode: '0600' - name: Display disk space summary debug: msg: - "Disk space analysis completed on {{ ansible_hostname }}" - "Large files found: {{ large_files.results | sum(attribute='matched') | default(0) }}" - "Report saved to: {{ output_file }}" - name: Return disk space findings set_fact: disk_space_report: hostname: ansible_hostname ip_address: ansible_default_ipv4.address | default(ansible_ssh_host | default('unknown')) os: ansible_distribution + ' ' + ansible_distribution_version analysis_date: ansible_date_time.iso8601 report_file: output_file