我正试图为我们的ansible角色创建一个prometheus.yml.j2模板。这是一个变量:
SCRAPE_CONFIGS:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'postgresql'
static_configs:
- targets: ['postgresql-exporter:9187']我试过:
scrape_config:
{% for scrape in SCRAPE_CONFIGS -%}
{{ scrape }}
{% endfor %}这是输出:
scrape_config:
{'job_name': 'prometheus', 'static_configs': [{'targets': ['localhost:9090']}]}
{'job_name': 'postgresql', 'static_configs': [{'targets': ['postgresql-exporter:9187']}]}但是它应该看起来像变量本身:
scrape_config:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'postgresql'
static_configs:
- targets: ['postgresql-exporter:9187']否则,prometheus容器将引发语法错误,因为它无法正确读取prometheus.yml配置文件。有没有人有更好的建议来迭代这个嵌套的二叉树呢?结构应保持不变。还应该可以使用更多的条目添加不同的scrape_configs,如:
- job_name: 'elasticsearch'
scrape_intervall: 10s
scrape_timeout: 5s
static_configs:
- targets: ['elasticsearch-exporter:9114']发布于 2021-01-29 20:44:29
为什么不直接使用set_fact来重新创建所请求的字典结构,然后使用过滤器to_yaml将整个过程转储为YAML
考虑到剧本:
- hosts: all
gather_facts: no
tasks:
- set_fact:
config:
scrape_config: "{{ SCRAPE_CONFIGS }}"
vars:
SCRAPE_CONFIGS:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'postgresql'
static_configs:
- targets: ['postgresql-exporter:9187']
- copy:
content: "{{ config | to_yaml }}"
dest: prometheus.yml.j2这将创建一个包含以下内容的文件prometheus.yml.j2:
scrape_config:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
- job_name: postgresql
static_configs:
- targets: ['postgresql-exporter:9187']为了增加一个额外的元素,
- hosts: all
gather_facts: no
tasks:
- set_fact:
config:
scrape_config: "{{ SCRAPE_CONFIGS + elements_to_add }}"
vars:
SCRAPE_CONFIGS:
- job_name: 'prometheus'
static_configs:
- targets: ['localhost:9090']
- job_name: 'postgresql'
static_configs:
- targets: ['postgresql-exporter:9187']
elements_to_add:
- job_name: 'elasticsearch'
scrape_intervall: 10s
scrape_timeout: 5s
static_configs:
- targets: ['elasticsearch-exporter:9114']
- copy:
content: "{{ config | to_yaml }}"
dest: prometheus.yml.j2将创建一个包含以下内容的文件prometheus.yml.j2:
scrape_config:
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
- job_name: postgresql
static_configs:
- targets: ['postgresql-exporter:9187']
- job_name: elasticsearch
scrape_intervall: 10s
scrape_timeout: 5s
static_configs:
- targets: ['elasticsearch-exporter:9114']https://stackoverflow.com/questions/65960671
复制相似问题