ADD node_exporter role + molecule

This commit is contained in:
Илья Макаров 2025-06-01 13:01:59 +03:00
parent a835e2136c
commit 5675083f40
19 changed files with 364 additions and 2 deletions

View File

@ -3,5 +3,5 @@
- name: Установка и конфигурация blackbox_exporter - name: Установка и конфигурация blackbox_exporter
hosts: srv_1 hosts: srv_1
roles: roles:
- ../roles/blackbox_exporter - blackbox_exporter

View File

@ -0,0 +1,7 @@
---
- name: Установка и конфигурация node_exporter
hosts: srv_1
roles:
- node_exporter

View File

@ -19,7 +19,6 @@ platforms:
- /sys/fs/cgroup:/sys/fs/cgroup:rw - /sys/fs/cgroup:/sys/fs/cgroup:rw
pre_build_image: true pre_build_image: true
provisioner: provisioner:
name: ansible name: ansible
config_options: config_options:

View File

@ -0,0 +1,38 @@
Role Name
=========
A brief description of the role goes here.
Requirements
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
License
-------
BSD
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@ -0,0 +1,15 @@
#SPDX-License-Identifier: MIT-0
---
node_exporter_version: "1.9.0"
node_exporter_user: "node_exporter"
node_exporter_group: "node_exporter"
node_exporter_install_dir: "/opt/node_exporter"
node_exporter_listen_address: ":9100"
node_exporter_systemd_unit_path: "/etc/systemd/system/node_exporter.service"
node_exporter_symlink: "/usr/local/bin/node_exporter"

View File

@ -0,0 +1,8 @@
#SPDX-License-Identifier: MIT-0
---
- name: Update Systemd and restart Node Exporter
ansible.builtin.systemd:
name: node_exporter
state: restarted
daemon-reload: yes

View File

@ -0,0 +1,37 @@
#SPDX-License-Identifier: MIT-0
galaxy_info:
role_name: node_exporter
namespace: node_exporter
author: Илья Макаров
description: Устанавливает и обновляет Prometheus ode exporter
company: your company (optional)
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: http://example.com/issue/tracker
# Choose a valid license ID from https://spdx.org - some suggested licenses:
# - BSD-3-Clause (default)
# - MIT
# - GPL-2.0-or-later
# - GPL-3.0-only
# - Apache-2.0
# - CC-BY-4.0
license: MIT
min_ansible_version: 2.1
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
galaxy_tags: []
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags. Be sure to
# remove the '[]' above, if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
dependencies: []
# List your role dependencies here, one per line. Be sure to remove the '[]' above,
# if you add dependencies to this list.

View File

@ -0,0 +1,8 @@
---
- name: Применяем роль node_exporter
hosts: all
become: true
gather_facts: true
roles:
- role: ../../../node_exporter

View File

@ -0,0 +1,34 @@
---
dependency:
name: shell
command: echo "no dependencies"
lint: |
set -e
yamllint .
ansible-lint
driver:
name: docker
platforms:
- name: instance
image: geerlingguy/docker-rockylinux9-ansible
command: /usr/sbin/init
cgroupns_mode: host
privileged: true
volumes:
- /sys/fs/cgroup:/sys/fs/cgroup:rw
pre_build_image: true
provisioner:
name: ansible
config_options:
defaults:
verbosity: 0
interpreter_python: /usr/bin/python3.9
verifier:
name: testinfra
options:
verbose: true

View File

@ -0,0 +1,2 @@
[pytest]
testpaths = tests/

View File

@ -0,0 +1,60 @@
import os
import testinfra.utils.ansible_runner
test_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']
).get_hosts('all')
def test_user_and_group_exist(host):
"""
Проверяем, что пользователь и группа node_exporter существуют.
"""
user = host.user("node_exporter")
assert user.exists
assert user.group == "node_exporter"
def test_binary_and_symlink(host):
"""
Проверяем, что бинарник node_exporter установлен и имеет права на исполнение.
"""
binary = host.file("/opt/node_exporter/node_exporter")
symlink = host.file("/usr/local/bin/node_exporter")
assert binary.exists
assert binary.mode & 0o111
assert binary.user == "node_exporter"
assert binary.group == "node_exporter"
assert symlink.exists
assert symlink.is_symlink
assert symlink.linked_to == "/opt/node_exporter/node_exporter"
def test_service_unit_file(host):
"""
Проверяем, что systemd unit-файл для node_exporter существует и содержит правильную команду запуска.
"""
unit = host.file("/etc/systemd/system/node_exporter.service")
assert unit.exists
assert unit.user == "root"
assert unit.group == "root"
assert unit.mode == 0o644
assert unit.contains("ExecStart=/usr/local/bin/node_exporter")
def test_service_running_and_enabled(host):
"""
Проверяем, что сервис node_exporter запущен и включён в автозагрузку.
"""
svc = host.service("node_exporter")
assert svc.is_enabled
assert svc.is_running
def test_listen_port(host):
"""
Проверяем, что node_exporter слушает порт 9100.
"""
socket = host.socket("tcp://0.0.0.0:9100")
assert socket.is_listening

View File

@ -0,0 +1,32 @@
- name: Stop and disable node_exporter service
ansible.builtin.systemd:
name: node_exporter
state: stopped
enabled: no
ignore_errors: yes
- name: Remove systemd unit file for node_exporter
ansible.builtin.file:
path: "{{ node_exporter_systemd_unit_path }}"
state: absent
- name: Remove symlink /usr/local/bin/node_exporter
ansible.builtin.file:
path: /usr/local/bin/node_exporter
state: absent
- name: Remove node_exporter installation directory
ansible.builtin.file:
path: "{{ node_exporter_install_dir }}"
state: absent
- name: Remove user "{{ node_exporter_user }}"
ansible.builtin.user:
name: "{{ node_exporter_user }}"
state: absent
remove: yes
- name: Remove group "{{ node_exporter_group }}"
ansible.builtin.group:
name: "{{ node_exporter_group }}"
state: absent

View File

@ -0,0 +1,75 @@
---
# Тег install можно использовать для выборочного запуска
- name: Create group
ansible.builtin.group:
name: "{{ node_exporter_user }}"
system: yes
state: present
- name: Create user
ansible.builtin.user:
name: "{{ node_exporter_user }}"
group: "{{ node_exporter_group }}"
system: yes
shell: /sbin/nologin
- name: Create installation directory
ansible.builtin.file:
path: "{{ node_exporter_install_dir }}"
state: directory
owner: "{{ node_exporter_user }}"
group: "{{ node_exporter_group }}"
mode: '0755'
- name: Check if node_exporter archive exists locally
ansible.builtin.stat:
path: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64.tar.gz"
register: node_archive
- name: Download node_exporter archive if absent
ansible.builtin.get_url:
url: "https://github.com/prometheus/node_exporter/releases/download/v{{ node_exporter_version }}/node_exporter-{{ node_exporter_version }}.linux-amd64.tar.gz"
dest: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64.tar.gz"
mode: '0644'
when: not node_archive.stat.exists
changed_when: false
- name: Extract node_exporter binary
ansible.builtin.unarchive:
src: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64.tar.gz"
dest: "{{ node_exporter_install_dir }}"
remote_src: yes
extra_opts: [--strip-components=1]
creates: "{{ node_exporter_install_dir }}/node_exporter"
- name: Remove archive after extraction
ansible.builtin.file:
path: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64.tar.gz"
state: absent
when: node_archive.stat.exists
changed_when: false
- name: Set binary ownership and permissions
ansible.builtin.file:
path: "{{ node_exporter_install_dir }}/node_exporter"
owner: "{{ node_exporter_user }}"
group: "{{ node_exporter_group }}"
mode: '0755'
- name: Create symlink to node_exporter in /usr/local/bin
ansible.builtin.file:
src: "{{ node_exporter_install_dir }}/node_exporter"
dest: /usr/local/bin/node_exporter
state: link
- name: Deploy systemd unit for node_exporter
ansible.builtin.template:
src: node_exporter.service.j2
dest: "{{ node_exporter_systemd_unit_path }}"
notify: Update Systemd and restart Node Exporter
- name: Enable and start node_exporter service
ansible.builtin.systemd:
name: node_exporter
enabled: yes
state: started

View File

@ -0,0 +1,7 @@
#SPDX-License-Identifier: MIT-0
---
# tasks file for node_exporter
- import_tasks: install.yml
tags: install
- import_tasks: update.yml
tags: update

View File

@ -0,0 +1,12 @@
---
- name: Check current version
ansible.builtin.command: "/usr/local/bin/node_exporter --version"
register: current_version
changed_when: false
- name: Reinstall if version mismatch
block:
- import_tasks: delete.yml
- import_tasks: install.yml
when: current_version.stdout is not search(node_exporter_version)

View File

@ -0,0 +1,16 @@
[Unit]
Description=Prometheus Node Exporter
Wants=network-online.target
After=network-online.target
[Service]
User={{ node_exporter_user }}
Group={{ node_exporter_group }}
Type=simple
ExecStart={{ node_exporter_symlink }} \
--web.listen-address={{ node_exporter_listen_address }}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,3 @@
#SPDX-License-Identifier: MIT-0
localhost

View File

@ -0,0 +1,6 @@
#SPDX-License-Identifier: MIT-0
---
- hosts: localhost
remote_user: root
roles:
- node_exporter

View File

@ -0,0 +1,3 @@
#SPDX-License-Identifier: MIT-0
---
# vars file for node_exporter