103 lines
3.1 KiB
YAML
103 lines
3.1 KiB
YAML
---
|
|
- 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 }}"
|