You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Jinja2和Ansible遍历多文本文件生成Prometheus配置

解决方案

步骤1:拉取远程主机的网站列表文件到控制节点

先通过Ansible的fetch模块把所有服务器的网站列表文件拉到控制节点,方便后续统一处理:

- name: Fetch website list files from production hosts
  hosts: production
  tasks:
    - name: Pull websites.txt files to control node
      ansible.builtin.fetch:
        src: /path/to/{{ inventory_hostname }}_websites.txt
        dest: ./fetch_files/
        flat: yes

步骤2:编写Jinja2配置模板

创建Blackbox Exporter的配置模板(示例命名为blackbox_config.j2),通过遍历文件提取主机名和URL:

modules:
  http_2xx:
    prober: http
    http:
      valid_http_versions: ["HTTP/1.1", "HTTP/2.0"]
      method: GET

targets:
{% for file in lookup('fileglob', './fetch_files/*_websites.txt', wantlist=True) %}
{% set hostname = file | regex_replace('.*/(.*)_websites.txt', '\1') %}
  - targets:
{% for url in lookup('file', file).splitlines() if url.strip() %}
      - "{{ url.strip() }}"
{% endfor %}
    labels:
      instance: "{{ hostname }}"
      job: "website_monitoring"
{% endfor %}

步骤3:生成最终的Blackbox配置文件

在Ansible playbook中添加任务,使用模板生成最终配置:

- name: Generate Blackbox Exporter configuration
  hosts: localhost
  tasks:
    - name: Render blackbox config from template
      ansible.builtin.template:
        src: ./blackbox_config.j2
        dest: ./blackbox.yml
        mode: '0644'

关键注意事项

  • 用fileglob lookup遍历所有拉取到的文件,确保覆盖全部主机的网站列表
  • 通过regex_replace从文件名中提取主机名,若fetch的文件路径有层级,需调整正则匹配规则
  • 遍历URL时加入if url.strip()过滤空行,避免生成无效的target配置
  • 若有自定义Blackbox探测模块需求,直接修改模板中的modules部分即可

内容的提问来源于stack exchange,提问作者Louis Gromb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 00:25:21