---

- name: Deploy node_exporter
  hosts: all
  become: true
  vars:
    node_exporter_user: node_exporter
    node_exporter_group: node_exporter
    node_exporter_port: 9100
    org: prometheus
    repo: node_exporter
    version: 1.8.2
    filename: node_exporter-{{ version }}.linux-amd64
    project_url: https://github.com/{{ org }}/{{ repo }}/releases/download/v{{ version }}
  tasks:

    - name: Download {{ filename }}
      ansible.builtin.get_url:
        url: '{{ project_url }}/{{ filename }}.tar.gz'
        dest: /tmp/{{ filename }}.tar.gz
        mode: '0440'
      tags:
        - download

    - name: Unarchive {{ filename }}
      ansible.builtin.unarchive:
        src: /tmp/{{ filename }}.tar.gz
        dest: /tmp/
        remote_src: true
      tags:
        - extract

    - name: Create system group for user account {{ node_exporter_group }}
      ansible.builtin.group:
        name: "{{ node_exporter_group }}"
        system: true
        state: present
      tags:
        - configuration

    - name: Create system user account {{ node_exporter_user }}
      ansible.builtin.user:
        name: "{{ node_exporter_user }}"
        comment: Prometheus node_exporter system account
        group: "{{ node_exporter_group }}"
        system: true
        home: /var/lib/node_exporter
        create_home: false
        shell: /sbin/nologin
        state: present
      tags:
        - configuration

    - name: Copy node_exporter binary to /usr/local/bin
      ansible.builtin.copy:
        src: /tmp/{{ filename }}/node_exporter
        dest: /usr/local/bin/node_exporter
        owner: root
        group: root
        mode: '0755'
        remote_src: true
      tags:
        - configuration

    - name: Copy systemd unit file
      ansible.builtin.template:
        src: node_exporter.service.j2
        dest: /etc/systemd/system/node_exporter.service
        owner: root
        group: root
        mode: '0644'
      notify:
        - Reload systemd unit files
        - Restart node_exporter systemd service
      tags:
        - configuration

    - name: Ensure systemd service is running
      ansible.builtin.systemd_service:
        name: node_exporter.service
        state: started
        enabled: true
      tags:
        - configuration

  handlers:
    - name: Reload systemd unit files
      ansible.builtin.systemd:
        daemon_reload: true
      tags:
        - configuration

    - name: Restart node_exporter systemd service
      ansible.builtin.systemd:
        name: node_exporter.service
        state: restarted
      tags:
        - configuration
