ansibletemplatingansible-template

AnsibleError: template error while templating string: expected token ':', got '}'


An error occurs when preparing the template. Who can tell you how to fix it?

Variables, if necessary, can also be edited.

  vars:
    AllСountry:
         - "name1"
         - "name2"
    name1:
         - "region1a"  
         - "region1b"   
    name2:
         - "region2a"
         - "region2b"

Code

{% for country in AllСountry %}   
{name: "{{ country }}",{% for count in {{ country }} %}My country = {{ count }}
{% endfor %}{% endfor %}

the result is an error

AnsibleError: template error while templating string: expected token ':', got '}'

Yes in the end I expect to get the output of the entire list from

name: "name1  My country = "region1a" My country = "region1b"   
name: "name2: My country = "region2a" My country = "region2b"

Solution

  • This happens because you are nesting a expression delimiter {{ in a statement delimiter {% in Jinja here:

    {% for count in {{ country }} %}
    {#              ^--- right there #}
    

    In order to achieve what you are looking to do, you can use the vars lookup.

    Given the task:

    - debug: 
        msg: >
          {% for country in AllCountry %}   
          {name: "{{ country }}",{% for count in lookup('vars', country) %}My country = {{ count }}
          {% endfor %}{% endfor %}
      vars:
        AllCountry:
          - name1
          - name2
        name1:
          - region1a
          - region1b 
        name2:
          - region2a
          - region2b
    

    This yields:

    ok: [localhost] => 
      msg: |2-
         {name: "name1",My country = region1a My country = region1b  {name: "name2",My country = region2a My country = region2b