11 Commits

Author SHA1 Message Date
d22bbd3dba feat: add PostgreSQL infrastructure for App2
- Add PostgreSQL role for installing and configuring PostgreSQL 17
- Add postgres_exporter role for PostgreSQL metrics collection
- Add deploy-postgres-app2.yml playbook for deployment
- Configure test database 'testdb' with user 'testuser'
- Set up postgres_exporter user for monitoring
- Include firewall configuration for PostgreSQL (5432) and postgres_exporter (9187)
- Follow existing role structure pattern from node_exporter
2026-02-04 07:27:56 +00:00
d70c2813de Merge branch 'feature/nginx-app1-deployment' 2026-02-04 05:42:38 +00:00
14d945e7b5 Добавлена конфигурация мониторинга Nginx и финальные правки для app1 2026-02-04 05:40:03 +00:00
ad387df05d Merge pull request 'Add nginx role and playbook for App1 deployment' (#4) from feature/nginx-app1-deployment into main
Reviewed-on: #4
2026-02-04 04:41:03 +00:00
b1fc6bcf3c Add nginx role and playbook for App1 deployment
- Complete nginx role with official repository setup
- Configuration placed in conf.d/ for proper inclusion
- Working stub_status endpoints (/status, /nginx_status)
- Custom HTML template with monitoring information
- Cleanup of default Nginx configurations
- Ready for deployment on App1 (192.168.0.110)
2026-02-04 03:49:11 +00:00
5fa246356a Merge pull request 'Добавлена установка Grafana: роли, плейбуки и конфигурация' (#3) from feature/grafana-installation into main
Reviewed-on: #3
2026-02-04 02:38:59 +00:00
17dd0fddff Добавлена установка Grafana: роли, плейбуки и конфигурация 2026-02-04 02:28:50 +00:00
0abdb8b0a5 Merge pull request 'feat: Добавлена установка Node Exporter на все хосты' (#2) from feature/prometheus-installation into main
Reviewed-on: #2
2026-02-03 04:44:22 +00:00
26f6832275 feat: Добавлена установка Node Exporter на все хосты
- Создана роль node_exporter для установки на LXC контейнеры
- Добавлен плейбук deploy_all_node_exporters.yml
- Настроен ansible.cfg для правильного поиска ролей
- Node Exporter успешно установлен на все 10 хостов
- Prometheus собирает метрики со всех Node Exporters
- Все 14 таргетов в состоянии UP
2026-02-03 04:43:05 +00:00
1bab23c929 Merge pull request 'feat: Add Prometheus installation role and playbook' (#1) from feature/prometheus-installation into main
Reviewed-on: #1
2026-02-03 02:29:20 +00:00
8212b75ac9 feat: Add Prometheus installation role and playbook
- Created Prometheus role with automated installation
- Version: 2.48.1
- Configured remote_write to VictoriaMetrics (192.168.0.104:8428)
- Added scrape configs for monitoring infrastructure
- Created systemd service configuration
- Successfully tested on 192.168.0.105
2026-02-03 02:26:22 +00:00
45 changed files with 2406 additions and 0 deletions

View File

@ -3,6 +3,7 @@ inventory = inventories/production/hosts
host_key_checking = False
interpreter_python = /usr/bin/python3
gathering = smart
roles_path = ./roles
[ssh_connection]
pipelining = True

View File

@ -24,3 +24,6 @@ ansible_ssh_private_key_file=~/.ssh/id_ansible
[all_except_ansible:children]
infrastructure
applications
[grafana]
192.168.0.106 # pvestandt1-grafana

View File

@ -0,0 +1,35 @@
---
- name: Add PostgreSQL exporter to Prometheus
hosts: 192.168.0.105
become: yes
tasks:
- name: Add postgres_exporter scrape config
blockinfile:
path: /etc/prometheus/prometheus.yml
insertafter: ' # Nginx metrics via nginx-prometheus-exporter'
block: |2
# PostgreSQL metrics via postgres_exporter
- job_name: 'postgres-app2'
scrape_interval: 15s
scrape_timeout: 10s
static_configs:
- targets: ['192.168.0.111:9187']
labels:
instance: 'app2'
service: 'postgresql'
job: 'postgres'
metric_relabel_configs:
- source_labels: [__address__]
target_label: instance
- source_labels: [__address__]
regex: '([^:]+):\\d+'
replacement: '${1}'
target_label: host
marker: "# {mark} ANSIBLE MANAGED BLOCK - postgres_exporter"
backup: yes
- name: Reload Prometheus
systemd:
name: prometheus
state: reloaded

View File

@ -0,0 +1,102 @@
---
- name: Configure Nginx monitoring in Prometheus
hosts: 192.168.0.105
become: yes
tasks:
- name: Check if nginx config already exists
stat:
path: /etc/prometheus/nginx-app1.yml
register: nginx_config
- name: Create Nginx scrape config
copy:
content: |
# Nginx stub_status metrics
- job_name: 'nginx-app1'
scrape_interval: 15s
scrape_timeout: 10s
metrics_path: /status
static_configs:
- targets: ['192.168.0.110:80']
labels:
instance: 'app1'
service: 'nginx'
job: 'nginx'
metric_relabel_configs:
- source_labels: [__address__]
target_label: instance
- source_labels: [__address__]
regex: '([^:]+):\d+'
replacement: '${1}'
target_label: host
dest: /etc/prometheus/nginx-app1.yml
owner: root
group: root
mode: '0644'
when: not nginx_config.stat.exists
register: config_created
- name: Include nginx config in prometheus.yml
lineinfile:
path: /etc/prometheus/prometheus.yml
line: ' - "nginx-app1.yml"'
insertafter: '^rule_files:'
state: present
register: config_modified
- name: Test Prometheus configuration
command: promtool check config /etc/prometheus/prometheus.yml
register: prometheus_test
changed_when: false
- name: Show test result
debug:
msg: "{{ prometheus_test.stdout_lines }}"
- name: Reload Prometheus if config changed
systemd:
name: prometheus
state: reloaded
when: (config_created.changed or config_modified.changed) and prometheus_test.rc == 0
- name: Wait for Prometheus to reload
pause:
seconds: 3
- name: Verify Nginx target in Prometheus
shell: |
curl -s "http://localhost:9090/api/v1/targets" | python3 -c "
import json, sys
data = json.load(sys.stdin)
for target in data['data']['activeTargets']:
if 'nginx' in target['labels'].get('job', ''):
print(f\"Found nginx target: {target['labels']} - Health: {target['health']}\")
"
register: target_check
changed_when: false
ignore_errors: yes
- name: Show target check result
debug:
msg: "{{ target_check.stdout_lines if target_check.stdout_lines else 'Nginx target not found' }}"
- name: Check if nginx metrics are available
shell: |
# Wait a bit for metrics to appear
sleep 2
curl -s "http://localhost:9090/api/v1/query?query=up{job='nginx-app1'}" | python3 -c "
import json, sys
data = json.load(sys.stdin)
if data['status'] == 'success' and data['data']['result']:
for result in data['data']['result']:
print(f\"Nginx metrics UP: {result['metric']}\")
else:
print(\"Nginx metrics not available yet\")
"
register: metrics_check
changed_when: false
- name: Show metrics check result
debug:
msg: "{{ metrics_check.stdout_lines }}"

View File

@ -0,0 +1,49 @@
---
- name: Deploy Nginx with load testing features on App1
hosts: 192.168.0.110
become: yes
gather_facts: yes
roles:
- role: nginx
tasks:
- name: Verify Nginx installation
uri:
url: "http://{{ ansible_default_ipv4.address }}"
status_code: 200
timeout: 10
register: nginx_check
until: nginx_check.status == 200
retries: 5
delay: 5
ignore_errors: yes
- name: Test API endpoints
uri:
url: "http://{{ ansible_default_ipv4.address }}{{ item }}"
status_code: 200
timeout: 5
loop:
- /api/test
- /api/metrics
register: api_test
ignore_errors: yes
- name: Display deployment result
debug:
msg: |
✅ Nginx with load testing deployed on {{ inventory_hostname }}!
🌐 Main page: http://{{ ansible_default_ipv4.address }}
📊 Status page: http://{{ ansible_default_ipv4.address }}/status
🔧 Test APIs:
- http://{{ ansible_default_ipv4.address }}/api/test
- http://{{ ansible_default_ipv4.address }}/api/slow
- http://{{ ansible_default_ipv4.address }}/api/error
- http://{{ ansible_default_ipv4.address }}/api/metrics
📈 Monitoring:
- Node metrics: http://{{ ansible_default_ipv4.address }}:9100/metrics
- Prometheus: http://192.168.0.105:9090
- Grafana: http://192.168.0.106:3000
🎯 Load testing interface ready with JavaScript controls!

View File

@ -0,0 +1,12 @@
---
- name: Deploy PostgreSQL and Postgres Exporter on App2
hosts: 192.168.0.111
become: yes
gather_facts: yes
roles:
- role: postgresql
tags: postgresql
- role: postgres_exporter
tags: postgres_exporter

View File

@ -0,0 +1,61 @@
---
- name: Final fix for App1 Nginx configuration
hosts: 192.168.0.110
become: yes
tasks:
- name: Deploy final Nginx configuration
template:
src: "/root/projects/ansible-config/roles/nginx/templates/app1.conf.j2"
dest: /etc/nginx/conf.d/app1.conf
owner: root
group: root
mode: '0644'
- name: Test Nginx configuration
command: nginx -t
register: nginx_test
changed_when: false
- name: Show test result
debug:
msg: "{{ nginx_test.stdout_lines }}"
- name: Reload Nginx
systemd:
name: nginx
state: reloaded
when: nginx_test.rc == 0
- name: Test all endpoints
shell: |
echo "=== Testing endpoints ==="
for endpoint in /api/test /health /status /nginx_status; do
echo -n "$endpoint: "
curl -s -o /dev/null -w "%{http_code}" http://localhost$endpoint && echo " OK" || echo " FAILED"
done
register: endpoint_test
changed_when: false
- name: Show endpoint test results
debug:
msg: "{{ endpoint_test.stdout_lines }}"
- name: Verify endpoints return JSON
shell: |
echo "=== Checking JSON responses ==="
curl -s http://localhost/api/test | python3 -m json.tool && echo "API Test: OK" || echo "API Test: FAILED"
curl -s http://localhost/health | python3 -m json.tool && echo "Health: OK" || echo "Health: FAILED"
register: json_test
changed_when: false
ignore_errors: yes
- name: Final status check
debug:
msg: |
✅ App1 Nginx configuration fixed!
🌐 Access: http://192.168.0.110
📊 Status: http://192.168.0.110/status
🔧 API Test: http://192.168.0.110/api/test
💚 Health: http://192.168.0.110/health
📈 Node metrics: http://192.168.0.110:9100/metrics

View File

@ -0,0 +1,46 @@
---
- name: Install and Configure Prometheus
hosts: 192.168.0.105 # Prometheus container
become: yes
gather_facts: yes
pre_tasks:
- name: Update apt cache
apt:
update_cache: yes
cache_valid_time: 3600
- name: Install required packages
apt:
name:
- curl
- wget
- ca-certificates
state: present
roles:
- role: ../../roles/prometheus
post_tasks:
- name: Verify Prometheus is accessible from target host
uri:
url: "http://localhost:9090/metrics"
status_code: 200
- name: Check VictoriaMetrics connectivity from Prometheus
uri:
url: "http://192.168.0.104:8428/health"
status_code: 200
- name: Display access information
debug:
msg:
- "========================================="
- "Prometheus installed successfully!"
- "========================================="
- "Web UI: http://{{ ansible_host }}:9090"
- "Metrics: http://{{ ansible_host }}:9090/metrics"
- "Targets: http://{{ ansible_host }}:9090/targets"
- "Configuration: /etc/prometheus/prometheus.yml"
- "Data directory: /var/lib/prometheus"
- "========================================="

View File

@ -0,0 +1,65 @@
---
- name: Install nginx-prometheus-exporter on App1
hosts: 192.168.0.110
become: yes
tasks:
- name: Download nginx-prometheus-exporter
get_url:
url: https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.11.0/nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
dest: /tmp/nginx-exporter.tar.gz
- name: Extract nginx-exporter
unarchive:
src: /tmp/nginx-exporter.tar.gz
dest: /usr/local/bin/
remote_src: yes
creates: /usr/local/bin/nginx-prometheus-exporter
- name: Create systemd service
copy:
content: |
[Unit]
Description=NGINX Prometheus Exporter
After=network.target nginx.service
[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/nginx-prometheus-exporter -nginx.scrape-uri=http://localhost:80/status
Restart=on-failure
[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/nginx-exporter.service
owner: root
group: root
mode: '0644'
- name: Enable and start nginx-exporter
systemd:
name: nginx-exporter
state: started
enabled: yes
daemon_reload: yes
- name: Test nginx-exporter
uri:
url: http://localhost:9113/metrics
status_code: 200
register: exporter_test
ignore_errors: yes
- name: Show test result
debug:
msg: "Nginx exporter test: {{ 'SUCCESS' if exporter_test.status == 200 else 'FAILED' }}"
- name: Verify metrics
shell: |
curl -s http://localhost:9113/metrics | grep -i nginx | head -5
register: metrics_check
changed_when: false
- name: Show metrics check
debug:
msg: "{{ metrics_check.stdout_lines }}"

View File

@ -0,0 +1,47 @@
---
- name: Check Grafana installation status
hosts: grafana
become: yes
tasks:
- name: Check Grafana service
systemd:
name: grafana
register: service_status
- name: Check if Grafana is listening on port
wait_for:
port: 3000
host: 127.0.0.1
timeout: 10
state: started
register: port_status
- name: Check Grafana API health
uri:
url: "http://localhost:3000/api/health"
method: GET
status_code: 200
timeout: 10
register: api_status
ignore_errors: yes
- name: Get Grafana version
command: /usr/local/bin/grafana-server --version
register: version_info
changed_when: false
ignore_errors: yes
- name: Display Grafana status report
debug:
msg: |
📊 Статус Grafana на {{ inventory_hostname }}:
Служба: {{ "✅ Запущена" if service_status.status.ActiveState == "active" else "❌ Остановлена" }}
Порт 3000: {{ "✅ Открыт" if port_status.state == "started" else "❌ Закрыт" }}
API: {{ "✅ Доступен (HTTP " ~ api_status.status ~ ")" if api_status.status == 200 else "❌ Недоступен" }}
{% if version_info is succeeded %}
Версия: {{ version_info.stdout_lines[-1] | regex_search('Version ([0-9.]+)') | default('Неизвестна') }}
{% else %}
Версия: Не удалось определить
{% endif %}

View File

@ -0,0 +1,55 @@
---
- name: Clean up Grafana completely
hosts: grafana
become: yes
tasks:
- name: Stop and disable Grafana service
systemd:
name: grafana
state: stopped
enabled: no
daemon_reload: yes
ignore_errors: yes
- name: Remove systemd service file
file:
path: /etc/systemd/system/grafana.service
state: absent
- name: Remove symlinks
file:
path: "{{ item }}"
state: absent
loop:
- /usr/local/bin/grafana-server
- /usr/local/bin/grafana-cli
- name: Remove Grafana directories
file:
path: "{{ item }}"
state: absent
loop:
- /usr/share/grafana
- /usr/share/grafana-*
- /var/lib/grafana
- /var/log/grafana
- /etc/grafana
- name: Remove temporary files
file:
path: /tmp/grafana-*.tar.gz
state: absent
- name: Remove Grafana user and group
user:
name: grafana
state: absent
remove: yes
- name: Reload systemd
systemd:
daemon_reload: yes
- name: Verify cleanup
debug:
msg: "✅ Grafana полностью удалена с хоста {{ inventory_hostname }}"

View File

@ -0,0 +1,15 @@
---
- name: Deploy Node Exporter to ALL hosts
hosts: all
become: yes
gather_facts: yes
pre_tasks:
- name: Update apt cache
apt:
update_cache: yes
when: ansible_os_family == 'Debian'
roles:
- role: node_exporter
tags: node_exporter

View File

@ -0,0 +1,9 @@
---
- name: Install and configure Grafana
hosts: grafana
become: yes
vars:
grafana_version: "12.3.2"
grafana_admin_password: "admin"
roles:
- grafana

View File

@ -0,0 +1,47 @@
---
- name: Install and configure Grafana (with health checks)
hosts: grafana
become: yes
vars:
grafana_version: "12.3.2"
grafana_admin_password: "admin"
tasks:
- name: Include Grafana role
include_role:
name: grafana
- name: Final verification from control node
delegate_to: localhost
run_once: yes
block:
- name: Wait for Grafana to be fully ready
pause:
seconds: 30
prompt: "Waiting for Grafana to complete initialization..."
- name: Test Grafana access from control node
uri:
url: "http://{{ hostvars[groups['grafana'][0]]['ansible_default_ipv4']['address'] | default(groups['grafana'][0]) }}:3000/api/health"
method: GET
status_code: 200
timeout: 30
register: final_check
until: final_check.status == 200
retries: 12 # 12 попыток * 5 секунд = 60 секунд
delay: 5
- name: Display final success message
debug:
msg: |
🎉 Grafana успешно установлена и готова к работе!
Доступ по адресу: http://{{ hostvars[groups['grafana'][0]]['ansible_default_ipv4']['address'] | default(groups['grafana'][0]) }}:3000
Логин: admin
Пароль: {{ grafana_admin_password }}
Для проверки выполните команду:
curl http://{{ hostvars[groups['grafana'][0]]['ansible_default_ipv4']['address'] | default(groups['grafana'][0]) }}:3000/api/health
Или откройте в браузере:
http://{{ hostvars[groups['grafana'][0]]['ansible_default_ipv4']['address'] | default(groups['grafana'][0]) }}:3000

View File

@ -0,0 +1,4 @@
---
grafana_admin_password: "admin"
grafana_version: "12.3.2"
grafana_archive_type: "tar.gz" # или "zip"

View File

@ -0,0 +1,6 @@
---
- name: restart grafana
systemd:
name: grafana
state: restarted
daemon_reload: yes

View File

@ -0,0 +1,142 @@
---
- name: Debug - Show Grafana version
debug:
msg: "Устанавливаем Grafana версии {{ grafana_version }}"
tags: grafana
- name: Install minimal dependencies
apt:
name:
- curl
- adduser
- libfontconfig1
- tar
- gzip
- procps
state: present
update_cache: yes
tags: grafana
- name: Create Grafana user and group
user:
name: grafana
system: yes
shell: /bin/false
home: /usr/share/grafana
comment: "Grafana Server"
tags: grafana
- name: Create Grafana data/log/config directories
file:
path: "{{ item }}"
state: directory
owner: grafana
group: grafana
mode: '0755'
loop:
- /var/lib/grafana
- /var/log/grafana
- /etc/grafana
tags: grafana
- name: Download Grafana from official site
get_url:
url: "https://dl.grafana.com/oss/release/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
dest: "/tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
timeout: 300
validate_certs: no
tags: grafana
- name: Show download info
debug:
msg: "Grafana скачан: /tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
tags: grafana
- name: Extract Grafana archive
unarchive:
src: "/tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
dest: "/usr/share/"
remote_src: yes
owner: grafana
group: grafana
creates: "/usr/share/grafana-{{ grafana_version }}"
tags: grafana
- name: Remove existing /usr/share/grafana if it exists (cleanup)
file:
path: /usr/share/grafana
state: absent
tags: grafana
- name: Create symlink from extracted version
file:
src: "/usr/share/grafana-{{ grafana_version }}"
dest: "/usr/share/grafana"
state: link
owner: grafana
group: grafana
tags: grafana
- name: Create binary symlinks
file:
src: "/usr/share/grafana/bin/{{ item }}"
dest: "/usr/local/bin/{{ item }}"
state: link
owner: root
group: root
loop:
- grafana-server
- grafana-cli
tags: grafana
- name: Create Grafana configuration directory
file:
path: /etc/grafana
state: directory
owner: grafana
group: grafana
mode: '0755'
tags: grafana
- name: Configure Grafana
template:
src: grafana.ini.j2
dest: /etc/grafana/grafana.ini
owner: grafana
group: grafana
mode: '0644'
notify: restart grafana
tags: grafana
- name: Install systemd service
template:
src: grafana.service.j2
dest: /etc/systemd/system/grafana.service
owner: root
group: root
mode: '0644'
notify: restart grafana
tags: grafana
- name: Reload systemd
systemd:
daemon_reload: yes
tags: grafana
- name: Enable and start Grafana service
systemd:
name: grafana
enabled: yes
state: started
daemon_reload: yes
tags: grafana
- name: Wait and verify Grafana is fully operational
include_tasks: wait_and_verify.yml
tags: grafana
- name: Clean up temporary files
file:
path: "/tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
state: absent
tags: grafana

View File

@ -0,0 +1,68 @@
---
- name: Wait for Grafana to start (initial wait)
wait_for:
timeout: 30
tags: grafana
- name: Check if Grafana is listening on port 3000 (with retries)
wait_for:
port: 3000
host: 127.0.0.1
delay: 10
timeout: 300 # 5 минут максимум
state: started
register: grafana_port_check
tags: grafana
- name: Debug port check result
debug:
msg: "Grafana port check: {{ grafana_port_check.state }} after {{ grafana_port_check.elapsed }} seconds"
tags: grafana
- name: Wait for Grafana API to be ready
uri:
url: "http://localhost:3000/api/health"
method: GET
status_code: 200
timeout: 30
register: grafana_api_check
until: grafana_api_check.status == 200
retries: 30 # 30 попыток * 5 секунд = 150 секунд
delay: 5
tags: grafana
- name: Debug API check result
debug:
msg: "Grafana API responded with HTTP {{ grafana_api_check.status }} after {{ grafana_api_check.attempts }} attempts"
tags: grafana
- name: Verify Grafana installation (final check)
block:
- name: Check Grafana service status
systemd:
name: grafana
register: grafana_service_status
tags: grafana
- name: Check Grafana version
command: /usr/local/bin/grafana-server --version
register: grafana_version_check
changed_when: false
tags: grafana
- name: Show installation summary
debug:
msg: |
✅ Grafana успешно установлена!
Версия: {{ grafana_version_check.stdout_lines[-1] | regex_search('Version ([0-9.]+)') | default('12.3.2') }}
Служба: {{ grafana_service_status.status.ActiveState }}
Порт 3000: {{ 'открыт' if grafana_port_check.state == 'started' else 'закрыт' }}
API: {{ 'доступен' if grafana_api_check.status == 200 else 'недоступен' }}
Время установки: {{ grafana_port_check.elapsed | default(0) | round(2) }} секунд
Доступ по адресу: http://{{ inventory_hostname }}:3000
Логин: admin
Пароль: {{ grafana_admin_password | default('admin') }}
tags: grafana
tags: grafana

View File

@ -0,0 +1,27 @@
[server]
http_port = 3000
domain = 0.0.0.0
root_url = http://%s:3000
router_logging = true
enable_gzip = false
[security]
admin_user = admin
admin_password = {{ grafana_admin_password | default('admin') }}
[database]
type = sqlite3
path = /var/lib/grafana/grafana.db
[session]
provider = file
[analytics]
reporting_enabled = false
check_for_updates = false
[paths]
data = /var/lib/grafana
logs = /var/log/grafana
plugins = /var/lib/grafana/plugins
provisioning = /etc/grafana/provisioning

View File

@ -0,0 +1,24 @@
[Unit]
Description=Grafana Server
Documentation=https://grafana.com/docs
After=network.target
[Service]
Type=simple
User=grafana
Group=grafana
ExecStart=/usr/share/grafana/bin/grafana-server \
--config=/etc/grafana/grafana.ini \
--homepath=/usr/share/grafana \
--packaging=tar
Restart=on-failure
RestartSec=10
LimitNOFILE=10000
Environment="GF_PATHS_HOME=/usr/share/grafana"
Environment="GF_PATHS_CONFIG=/etc/grafana/grafana.ini"
Environment="GF_PATHS_DATA=/var/lib/grafana"
Environment="GF_PATHS_LOGS=/var/log/grafana"
Environment="GF_PATHS_PLUGINS=/var/lib/grafana/plugins"
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,4 @@
---
grafana_admin_password: "admin"
grafana_version: "12.3.2"
grafana_archive_type: "tar.gz" # или "zip"

View File

@ -0,0 +1,6 @@
---
- name: restart grafana
systemd:
name: grafana
state: restarted
daemon_reload: yes

View File

@ -0,0 +1,142 @@
---
- name: Debug - Show Grafana version
debug:
msg: "Устанавливаем Grafana версии {{ grafana_version }}"
tags: grafana
- name: Install minimal dependencies
apt:
name:
- curl
- adduser
- libfontconfig1
- tar
- gzip
- procps
state: present
update_cache: yes
tags: grafana
- name: Create Grafana user and group
user:
name: grafana
system: yes
shell: /bin/false
home: /usr/share/grafana
comment: "Grafana Server"
tags: grafana
- name: Create Grafana data/log/config directories
file:
path: "{{ item }}"
state: directory
owner: grafana
group: grafana
mode: '0755'
loop:
- /var/lib/grafana
- /var/log/grafana
- /etc/grafana
tags: grafana
- name: Download Grafana from official site
get_url:
url: "https://dl.grafana.com/oss/release/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
dest: "/tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
timeout: 300
validate_certs: no
tags: grafana
- name: Show download info
debug:
msg: "Grafana скачан: /tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
tags: grafana
- name: Extract Grafana archive
unarchive:
src: "/tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
dest: "/usr/share/"
remote_src: yes
owner: grafana
group: grafana
creates: "/usr/share/grafana-{{ grafana_version }}"
tags: grafana
- name: Remove existing /usr/share/grafana if it exists (cleanup)
file:
path: /usr/share/grafana
state: absent
tags: grafana
- name: Create symlink from extracted version
file:
src: "/usr/share/grafana-{{ grafana_version }}"
dest: "/usr/share/grafana"
state: link
owner: grafana
group: grafana
tags: grafana
- name: Create binary symlinks
file:
src: "/usr/share/grafana/bin/{{ item }}"
dest: "/usr/local/bin/{{ item }}"
state: link
owner: root
group: root
loop:
- grafana-server
- grafana-cli
tags: grafana
- name: Create Grafana configuration directory
file:
path: /etc/grafana
state: directory
owner: grafana
group: grafana
mode: '0755'
tags: grafana
- name: Configure Grafana
template:
src: grafana.ini.j2
dest: /etc/grafana/grafana.ini
owner: grafana
group: grafana
mode: '0644'
notify: restart grafana
tags: grafana
- name: Install systemd service
template:
src: grafana.service.j2
dest: /etc/systemd/system/grafana.service
owner: root
group: root
mode: '0644'
notify: restart grafana
tags: grafana
- name: Reload systemd
systemd:
daemon_reload: yes
tags: grafana
- name: Enable and start Grafana service
systemd:
name: grafana
enabled: yes
state: started
daemon_reload: yes
tags: grafana
- name: Wait and verify Grafana is fully operational
include_tasks: wait_and_verify.yml
tags: grafana
- name: Clean up temporary files
file:
path: "/tmp/grafana-{{ grafana_version }}.linux-amd64.tar.gz"
state: absent
tags: grafana

View File

@ -0,0 +1,110 @@
---
- name: Phase 1: Initial wait for Grafana to start
pause:
seconds: 60
prompt: "Phase 1/5: Initial wait for Grafana startup (60 seconds)..."
tags: grafana
- name: Check if Grafana service is active (with retries)
shell: |
systemctl is-active grafana
register: grafana_active
until: grafana_active.stdout == "active"
retries: 60 # 60 * 5 = 300 секунд (5 минут)
delay: 5
tags: grafana
- name: Phase 2: Wait for database migrations (wave 1)
pause:
seconds: 180
prompt: "Phase 2/5: Waiting for database migrations (180 seconds)..."
tags: grafana
- name: Phase 3: Wait for plugins installation (wave 2)
pause:
seconds: 180
prompt: "Phase 3/5: Waiting for plugins installation (180 seconds)..."
tags: grafana
- name: Phase 4: Wait for HTTP server startup (wave 3)
pause:
seconds: 180
prompt: "Phase 4/5: Waiting for HTTP server startup (180 seconds)..."
tags: grafana
- name: Check if port 3000 is listening (with very long timeout)
wait_for:
port: 3000
host: 127.0.0.1
timeout: 600 # 10 минут
state: started
register: port_check
tags: grafana
- name: Phase 5: Final verification (wave 4)
pause:
seconds: 120
prompt: "Phase 5/5: Final verification (120 seconds)..."
tags: grafana
- name: Check Grafana API health (with many retries)
uri:
url: "http://localhost:3000/api/health"
method: GET
status_code: 200
timeout: 10
register: api_check
until: api_check.status == 200
retries: 60 # 60 * 5 = 300 секунд (5 минут)
delay: 5
tags: grafana
- name: Calculate total wait time
set_fact:
total_wait_time: "{{ 60 + 180 + 180 + 180 + 120 }}"
tags: grafana
- name: Show installation success with detailed info
debug:
msg: |
🎉 Grafana успешно установлена и готова к работе!
⏱️ Общее время установки: {{ total_wait_time }} секунд
📊 Статус компонентов:
• Служба: ✅ {{ grafana_active.stdout }}
• Порт 3000: {{ '✅ открыт' if port_check is defined and port_check.state == 'started' else '❌ закрыт' }}
• API: {{ '✅ доступен (HTTP ' ~ api_check.status ~ ')' if api_check is defined and api_check.status == 200 else '❌ недоступен' }}
🔗 Доступ:
• URL: http://{{ inventory_hostname }}:3000
• Логин: admin
• Пароль: {{ grafana_admin_password | default('admin') }}
📋 Для проверки выполните:
curl http://{{ inventory_hostname }}:3000/api/health
💡 Примечание: Первый запуск Grafana занимает время из-за:
1. Миграций базы данных
2. Установки плагинов по умолчанию
3. Инициализации сервиса
Последующие запуски будут значительно быстрее.
tags: grafana
- name: Final check from control node (optional)
delegate_to: localhost
run_once: yes
when: false # Отключено по умолчанию, можно включить
tags: grafana
block:
- name: Test external access
uri:
url: "http://{{ hostvars[groups['grafana'][0]]['ansible_default_ipv4']['address'] | default(groups['grafana'][0]) }}:3000/api/health"
method: GET
status_code: 200
timeout: 30
register: external_check
- name: Show external access result
debug:
msg: "External access: {{ '✅ успешно' if external_check.status == 200 else '❌ недоступно' }}"

View File

@ -0,0 +1,27 @@
[server]
http_port = 3000
domain = 0.0.0.0
root_url = http://localhost:3000
router_logging = true
enable_gzip = false
[security]
admin_user = admin
admin_password = {{ grafana_admin_password | default('admin') }}
[database]
type = sqlite3
path = /var/lib/grafana/grafana.db
[session]
provider = file
[analytics]
reporting_enabled = false
check_for_updates = false
[paths]
data = /var/lib/grafana
logs = /var/log/grafana
plugins = /var/lib/grafana/plugins
provisioning = /etc/grafana/provisioning

View File

@ -0,0 +1,24 @@
[Unit]
Description=Grafana Server
Documentation=https://grafana.com/docs
After=network.target
[Service]
Type=simple
User=grafana
Group=grafana
ExecStart=/usr/share/grafana/bin/grafana-server \
--config=/etc/grafana/grafana.ini \
--homepath=/usr/share/grafana \
--packaging=tar
Restart=on-failure
RestartSec=10
LimitNOFILE=10000
Environment="GF_PATHS_HOME=/usr/share/grafana"
Environment="GF_PATHS_CONFIG=/etc/grafana/grafana.ini"
Environment="GF_PATHS_DATA=/var/lib/grafana"
Environment="GF_PATHS_LOGS=/var/log/grafana"
Environment="GF_PATHS_PLUGINS=/var/lib/grafana/plugins"
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,13 @@
---
# Handlers for Nginx role
- name: reload nginx
systemd:
name: nginx
state: reloaded
daemon_reload: yes
- name: restart nginx
systemd:
name: nginx
state: restarted
daemon_reload: yes

113
roles/nginx/tasks/main.yml Normal file
View File

@ -0,0 +1,113 @@
---
# Установка и настройка Nginx - финальная версия (без echo модуля)
- name: Install prerequisites
apt:
name:
- curl
- wget
- software-properties-common
- ca-certificates
- gnupg2
state: present
update_cache: yes
tags: nginx
- name: Create keyrings directory
file:
path: /etc/apt/keyrings
state: directory
mode: '0755'
tags: nginx
- name: Download and add Nginx GPG key
shell: |
curl -fsSL https://nginx.org/keys/nginx_signing.key | gpg --dearmor -o /etc/apt/keyrings/nginx.gpg
chmod 644 /etc/apt/keyrings/nginx.gpg
args:
creates: /etc/apt/keyrings/nginx.gpg
tags: nginx
- name: Add Nginx repository
apt_repository:
repo: "deb [signed-by=/etc/apt/keyrings/nginx.gpg] http://nginx.org/packages/ubuntu {{ ansible_distribution_release }} nginx"
state: present
filename: nginx-official
update_cache: yes
tags: nginx
- name: Install Nginx
apt:
name: nginx
state: latest
update_cache: yes
tags: nginx
- name: Create custom web directory
file:
path: /var/www/app1
state: directory
owner: www-data
group: www-data
mode: '0755'
tags: nginx
- name: Deploy test index.html
template:
src: index.html.j2
dest: /var/www/app1/index.html
owner: www-data
group: www-data
mode: '0644'
tags: nginx
- name: Remove default Nginx configurations
file:
path: "{{ item }}"
state: absent
loop:
- /etc/nginx/conf.d/default.conf
- /etc/nginx/conf.d/default.conf.backup
- /etc/nginx/sites-enabled/default
tags: nginx
notify: reload nginx
- name: Deploy Nginx configuration for app1 in conf.d
template:
src: app1.conf.j2
dest: /etc/nginx/conf.d/app1.conf
owner: root
group: root
mode: '0644'
tags: nginx
notify: reload nginx
- name: Remove old sites-available config if exists
file:
path: /etc/nginx/sites-available/app1
state: absent
tags: nginx
- name: Remove old sites-enabled symlink if exists
file:
path: /etc/nginx/sites-enabled/app1
state: absent
tags: nginx
- name: Test Nginx configuration
command: nginx -t
register: nginx_test
changed_when: false
tags: nginx
- name: Display Nginx test result
debug:
msg: "{{ nginx_test.stdout_lines }}"
tags: nginx
- name: Enable and start Nginx service
systemd:
name: nginx
state: started
enabled: yes
daemon_reload: yes
tags: nginx

View File

@ -0,0 +1,72 @@
# App1 Nginx configuration
server {
listen 80;
server_name _;
root /var/www/app1;
index index.html;
# Main page
location / {
try_files $uri $uri/ =404;
}
# Nginx status for monitoring
location /status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.0.0/24;
deny all;
}
# Alternative status endpoint
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 192.168.0.0/24;
deny all;
}
# Test endpoints for load generation
location /api/test {
add_header Content-Type application/json;
add_header Cache-Control "no-cache";
return 200 '{"status": "ok", "timestamp": "$time_iso8601", "server": "app1", "request_id": "$request_id", "method": "$request_method"}';
}
location /api/slow {
add_header Content-Type application/json;
add_header Cache-Control "no-cache";
# Simple JSON response
return 200 '{"status": "slow_endpoint", "message": "Endpoint for testing", "timestamp": "$time_iso8601"}';
}
location /api/error {
add_header Content-Type application/json;
add_header Cache-Control "no-cache";
# Simple error endpoint
return 500 '{"status": "error", "code": 500, "message": "Test error response", "request_id": "$request_id"}';
}
location /api/random {
add_header Content-Type application/json;
add_header Cache-Control "no-cache";
# Random response - always success but different messages
return 200 '{"status": "random", "timestamp": "$time_iso8601", "value": "$msec", "message": "Random endpoint response"}';
}
location /api/metrics {
add_header Content-Type application/json;
add_header Cache-Control "no-cache";
return 200 '{"server": "app1", "timestamp": "$time_iso8601", "available_endpoints": ["/api/test", "/api/slow", "/api/error", "/api/random", "/api/metrics", "/health", "/status"]}';
}
# Health check endpoint
location /health {
add_header Content-Type application/json;
access_log off;
return 200 '{"status": "healthy", "service": "nginx", "timestamp": "$time_iso8601", "version": "$nginx_version"}';
}
}

View File

@ -0,0 +1,307 @@
<!DOCTYPE html>
<html>
<head>
<title>Test App1 - Nginx Load Test</title>
<meta charset="UTF-8">
<style>
body {
font-family: Arial, sans-serif;
margin: 40px;
background-color: #f4f4f9;
color: #333;
}
.container {
max-width: 1000px;
margin: 0 auto;
padding: 20px;
background-color: white;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 { color: #2c3e50; border-left: 5px solid #3498db; padding-left: 15px; }
.panel {
background-color: #e8f4fc;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
border-left: 4px solid #3498db;
}
.metrics-panel {
background-color: #e8f8ef;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
border-left: 4px solid #2ecc71;
}
.load-panel {
background-color: #fff3cd;
padding: 20px;
border-radius: 8px;
margin: 20px 0;
border-left: 4px solid #f39c12;
}
button {
padding: 10px 20px;
margin: 5px;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
font-weight: bold;
}
.btn-primary { background-color: #3498db; color: white; }
.btn-success { background-color: #2ecc71; color: white; }
.btn-warning { background-color: #f39c12; color: white; }
.btn-danger { background-color: #e74c3c; color: white; }
.stats { display: flex; gap: 20px; margin-top: 20px; }
.stat-box {
flex: 1;
padding: 15px;
background: white;
border-radius: 5px;
text-align: center;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
}
#log {
background: #f8f9fa;
padding: 15px;
border-radius: 5px;
height: 200px;
overflow-y: auto;
font-family: monospace;
font-size: 12px;
border: 1px solid #ddd;
}
.status-icon::before {
content: "✓";
color: green;
font-weight: bold;
margin-right: 5px;
}
.error-icon::before {
content: "✗";
color: red;
font-weight: bold;
margin-right: 5px;
}
</style>
</head>
<body>
<div class="container">
<h1>Test Application 1 - Nginx Load Testing</h1>
<div class="panel">
<h3>Server Information</h3>
<p><strong>Hostname:</strong> {{ ansible_hostname }}</p>
<p><strong>IP Address:</strong> {{ ansible_default_ipv4.address }}</p>
<p><strong>Role:</strong> Web Server (Nginx)</p>
<p><strong>Deployed:</strong> {{ ansible_date_time.date }}</p>
</div>
<div class="load-panel">
<h3>Load Testing Controls</h3>
<div>
<button class="btn-primary" onclick="startLoadTest('light')">Light Load (1-5 req/sec)</button>
<button class="btn-success" onclick="startLoadTest('medium')">Medium Load (10-20 req/sec)</button>
<button class="btn-warning" onclick="startLoadTest('heavy')">Heavy Load (50-100 req/sec)</button>
<button class="btn-danger" onclick="stopLoadTest()">Stop Load Test</button>
</div>
<div style="margin-top: 20px;">
<label>Custom Requests: </label>
<input type="number" id="requestCount" value="100" min="1" max="10000" style="width: 80px;">
<button class="btn-primary" onclick="sendCustomRequests()">Send Requests</button>
<button class="btn-warning" onclick="generateTraffic()">Generate Random Traffic</button>
</div>
<div class="stats">
<div class="stat-box">
<h4>Requests Sent</h4>
<div id="requestsCount">0</div>
</div>
<div class="stat-box">
<h4>Successful</h4>
<div id="successCount">0</div>
</div>
<div class="stat-box">
<h4>Failed</h4>
<div id="failedCount">0</div>
</div>
<div class="stat-box">
<h4>Active Tests</h4>
<div id="activeTests">0</div>
</div>
</div>
</div>
<div class="metrics-panel">
<h3>Monitoring & Metrics</h3>
<p>Node Exporter: <a href="http://{{ ansible_default_ipv4.address }}:9100/metrics" target="_blank">:9100/metrics</a></p>
<p>Nginx Status: <a href="http://{{ ansible_default_ipv4.address }}/status" target="_blank">/status</a></p>
<p>Nginx Metrics: <a href="http://{{ ansible_default_ipv4.address }}/nginx_status" target="_blank">/nginx_status</a></p>
<h4>API Endpoints:</h4>
<div style="font-family: monospace; font-size: 12px; background: #f8f9fa; padding: 10px; border-radius: 5px;">
<div><a href="/api/test" target="_blank">/api/test</a> - Test endpoint</div>
<div><a href="/api/error" target="_blank">/api/error</a> - Error endpoint (500)</div>
<div><a href="/api/random" target="_blank">/api/random</a> - Random response</div>
<div><a href="/api/metrics" target="_blank">/api/metrics</a> - API info</div>
<div><a href="/health" target="_blank">/health</a> - Health check</div>
</div>
<h4>Quick Links:</h4>
<div>
<a href="http://192.168.0.106:3000" target="_blank">Grafana Dashboard</a> |
<a href="http://192.168.0.105:9090" target="_blank">Prometheus UI</a> |
<a href="http://192.168.0.100:3000" target="_blank">Git/Forgejo</a>
</div>
</div>
<div>
<h3>Request Log</h3>
<div id="log"></div>
</div>
</div>
<script>
let loadTestInterval = null;
let activeTests = 0;
let requestsSent = 0;
let successCount = 0;
let failedCount = 0;
function logMessage(message, type = 'info') {
const logDiv = document.getElementById('log');
const timestamp = new Date().toLocaleTimeString();
const icon = type === 'error' ? '<span class="error-icon"></span>' :
type === 'success' ? '<span class="status-icon"></span>' : '>';
const color = type === 'error' ? 'red' : type === 'success' ? 'green' : '#666';
logDiv.innerHTML = `<div style="color: ${color}; margin: 2px 0;">${icon} [${timestamp}] ${message}</div>` + logDiv.innerHTML;
}
function updateStats() {
document.getElementById('requestsCount').textContent = requestsSent;
document.getElementById('successCount').textContent = successCount;
document.getElementById('failedCount').textContent = failedCount;
document.getElementById('activeTests').textContent = activeTests;
}
async function sendRequest(endpoint = '/') {
requestsSent++;
updateStats();
try {
const startTime = Date.now();
const response = await fetch(endpoint);
const endTime = Date.now();
const duration = endTime - startTime;
if (response.ok) {
successCount++;
logMessage(`Request ${requestsSent} to ${endpoint}: ${duration}ms (${response.status})`, 'success');
} else {
failedCount++;
logMessage(`Request ${requestsSent} to ${endpoint}: Failed (${response.status})`, 'error');
}
} catch (error) {
failedCount++;
logMessage(`Request ${requestsSent} to ${endpoint}: Error - ${error.message}`, 'error');
}
}
function startLoadTest(intensity) {
if (loadTestInterval) {
clearInterval(loadTestInterval);
}
let interval;
let endpoints = ['/', '/api/test', '/api/random', '/health'];
switch(intensity) {
case 'light':
interval = 200; // 5 req/sec
logMessage('Starting LIGHT load test (5 req/sec)');
break;
case 'medium':
interval = 50; // 20 req/sec
logMessage('Starting MEDIUM load test (20 req/sec)');
break;
case 'heavy':
interval = 10; // 100 req/sec
logMessage('Starting HEAVY load test (100 req/sec)');
break;
}
activeTests++;
updateStats();
loadTestInterval = setInterval(() => {
const endpoint = endpoints[Math.floor(Math.random() * endpoints.length)];
sendRequest(endpoint);
}, interval);
}
function stopLoadTest() {
if (loadTestInterval) {
clearInterval(loadTestInterval);
loadTestInterval = null;
activeTests = Math.max(0, activeTests - 1);
updateStats();
logMessage('Load test stopped');
}
}
function sendCustomRequests() {
const count = parseInt(document.getElementById('requestCount').value);
const endpoints = ['/', '/api/test', '/api/error', '/api/random', '/health'];
logMessage(`Sending ${count} custom requests`);
activeTests++;
updateStats();
let completed = 0;
for (let i = 0; i < count; i++) {
setTimeout(() => {
const endpoint = endpoints[Math.floor(Math.random() * endpoints.length)];
sendRequest(endpoint);
completed++;
if (completed === count) {
activeTests--;
updateStats();
logMessage(`Completed ${count} custom requests`);
}
}, i * 10); // Stagger requests
}
}
function generateTraffic() {
logMessage('Starting random traffic generation');
activeTests++;
updateStats();
const endpoints = ['/', '/api/test', '/api/error', '/api/random', '/health'];
const randomTrafficInterval = setInterval(() => {
if (Math.random() > 0.7) { // 30% chance to send request
const endpoint = endpoints[Math.floor(Math.random() * endpoints.length)];
sendRequest(endpoint);
}
}, 100);
// Stop after 2 minutes
setTimeout(() => {
clearInterval(randomTrafficInterval);
activeTests--;
updateStats();
logMessage('Random traffic generation stopped');
}, 120000);
}
// Initialize with some log messages
logMessage('App1 Load Testing Interface Ready');
logMessage(`Server: {{ ansible_hostname }} ({{ ansible_default_ipv4.address }})`);
logMessage('Use buttons above to generate load for monitoring');
</script>
</body>
</html>

View File

@ -0,0 +1,59 @@
---
# Install nginx-prometheus-exporter
- name: Download nginx-prometheus-exporter
get_url:
url: https://github.com/nginxinc/nginx-prometheus-exporter/releases/download/v0.11.0/nginx-prometheus-exporter_0.11.0_linux_amd64.tar.gz
dest: /tmp/nginx-exporter.tar.gz
tags: nginx_exporter
- name: Extract nginx-exporter
unarchive:
src: /tmp/nginx-exporter.tar.gz
dest: /tmp/
remote_src: yes
creates: /tmp/nginx-prometheus-exporter
tags: nginx_exporter
- name: Install nginx-exporter binary
copy:
src: /tmp/nginx-prometheus-exporter
dest: /usr/local/bin/nginx-prometheus-exporter
remote_src: yes
mode: '0755'
tags: nginx_exporter
- name: Create systemd service for nginx-exporter
copy:
content: |
[Unit]
Description=NGINX Prometheus Exporter
After=network.target
[Service]
Type=simple
User=root
ExecStart=/usr/local/bin/nginx-prometheus-exporter -nginx.scrape-uri=http://localhost:80/status
Restart=on-failure
[Install]
WantedBy=multi-user.target
dest: /etc/systemd/system/nginx-exporter.service
owner: root
group: root
mode: '0644'
tags: nginx_exporter
- name: Enable and start nginx-exporter
systemd:
name: nginx-exporter
state: started
enabled: yes
daemon_reload: yes
tags: nginx_exporter
- name: Open firewall port for nginx-exporter
ufw:
rule: allow
port: '9113'
proto: tcp
tags: nginx_exporter

View File

@ -0,0 +1,3 @@
---
node_exporter_version: "1.7.0"
node_exporter_port: 9100

View File

@ -0,0 +1,103 @@
---
- name: Install required packages
apt:
name:
- wget
- tar
state: present
update_cache: yes
tags: node_exporter
- name: Create node_exporter user
user:
name: node_exporter
system: yes
shell: /bin/false
home: /nonexistent
comment: "Node Exporter Service User"
tags: node_exporter
- name: Download Node Exporter
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 }}.tar.gz"
timeout: 30
validate_certs: no
tags: node_exporter
- name: Extract Node Exporter
unarchive:
src: "/tmp/node_exporter-{{ node_exporter_version }}.tar.gz"
dest: "/tmp/"
remote_src: yes
creates: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64"
tags: node_exporter
- name: Install Node Exporter binary
copy:
src: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64/node_exporter"
dest: "/usr/local/bin/node_exporter"
owner: node_exporter
group: node_exporter
mode: '0755'
remote_src: yes
tags: node_exporter
- name: Create systemd service for LXC
template:
src: node_exporter.service.j2
dest: /etc/systemd/system/node_exporter.service
owner: root
group: root
mode: '0644'
tags: node_exporter
- name: Create textfile collector directory
file:
path: /var/lib/node_exporter/textfile_collector
state: directory
owner: node_exporter
group: node_exporter
mode: '0755'
tags: node_exporter
- name: Clean up temp files
file:
path: "/tmp/node_exporter-{{ node_exporter_version }}.tar.gz"
state: absent
tags: node_exporter
- name: Clean up extracted directory
file:
path: "/tmp/node_exporter-{{ node_exporter_version }}.linux-amd64"
state: absent
tags: node_exporter
- name: Reload systemd
systemd:
daemon_reload: yes
tags: node_exporter
- name: Enable and start Node Exporter
systemd:
name: node_exporter
enabled: yes
state: started
daemon_reload: yes
tags: node_exporter
- name: Configure UFW for Node Exporter
ufw:
rule: allow
port: "{{ node_exporter_port }}"
proto: tcp
comment: "Node Exporter metrics"
tags: node_exporter
- name: Verify Node Exporter is running
wait_for:
port: "{{ node_exporter_port }}"
host: "{{ ansible_host }}"
delay: 3
timeout: 60
tags: node_exporter

View File

@ -0,0 +1,30 @@
[Unit]
Description=Node Exporter
After=network.target
Wants=network.target
[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter \
--collector.cpu \
--collector.diskstats \
--collector.filesystem \
--collector.loadavg \
--collector.meminfo \
--collector.netdev \
--collector.netstat \
--collector.stat \
--collector.time \
--collector.uname \
--collector.vmstat \
--collector.systemd \
--collector.textfile \
--web.listen-address=:{{ node_exporter_port }}
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,12 @@
---
# Postgres Exporter
postgres_exporter_version: "0.15.0"
postgres_exporter_port: 9187
postgres_exporter_user: "postgres_exporter"
postgres_exporter_password: "exporterpassword123"
# Connection settings
postgres_exporter_data_source_name: "user={{ postgres_exporter_user }} password={{ postgres_exporter_password }} host=localhost port=5432 dbname=postgres sslmode=disable"
# Systemd service
postgres_exporter_service_name: "postgres_exporter"

View File

@ -0,0 +1,94 @@
---
- name: Install required packages
apt:
name:
- wget
- tar
state: present
update_cache: yes
tags: postgres_exporter
- name: Create postgres_exporter user
user:
name: postgres_exporter
system: yes
shell: /bin/false
home: /nonexistent
comment: "Postgres Exporter Service User"
tags: postgres_exporter
- name: Download Postgres Exporter
get_url:
url: "https://github.com/prometheus-community/postgres_exporter/releases/download/v{{ postgres_exporter_version }}/postgres_exporter-{{ postgres_exporter_version }}.linux-amd64.tar.gz"
dest: "/tmp/postgres_exporter-{{ postgres_exporter_version }}.tar.gz"
timeout: 30
validate_certs: no
tags: postgres_exporter
- name: Extract Postgres Exporter
unarchive:
src: "/tmp/postgres_exporter-{{ postgres_exporter_version }}.tar.gz"
dest: "/tmp/"
remote_src: yes
creates: "/tmp/postgres_exporter-{{ postgres_exporter_version }}.linux-amd64"
tags: postgres_exporter
- name: Install Postgres Exporter binary
copy:
src: "/tmp/postgres_exporter-{{ postgres_exporter_version }}.linux-amd64/postgres_exporter"
dest: "/usr/local/bin/postgres_exporter"
owner: postgres_exporter
group: postgres_exporter
mode: '0755'
remote_src: yes
tags: postgres_exporter
- name: Create systemd service
template:
src: postgres_exporter.service.j2
dest: /etc/systemd/system/{{ postgres_exporter_service_name }}.service
owner: root
group: root
mode: '0644'
tags: postgres_exporter
- name: Clean up temp files
file:
path: "/tmp/postgres_exporter-{{ postgres_exporter_version }}.tar.gz"
state: absent
tags: postgres_exporter
- name: Clean up extracted directory
file:
path: "/tmp/postgres_exporter-{{ postgres_exporter_version }}.linux-amd64"
state: absent
tags: postgres_exporter
- name: Reload systemd
systemd:
daemon_reload: yes
tags: postgres_exporter
- name: Enable and start Postgres Exporter
systemd:
name: "{{ postgres_exporter_service_name }}"
enabled: yes
state: started
daemon_reload: yes
tags: postgres_exporter
- name: Configure UFW for Postgres Exporter
ufw:
rule: allow
port: "{{ postgres_exporter_port }}"
proto: tcp
comment: "Postgres Exporter metrics"
tags: postgres_exporter
- name: Verify Postgres Exporter is running
wait_for:
port: "{{ postgres_exporter_port }}"
host: "{{ ansible_host }}"
delay: 3
timeout: 60
tags: postgres_exporter

View File

@ -0,0 +1,16 @@
[Unit]
Description=Postgres Exporter
After=network.target postgresql.service
Wants=postgresql.service
[Service]
Type=simple
User=postgres_exporter
Group=postgres_exporter
Environment=DATA_SOURCE_NAME="{{ postgres_exporter_data_source_name }}"
ExecStart=/usr/local/bin/postgres_exporter --web.listen-address=:{{ postgres_exporter_port }}
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,21 @@
---
# PostgreSQL
postgresql_version: "17"
postgresql_port: 5432
postgresql_listen_addresses: "*"
postgresql_data_dir: "/var/lib/postgresql/{{ postgresql_version }}/main"
# Database configuration
postgresql_databases:
- name: testdb
owner: testuser
postgresql_users:
- name: testuser
password: "testpassword123"
databases: [testdb]
privileges: ["ALL"]
# Postgres exporter user (for metrics collection)
postgres_exporter_user: "postgres_exporter"
postgres_exporter_password: "exporterpassword123"

View File

@ -0,0 +1,121 @@
---
- name: Install required packages for PostgreSQL installation
apt:
name:
- ca-certificates
- curl
- gnupg
- lsb-release
state: present
update_cache: yes
tags: postgresql
- name: Create PostgreSQL repository keyring directory
file:
path: /etc/apt/keyrings
state: directory
mode: '0755'
tags: postgresql
- name: Download and install PostgreSQL GPG key
shell: |
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg
chmod 644 /etc/apt/keyrings/postgresql.gpg
args:
creates: /etc/apt/keyrings/postgresql.gpg
tags: postgresql
- name: Add PostgreSQL repository
apt_repository:
repo: "deb [signed-by=/etc/apt/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt {{ ansible_distribution_release }}-pgdg main"
state: present
update_cache: yes
tags: postgresql
- name: Install PostgreSQL
apt:
name:
- postgresql-{{ postgresql_version }}
- postgresql-contrib-{{ postgresql_version }}
- postgresql-client-{{ postgresql_version }}
state: present
update_cache: yes
tags: postgresql
- name: Ensure PostgreSQL service is started and enabled
service:
name: postgresql@17-main
state: started
enabled: yes
tags: postgresql
- name: Configure PostgreSQL listen addresses
lineinfile:
path: "/etc/postgresql/{{ postgresql_version }}/main/postgresql.conf"
regexp: "^listen_addresses[[:space:]]*="
line: "listen_addresses = '{{ postgresql_listen_addresses }}'"
backup: yes
tags: postgresql
- name: Configure PostgreSQL authentication
lineinfile:
path: "/etc/postgresql/{{ postgresql_version }}/main/pg_hba.conf"
line: "host all all 192.168.0.0/24 md5"
insertafter: "^# IPv4 local connections:"
backup: yes
tags: postgresql
- name: Reload PostgreSQL configuration
service:
name: postgresql@17-main
state: reloaded
name: postgresql@17-main
tags: postgresql
- name: Create PostgreSQL users and databases
become: yes
become_user: postgres
community.postgresql.postgresql_user:
name: "{{ item.name }}"
password: "{{ item.password }}"
state: present
loop: "{{ postgresql_users }}"
tags: postgresql
- name: Create PostgreSQL databases
become: yes
become_user: postgres
community.postgresql.postgresql_db:
name: "{{ item.name }}"
owner: "{{ item.owner }}"
state: present
loop: "{{ postgresql_databases }}"
tags: postgresql
- name: Create postgres_exporter user for monitoring
become: yes
become_user: postgres
community.postgresql.postgresql_user:
name: "{{ postgres_exporter_user }}"
password: "{{ postgres_exporter_password }}"
state: present
tags: postgresql
- name: Grant permissions to postgres_exporter user
become: yes
become_user: postgres
community.postgresql.postgresql_privs:
database: postgres
state: present
privs: CONNECT
type: database
roles: "{{ postgres_exporter_user }}"
tags: postgresql
- name: Configure UFW for PostgreSQL
ufw:
rule: allow
port: "{{ postgresql_port }}"
proto: tcp
comment: "PostgreSQL"
tags: postgresql

View File

@ -0,0 +1,32 @@
---
# Версия Prometheus
prometheus_version: "2.48.1"
prometheus_user: prometheus
prometheus_group: prometheus
# Директории
prometheus_config_dir: /etc/prometheus
prometheus_data_dir: /var/lib/prometheus
prometheus_binary_dir: /usr/local/bin
# Настройки сервиса
prometheus_port: 9090
prometheus_retention: "7d"
prometheus_log_level: info
# VictoriaMetrics для remote_write
victoriametrics_host: "192.168.0.104"
victoriametrics_port: 8428
victoriametrics_url: "http://{{ victoriametrics_host }}:{{ victoriametrics_port }}/api/v1/write"
# Vault для метрик
vault_host: "192.168.0.103"
vault_port: 8200
vault_token: "root"
# Git/Forgejo
git_host: "192.168.0.100"
git_port: 3000
# Список хостов для node_exporter (будем добавлять позже)
node_exporter_targets: []

View File

@ -0,0 +1,13 @@
---
- name: restart prometheus
systemd:
name: prometheus
state: restarted
daemon_reload: yes
become: yes
- name: reload prometheus
uri:
url: "http://localhost:{{ prometheus_port }}/-/reload"
method: POST
become: yes

View File

@ -0,0 +1,121 @@
---
- name: Create prometheus system user
user:
name: "{{ prometheus_user }}"
shell: /bin/false
home: /nonexistent
create_home: no
system: yes
state: present
- name: Create prometheus directories
file:
path: "{{ item }}"
state: directory
owner: "{{ prometheus_user }}"
group: "{{ prometheus_group }}"
mode: '0755'
loop:
- "{{ prometheus_config_dir }}"
- "{{ prometheus_config_dir }}/rules"
- "{{ prometheus_config_dir }}/file_sd"
- "{{ prometheus_data_dir }}"
- name: Check if Prometheus is already installed
stat:
path: "{{ prometheus_binary_dir }}/prometheus"
register: prometheus_binary
- name: Check Prometheus version
shell: "{{ prometheus_binary_dir }}/prometheus --version 2>&1 | head -1 | awk '{print $3}'"
register: prometheus_installed_version
when: prometheus_binary.stat.exists
changed_when: false
failed_when: false
- name: Download and install Prometheus
block:
- name: Download Prometheus {{ prometheus_version }}
unarchive:
src: "https://github.com/prometheus/prometheus/releases/download/v{{ prometheus_version }}/prometheus-{{ prometheus_version }}.linux-amd64.tar.gz"
dest: /tmp
remote_src: yes
owner: root
group: root
mode: '0755'
- name: Copy Prometheus binaries
copy:
src: "/tmp/prometheus-{{ prometheus_version }}.linux-amd64/{{ item }}"
dest: "{{ prometheus_binary_dir }}/{{ item }}"
owner: root
group: root
mode: '0755'
remote_src: yes
loop:
- prometheus
- promtool
notify: restart prometheus
- name: Copy console libraries
copy:
src: "/tmp/prometheus-{{ prometheus_version }}.linux-amd64/{{ item }}/"
dest: "{{ prometheus_config_dir }}/{{ item }}/"
owner: "{{ prometheus_user }}"
group: "{{ prometheus_group }}"
remote_src: yes
loop:
- consoles
- console_libraries
- name: Clean up downloaded files
file:
path: "/tmp/prometheus-{{ prometheus_version }}.linux-amd64"
state: absent
when: not prometheus_binary.stat.exists or (prometheus_installed_version.stdout != prometheus_version)
- name: Configure Prometheus
template:
src: prometheus.yml.j2
dest: "{{ prometheus_config_dir }}/prometheus.yml"
owner: "{{ prometheus_user }}"
group: "{{ prometheus_group }}"
mode: '0644'
backup: yes
validate: "{{ prometheus_binary_dir }}/promtool check config %s"
notify: reload prometheus
- name: Create Prometheus systemd service
template:
src: prometheus.service.j2
dest: /etc/systemd/system/prometheus.service
mode: '0644'
notify: restart prometheus
- name: Ensure Prometheus is started and enabled
systemd:
name: prometheus
state: started
enabled: yes
daemon_reload: yes
- name: Wait for Prometheus to be ready
uri:
url: "http://localhost:{{ prometheus_port }}/metrics"
status_code: 200
register: prometheus_health
until: prometheus_health.status == 200
retries: 10
delay: 5
- name: Check Prometheus targets status
uri:
url: "http://localhost:{{ prometheus_port }}/api/v1/targets"
register: targets_response
- name: Display Prometheus status
debug:
msg:
- "Prometheus version: {{ prometheus_version }}"
- "Prometheus URL: http://{{ ansible_host }}:{{ prometheus_port }}"
- "Active targets: {{ targets_response.json.data.activeTargets | length }}"

View File

@ -0,0 +1,29 @@
[Unit]
Description=Prometheus Monitoring System
Documentation=https://prometheus.io/docs/
Wants=network-online.target
After=network-online.target
[Service]
User={{ prometheus_user }}
Group={{ prometheus_group }}
Type=simple
ExecStart={{ prometheus_binary_dir }}/prometheus \
--config.file={{ prometheus_config_dir }}/prometheus.yml \
--storage.tsdb.path={{ prometheus_data_dir }} \
--storage.tsdb.retention.time={{ prometheus_retention }} \
--web.console.templates={{ prometheus_config_dir }}/consoles \
--web.console.libraries={{ prometheus_config_dir }}/console_libraries \
--web.enable-lifecycle \
--web.enable-admin-api \
--log.level={{ prometheus_log_level }}
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StandardOutput=journal
StandardError=journal
SyslogIdentifier=prometheus
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,80 @@
# Ansible managed - do not edit manually
global:
scrape_interval: 15s
evaluation_interval: 15s
external_labels:
monitor: 'pve-monitoring'
environment: 'production'
prometheus_replica: '{{ ansible_hostname }}'
# Alertmanager configuration (optional)
alerting:
alertmanagers:
- static_configs:
- targets: []
# Load rules once and periodically evaluate them
rule_files:
- "{{ prometheus_config_dir }}/rules/*.yml"
# Remote write to VictoriaMetrics
remote_write:
- url: "{{ victoriametrics_url }}"
queue_config:
max_samples_per_send: 10000
capacity: 20000
max_shards: 30
metadata_config:
send: true
send_interval: 1m
# Scrape configurations
scrape_configs:
# Prometheus self-monitoring
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:{{ prometheus_port }}']
labels:
instance: 'prometheus'
container: 'pvestandt6'
# VictoriaMetrics monitoring
- job_name: 'victoriametrics'
static_configs:
- targets: ['{{ victoriametrics_host }}:{{ victoriametrics_port }}']
labels:
instance: 'victoriametrics'
container: 'pvestandt5'
# Vault metrics
- job_name: 'vault'
metrics_path: '/v1/sys/metrics'
params:
format: ['prometheus']
bearer_token: '{{ vault_token }}'
static_configs:
- targets: ['{{ vault_host }}:{{ vault_port }}']
labels:
instance: 'vault'
container: 'pvestandt4'
# Git/Forgejo metrics
- job_name: 'gitea'
metrics_path: '/metrics'
static_configs:
- targets: ['{{ git_host }}:{{ git_port }}']
labels:
instance: 'git'
container: 'pvestandt1'
# Node exporters - будем добавлять динамически
- job_name: 'node'
static_configs:
{% if node_exporter_targets | length > 0 %}
- targets:
{% for target in node_exporter_targets %}
- {{ target }}:9100
{% endfor %}
{% else %}
- targets: [] # Will be populated after installing node_exporter
{% endif %}

View File

@ -0,0 +1,36 @@
---
# Configure Prometheus to monitor Nginx
- name: Create Nginx scrape configuration
copy:
content: |
# Nginx metrics from stub_status
- job_name: 'nginx'
scrape_interval: 15s
scrape_timeout: 10s
metrics_path: /status
static_configs:
- targets: ['192.168.0.110:80']
labels:
instance: 'app1-nginx'
service: 'web-server'
environment: 'test'
metric_relabel_configs:
- source_labels: [__address__]
target_label: instance
- source_labels: [__address__]
regex: '([^:]+)(?::\d+)?'
replacement: '${1}'
target_label: hostname
dest: /etc/prometheus/nginx.yml
owner: root
group: root
mode: '0644'
notify: reload prometheus
- name: Include Nginx config in main prometheus.yml
lineinfile:
path: /etc/prometheus/prometheus.yml
line: ' - "nginx.yml"'
insertafter: 'rule_files:'
state: present
notify: reload prometheus