Ansible 不直接采集应用健康指标,而是通过自动化部署 OpenTelemetry Collector、各类 Exporter 和自定义脚本,统一配置 Prometheus 抓取目标,并支持健康接口验证与轻量巡检。

Ansible 本身不直接采集应用健康指标,它不替代监控系统(如 Prometheus、OpenTelemetry 或 Zabbix),而是通过编排、部署和调用指标采集组件来实现健康数据的统一收集。核心思路是:用 Ansible 自动化部署和配置采集器(如 OpenTelemetry Collector、Prometheus Exporter、自定义脚本等),再由这些采集器将指标推送给后端监控平台。
部署 OpenTelemetry Collector 作为统一采集入口
OpenTelemetry Collector 是当前主流的可观测性数据接收、处理与转发组件,支持从多种来源(进程指标、HTTP 端点、JVM、.NET、日志流等)拉取或接收健康指标。
- 使用 grafana.grafana.opentelemetry_collector Ansible 角色(需先安装:
ansible-galaxy collection install grafana.grafana) - 在 Playbook 中配置 receivers(如
prometheus、hostmetrics、httpcheck)和 exporters(如prometheusremotewrite推送至 Prometheus,或otlp发往 Grafana Tempo/Logs) - 示例片段(采集本机应用 HTTP 健康端点):
otel_collector_receivers: httpcheck: - endpoint: "http://localhost:8080/actuator/health" method: GET timeout: 10s interval: 30s
批量部署应用专属 Exporter
对 Java、Node.js、Python 等常见运行时,可借助 Ansible 快速部署对应 Exporter:
Linux 安全审计工具,检查 SSH 配置、开放/监听端口、防火墙规则(ufw/iptables/nftables)、失败登录尝试、sudoers 权限...
-
Java 应用:用 Ansible 下载并启动
prometheus-jmx-exporter,挂载 JMX 配置文件,监听应用 JMX 端口 -
Spring Boot:确保
spring-boot-actuator已启用,Ansible 可自动配置 Nginx 反向代理或防火墙放行/actuator/metrics、/actuator/health等端点供 Prometheus 抓取 -
自定义脚本:用
copy模块分发 shell/Python 脚本(如检查数据库连接、响应延迟、队列积压),再用systemd模块注册为定时服务,输出格式兼容 Prometheus 文本协议(text/plain; version=0.0.4)
集中配置 Prometheus 抓取目标
若采用 Pull 模式(Prometheus 主动抓取),Ansible 可统一维护 prometheus.yml 的 scrape_configs:
- 动态生成 targets 列表:基于 inventory 分组(如
[app_servers])生成 IP+端口列表 - 用
template模块渲染配置文件,注入变量(如{{ ansible_host }}:8080/metrics) - 配合
systemd模块重载 Prometheus 服务:systemctl reload prometheus
验证与轻量级巡检集成
Ansible 还可承担“健康快照”职责,不依赖长期采集器:
- 用
uri模块请求应用健康接口(如GET /health),校验 HTTP 状态码和 JSON 响应字段(status: UP) - 用
shell+json_query提取关键指标(如 JVM 内存使用率),结合assert模块做阈值断言 - 将结果写入日志或发送到 Slack/Email(通过
community.general.slack等模块)

















