ADD blackbox role + mole

This commit is contained in:
Илья Макаров 2025-05-31 17:38:08 +03:00
parent 216da45c80
commit a835e2136c
23 changed files with 405 additions and 1 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
venv/
robertdebock*
__pycache__/

View File

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

View File

@ -1,5 +1,6 @@
---
- name: Ensure fail2ban is installed and configured
- name: Установка и конфигурация fail2aban
hosts: srv_1
roles:
- ../roles/fail2ban

5
requirements.txt Normal file
View File

@ -0,0 +1,5 @@
molecule
molecule-vagrant
molecule-plugins[docker]
testinfra
ansible-lint

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,11 @@
---
# defaults file for blackcox_exporter
blackbox_exporter_version: "0.26.0"
blackbox_exporter_user: "blackbox_exporter"
blackbox_exporter_group: "blackbox_exporter"
blackbox_exporter_install_dir: "/opt/blackbox_exporter"
blackbox_exporter_config_path: "/etc/blackbox_exporter/blackbox.yml"
blackbox_exporter_web_listen_address: ":9115"

View File

@ -0,0 +1,9 @@
---
# handlers file for blackcox_exporter
# хэндлер вызывается при изменении шаблона или конфигурации
- name: Перезапустить Blackbox Exporter
ansible.builtin.systemd:
name: blackbox_exporter
state: restarted
daemon-reload: yes

View File

@ -0,0 +1,55 @@
galaxy_info:
author: Ilya Makarov
description: your role description
company: your company (optional)
role_name: blackbox_exporter
namespace: blackbox_exporter
# 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: license (GPL-2.0-or-later, MIT, etc)
min_ansible_version: 2.1
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
#
# Provide a list of supported platforms, and for each platform a list of versions.
# If you don't wish to enumerate all versions for a particular platform, use 'all'.
# To view available platforms and versions (or releases), visit:
# https://galaxy.ansible.com/api/v1/platforms/
#
# platforms:
# - name: Fedora
# versions:
# - all
# - 25
# - name: SomePlatform
# versions:
# - all
# - 1.0
# - 7
# - 99.99
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: Применяем роль blackbox_exporter
hosts: all
become: true
gather_facts: true
roles:
- role: ../../../blackbox_exporter

View File

@ -0,0 +1,41 @@
---
dependency:
name: galaxy
options:
role-file: requirements.yml
requirements-file: requirements.yml
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
lint: |
set -e
yamllint .
ansible-lint
verifier:
name: testinfra
options:
verbose: true
additional_files_or_dirs:
- tests/

View File

@ -0,0 +1,9 @@
---
- name: Prepare
hosts: all
become: true
gather_facts: false
roles:
- robertdebock.bootstrap
- robertdebock.epel

View File

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

View File

@ -0,0 +1,61 @@
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):
user = host.user("blackbox_exporter")
assert user.exists
assert user.group == "blackbox_exporter"
def test_service_enabled_and_running(host):
svc = host.service("blackbox_exporter")
assert svc.is_enabled
assert svc.is_running
def test_binary_and_symlink(host):
binary = host.file("/opt/blackbox_exporter/blackbox_exporter")
symlink = host.file("/usr/local/bin/blackbox_exporter")
assert binary.exists
assert binary.mode & 0o111
assert binary.user == "blackbox_exporter"
assert binary.group == "blackbox_exporter"
assert symlink.exists
assert symlink.is_symlink
assert symlink.linked_to == "/opt/blackbox_exporter/blackbox_exporter"
def test_config_directory(host):
cfg_dir = host.file("/etc/blackbox_exporter")
assert cfg_dir.exists
assert cfg_dir.is_directory
assert cfg_dir.user == "blackbox_exporter"
assert cfg_dir.group == "blackbox_exporter"
assert cfg_dir.mode == 0o755
def test_config_file(host):
cfg = host.file("/etc/blackbox_exporter/blackbox.yml")
assert cfg.exists
assert cfg.user == "blackbox_exporter"
assert cfg.group == "blackbox_exporter"
assert cfg.mode == 0o644
assert cfg.contains("modules:")
assert cfg.contains("http_2xx")
def test_systemd_unit_file(host):
unit = host.file("/etc/systemd/system/blackbox_exporter.service")
assert unit.exists
assert unit.user == "root"
assert unit.group == "root"
assert unit.mode == 0o644
assert unit.contains("ExecStart=/usr/local/bin/blackbox_exporter")
def test_listen_socket(host):
socket = host.socket("tcp://0.0.0.0:9115")
assert socket.is_listening
def test_logs_exist(host):
journalctl = host.check_output("journalctl -u blackbox_exporter --no-pager")
assert "Listening on" in journalctl or "level=info" in journalctl

View File

@ -0,0 +1,6 @@
---
roles:
- name: robertdebock.bootstrap
- name: robertdebock.epel
collections:
- name: community.general

View File

@ -0,0 +1,10 @@
---
- name: Deploy blackbox_exporter config
ansible.builtin.template:
src: blackbox.yml.j2
dest: "{{ blackbox_exporter_config_path }}"
owner: "{{ blackbox_exporter_user }}"
group: "{{ blackbox_exporter_group }}"
mode: '0644'
notify: Перезапустить Blackbox Exporter

View File

@ -0,0 +1,78 @@
- name: Создаём групу
ansible.builtin.group:
name: "{{ blackbox_exporter_group }}"
system: yes
state: present
- name: Создаём пользователя
ansible.builtin.user:
name: "{{ blackbox_exporter_user }}"
group: "{{ blackbox_exporter_user }}"
system: yes
shell: /sbin/nologin
create_home: no
- name: Проверяем, существует ли архив
ansible.builtin.stat:
path: "/tmp/blackbox_exporter-{{ blackbox_exporter_version }}.tar.gz"
register: archive_stat
- name: Загружаем архив экспортера, если не существует
ansible.builtin.get_url:
url: "https://github.com/prometheus/blackbox_exporter/releases/download/v{{ blackbox_exporter_version }}/blackbox_exporter-{{ blackbox_exporter_version }}.linux-amd64.tar.gz"
dest: "/tmp/blackbox_exporter-{{ blackbox_exporter_version }}.tar.gz"
mode: '0644'
when: not archive_stat.stat.exists
changed_when: false
- name: Создаём целевую директорию
ansible.builtin.file:
path: "{{ blackbox_exporter_install_dir }}"
state: directory
mode: '0755'
owner: "{{ blackbox_exporter_user }}"
group: "{{ blackbox_exporter_user }}"
- name: Разархивируем файл архива
ansible.builtin.unarchive:
src: "/tmp/blackbox_exporter-{{ blackbox_exporter_version }}.tar.gz"
dest: "{{ blackbox_exporter_install_dir }}"
owner: "{{ blackbox_exporter_user }}"
group: "{{ blackbox_exporter_user }}"
mode: "0755"
remote_src: yes
extra_opts: [--strip-components=1]
creates: "{{ blackbox_exporter_install_dir }}/blackbox_exporter" # предотвращает повторную распаковку
- name: Удляем архив после разархивации
ansible.builtin.file:
path: "/tmp/blackbox_exporter-{{ blackbox_exporter_version }}.tar.gz"
state: absent
changed_when: false
- name: Создаём симовлическую ссылку на бинарный файл
ansible.builtin.file:
src: "{{ blackbox_exporter_install_dir }}/blackbox_exporter"
dest: /usr/local/bin/blackbox_exporter
state: link
- name: Создаём каталог для конфигурационного файла
ansible.builtin.file:
path: "{{ blackbox_exporter_config_path | dirname }}"
state: directory
owner: "{{ blackbox_exporter_user }}"
group: "{{ blackbox_exporter_group }}"
mode: '0755'
- name: Создаём systemd юнит
ansible.builtin.template:
src: blackbox_exporter.service.j2
dest: /etc/systemd/system/blackbox_exporter.service
mode: '0644'
notify: Перезапустить Blackbox Exporter
- name: Enable and start service
ansible.builtin.systemd:
name: blackbox_exporter
enabled: yes
state: started

View File

@ -0,0 +1,9 @@
---
# tasks file for blackcox_exporter
- import_tasks: install.yml
tags: install
- import_tasks: config.yml
tags: config
- import_tasks: update.yml
tags: update

View File

@ -0,0 +1,10 @@
---
- name: Check current version
ansible.builtin.command: "/usr/local/bin/blackbox_exporter --version"
register: current_version
changed_when: false
- name: Reinstall if version mismatch
import_tasks: install.yml
when: current_version.stdout is not search('v' ~ blackbox_exporter_version)

View File

@ -0,0 +1,13 @@
modules:
http_2xx:
prober: http
timeout: 5s
http:
valid_http_versions: ["HTTP/1.1", "HTTP/2"]
method: GET
tls_config:
insecure_skip_verify: false
tcp_connect:
prober: tcp
timeout: 5s

View File

@ -0,0 +1,19 @@
[Unit]
Description=Prometheus Blackbox Exporter
Wants=network-online.target
After=network-online.target
[Service]
User={{ blackbox_exporter_user }}
Group={{ blackbox_exporter_group }}
AmbientCapabilities=CAP_NET_RAW
CapabilityBoundingSet=CAP_NET_RAW
ExecStart=/usr/local/bin/blackbox_exporter \
--config.file={{ blackbox_exporter_config_path }} \
--web.listen-address={{ blackbox_exporter_web_listen_address }}
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,2 @@
localhost

View File

@ -0,0 +1,5 @@
---
- hosts: localhost
remote_user: root
roles:
- blackcox_exporter

View File

@ -0,0 +1,2 @@
---
# vars file for blackcox_exporter