来自 jinja2 的 Ansible 模板 [英] Ansible template from jinja2

查看:30
本文介绍了来自 jinja2 的 Ansible 模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉你如何实现输入名为region1a的模板时输出name1组中所有region的实现,输入名为region2b的模板时,输出name2组中的所有region

Who can tell you how to implement the output of all regions in the name1 group when entering a template named region1a, and when entering a template named region2b, output all regions from the name2 group

我是这样实现的:有一个启动模板生成的任务:

I implement it like this: there is a task that starts template generation:

      vars:
        AllCountry:
          - name1
          - name2
        name1:
          - region1a
          - region1b 
        name2:
          - region2a
          - region2b
  tasks:
  - name:
    template:
      src: "regions.j2"
      dest: "{{ item }}.conf"
    loop:
      - region1a
      - region2b

---regions.j2---

regions [{%for count in name1%} "my country = {{count}}", {%end for %}]

这给出了所需的输出,但只是因为它明确指定了要输出的名称(1 或 2)

this gives the desired output, but only because it is explicitly specified for which name (1 or 2) to output

regions "my country = region1a", "my country = region1b"

对于循环中指定的每个值,必须生成模板配置文件.当您在循环中指定值时 region1a 和 region1b 模板应该只在 region1a.conf 的配置文件中生成一行

For each value specified in the loop, a template configuration file must be generated. When you specify values in loop region1a and region1b template should generate only one row in the configuration file for region1a.conf

regions "my country = region1a", "my country = region1b"

为 region1b 在 region1b.conf 的配置文件中只生成一行

for region1b generate only one row in the configuration file for region1b.conf

regions "my country = region1a", "my country = region1b"

用户 β.εηοιτ.βε 提出了更优化的结构.方便的话可以使用.

User β.εηοιτ.βε a more optimal structure was proposed. If convenient, you can use it.

vars:
countries:
  country1:
    regions:
      - region1
      - region2
      - region3
    capital: region1
  country2:
    regions:
      - region4
      - region5
    capital: region5

推荐答案

感谢大家的帮助.尽管如此,我还是设法自己弄明白了.这是最终的解决方案:

Thank you all for your help. Still, I managed to figure it out myself. Here is the final solution:

{% for country in AllCountry %}
{% if item in lookup('vars', country) %}{% for count in lookup('vars', country) %} "My country = {{ count }}"{% if not loop.last %},{% endif %}{% endfor %}{% endif %}{% endfor %}

这篇关于来自 jinja2 的 Ansible 模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆