如何在jinja2 ansible中将嵌套字典保存为变量?

如何在jinja2 ansible中将嵌套字典保存为变量?,ansible,yaml,jinja2,Ansible,Yaml,Jinja2,我正在尝试为我们的ansible角色创建一个prometheus.yml.j2模板。这是变量: SCRAPE_CONFIGS: - job_name: 'prometheus' static_configs: - targets: ['localhost:9090'] - job_name: 'postgresql' static_configs: - targets: ['postgresql-exporter:9187'] 我试过: scr

我正在尝试为我们的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_配置,其中包含更多条目,如:

- job_name: 'elasticsearch'
  scrape_intervall: 10s
  scrape_timeout: 5s
  static_configs:
    - targets: ['elasticsearch-exporter:9114']
为什么不使用一个来重新创建您请求的词汇结构,然后使用过滤器将整个内容作为YAML转储

根据剧本:

-主机:所有
收集事实:不
任务:
-设定事实:
配置:
scrape_config:“{{scrape_CONFIGS}”
变量:
刮取_配置:
-工作名称:“普罗米修斯”
静态\u配置:
-目标:['localhost:9090']
-作业名称:“postgresql”
静态\u配置:
-目标:['postgresql-exporter:9187']
-副本:
内容:“{config}to_yaml}”
目的地:普罗米修斯.yml.j2
这将创建一个包含以下内容的文件prometheus.yml.j2:

scrape\u配置:
-工作名称:普罗米修斯
静态\u配置:
-目标:['localhost:9090']
-作业名称:postgresql
静态\u配置:
-目标:['postgresql-exporter:9187']

为了增加一个额外的元素,剧本

-主机:所有
收集事实:不
任务:
-设定事实:
配置:
scrape_-config:“{{scrape_-CONFIGS+元素\u-to\u-add}”
变量:
刮取_配置:
-工作名称:“普罗米修斯”
静态\u配置:
-目标:['localhost:9090']
-作业名称:“postgresql”
静态\u配置:
-目标:['postgresql-exporter:9187']
元素添加到:
-作业名称:“elasticsearch”
刮伤间隔:10秒
刮擦超时:5s
静态\u配置:
-目标:['elasticsearch-exporter:9114']
-副本:
内容:“{config}to_yaml}”
目的地:普罗米修斯.yml.j2
将创建一个包含以下内容的文件prometheus.yml.j2:

scrape\u配置:
-工作名称:普罗米修斯
静态\u配置:
-目标:['localhost:9090']
-作业名称:postgresql
静态\u配置:
-目标:['postgresql-exporter:9187']
-职位名称:elasticsearch
刮伤间隔:10秒
刮擦超时:5s
静态\u配置:
-目标:['elasticsearch-exporter:9114']
谢谢你的回答:)我没有使用“set_fact”,而是你建议的过滤器“to_yaml”{{SCRAPE_CONFIGS | to_yaml}为我做的:)