# Install Node Exporter
# Deploys Prometheus node_exporter for system-level metrics collection.
# Creates a dedicated service account and systemd unit for production use.
#
# Customize:
#   - Set INVENTORY_GROUP to target hosts
#   - Set NODE_EXPORTER_VERSION to the desired release version
#   - Set LISTEN_PORT if you need a non-default port (default: 9100)

name: install-node-exporter
description: Deploy Prometheus node_exporter for system metrics collection
tags: [monitoring, prometheus, node-exporter, metrics, linux]
tool: ansible
cloud_provider: agnostic
os_family: agnostic
risk_level: low
compliance_tags: []

vars:
  INVENTORY_GROUP: "{{INVENTORY_GROUP}}"
  NODE_EXPORTER_VERSION: "{{NODE_EXPORTER_VERSION}}"
  LISTEN_PORT: "{{LISTEN_PORT}}"

playbook: |
  ---
  - hosts: "{{ inventory_group }}"
    become: true
    vars:
      version: "{{ node_exporter_version | default('1.7.0') }}"
      listen_address: "0.0.0.0:{{ listen_port | default(9100) }}"
    tasks:
      - name: Create node_exporter user
        user:
          name: node_exporter
          shell: /usr/sbin/nologin
          system: yes
          create_home: no

      - name: Download node_exporter
        get_url:
          url: "https://github.com/prometheus/node_exporter/releases/download/v{{ version }}/node_exporter-{{ version }}.linux-amd64.tar.gz"
          dest: "/tmp/node_exporter-{{ version }}.tar.gz"

      - name: Extract node_exporter
        unarchive:
          src: "/tmp/node_exporter-{{ version }}.tar.gz"
          dest: /tmp
          remote_src: yes

      - name: Install node_exporter binary
        copy:
          src: "/tmp/node_exporter-{{ version }}.linux-amd64/node_exporter"
          dest: /usr/local/bin/node_exporter
          remote_src: yes
          owner: node_exporter
          group: node_exporter
          mode: "0755"
        notify: restart node_exporter

      - name: Create systemd service
        copy:
          dest: /etc/systemd/system/node_exporter.service
          content: |
            [Unit]
            Description=Prometheus Node Exporter
            After=network-online.target

            [Service]
            User=node_exporter
            ExecStart=/usr/local/bin/node_exporter --web.listen-address={{ listen_address }}
            Restart=on-failure
            RestartSec=5

            [Install]
            WantedBy=multi-user.target
        notify: restart node_exporter

      - name: Enable and start node_exporter
        systemd:
          name: node_exporter
          enabled: yes
          state: started
          daemon_reload: yes

    handlers:
      - name: restart node_exporter
        systemd:
          name: node_exporter
          state: restarted
          daemon_reload: yes
