Ansible template from jinja2

这一生的挚爱 提交于 2020-11-29 19:14:41

问题


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 %}]

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"

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"

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

回答1:


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 %}


来源:https://stackoverflow.com/questions/65000766/ansible-template-from-jinja2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!