【问题标题】:AnsibleError: template error while templating string: expected token ':', got '}'AnsibleError:模板化字符串时出现模板错误:预期令牌':',得到'}'
【发布时间】:2021-03-06 16:16:49
【问题描述】:

准备模板时出错。谁能告诉你如何解决?

如有必要,也可以编辑变量。

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

代码

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

结果是一个错误 AnsibleError:模板化字符串时出现模板错误:预期的令牌':',得到'}'

是的,最后我希望得到整个列表的输出

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

【问题讨论】:

    标签: templating ansible-template


    【解决方案1】:

    发生这种情况是因为您在 Jinja 的语句分隔符 {% 中嵌套了表达式分隔符 {{

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

    为了实现您的目标,您可以使用vars 查找。

    鉴于剧本:

    - 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
    

    这产生了回顾:

    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   
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多