问题
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