homelab_automation/ansible/playbooks/builtin/_builtin_collect_cpu_info.yml

51 lines
2.0 KiB
YAML

---
# Builtin Playbook: Collecte des informations CPU
- name: Collect CPU Information
hosts: all
become: false
gather_facts: true
vars:
_builtin_playbook: true
_builtin_id: collect_cpu_info
_collect_metrics: true
tasks:
- name: Get CPU load averages
ansible.builtin.shell: cat /proc/loadavg | awk '{print $1, $2, $3}'
register: cpu_load
changed_when: false
- name: Get CPU temperature
ansible.builtin.shell: |
if [ -f /sys/class/thermal/thermal_zone0/temp ]; then
cat /sys/class/thermal/thermal_zone0/temp | awk '{printf "%.1f", $1/1000}'
else
echo "null"
fi
register: cpu_temp
changed_when: false
ignore_errors: true
- name: Get CPU usage percentage
ansible.builtin.shell: |
top -bn1 | grep "Cpu(s)" | awk '{print 100 - $8}' 2>/dev/null || echo "0"
register: cpu_usage
changed_when: false
ignore_errors: true
- name: Build metrics output
ansible.builtin.set_fact:
metrics_output:
host: "{{ inventory_hostname }}"
data:
cpu_count: "{{ ansible_processor_vcpus | default(ansible_processor_count, true) | default(1) }}"
cpu_model: "{{ ansible_processor[2] | default('Unknown', true) if (ansible_processor is defined and ansible_processor | length > 2) else 'Unknown' }}"
cpu_load_1m: "{{ cpu_load.stdout.split()[0] | default('0', true) | float }}"
cpu_load_5m: "{{ cpu_load.stdout.split()[1] | default('0', true) | float }}"
cpu_load_15m: "{{ cpu_load.stdout.split()[2] | default('0', true) | float }}"
cpu_usage_percent: "{{ cpu_usage.stdout | default('0', true) | float }}"
cpu_temperature: "{{ cpu_temp.stdout if (cpu_temp.stdout is defined and cpu_temp.stdout != 'null') else '' }}"
- name: Output metrics
ansible.builtin.debug:
msg: "METRICS_JSON_START:{{ metrics_output | to_json }}:METRICS_JSON_END"