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

北慕城南 提交于 2021-01-27 22:03:32

问题


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"

回答1:


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 playbook:

- hosts: all
  gather_facts: no
      
  tasks:
    - 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 the recap:

PLAY [all] *******************************************************************************************************

TASK [debug] *****************************************************************************************************
ok: [localhost] => {
    "msg": "    {name: \"name1\",My country = region1a My country = region1b     {name: \"name2\",My country = region2a My country = region2b \n"
}

PLAY RECAP *******************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Note that lookup('vars', country) could also be shortened into vars[country]



来源:https://stackoverflow.com/questions/64977059/ansibleerror-template-error-while-templating-string-expected-token-got

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