- name: Extract CSV data and create summary report hosts: all ignore_unreachable: true vars: energy_label: "Energy/Ah" voltage_label: "Voltage/V" time_label: "Timestamp" output_file: "Summary.csv" previous_csv: "/var/www/html/Summary.csv" tasks: - name: Initialize output file with headers local_action: shell echo "Host,Energy,Voltage,Timestamp,Status" > "{{ output_file }}" run_once: true delegate_to: localhost - name: Process CSV data block: - name: Read CSV file from remote host ansible.builtin.shell: cat /var/www/html/Data/Status.csv register: csv_content - name: Extract energy and voltage values ansible.builtin.set_fact: energy_value: "{{ (csv_content.stdout_lines | select('search', '^' + energy_label) | first | split(','))[1] | default('Not Found') }}" voltage_value: "{{ (csv_content.stdout_lines | select('search', '^' + voltage_label) | first | split(','))[1] | default('Not Found') }}" time_value: "{{ (csv_content.stdout_lines | select('search', '^' + time_label) | first | split(','))[1] | default('Not Found') }}" - name: Append values to output file local_action: shell echo "{{ inventory_hostname }},{{ energy_value }},{{ voltage_value }},{{ time_value }},OK" >> "{{ output_file }}" delegate_to: localhost rescue: - name: Use last known values when read fails ansible.builtin.shell: | prev=$(grep "^{{ inventory_hostname }}," {{ previous_csv }} 2>/dev/null | tail -1) if [ -n "$prev" ]; then energy=$(echo "$prev" | cut -d',' -f2) voltage=$(echo "$prev" | cut -d',' -f3) timestamp=$(echo "$prev" | cut -d',' -f4) echo "{{ inventory_hostname }},$energy,$voltage,$timestamp,EI TAVOITETTU" >> "{{ output_file }}" else echo "{{ inventory_hostname }},Not Found,Not Found,Not Found,EI TAVOITETTU" >> "{{ output_file }}" fi delegate_to: localhost - name: Write last known values for unreachable host ansible.builtin.shell: | prev=$(grep "^{{ inventory_hostname }}," {{ previous_csv }} 2>/dev/null | tail -1) if [ -n "$prev" ]; then energy=$(echo "$prev" | cut -d',' -f2) voltage=$(echo "$prev" | cut -d',' -f3) timestamp=$(echo "$prev" | cut -d',' -f4) echo "{{ inventory_hostname }},$energy,$voltage,$timestamp,EI TAVOITETTU" >> "{{ output_file }}" else echo "{{ inventory_hostname }},Not Found,Not Found,Not Found,EI TAVOITETTU" >> "{{ output_file }}" fi delegate_to: localhost when: ansible_host_unreachable is defined and ansible_host_unreachable - name: Copy result file to Apache html folder hosts: localhost tasks: - name: Copy CSV file to /var/www/html/ copy: src: Summary.csv dest: /var/www/html/Summary.csv owner: www-data group: www-data mode: '0644'