Alex alex
Alex alex

Reputation: 116

Ansible template from jinja2

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

Upvotes: 0

Views: 535

Answers (1)

Alex alex
Alex alex

Reputation: 116

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

Upvotes: 0

Related Questions