首页 > 解决方案 > AnsibleUndefinedVariable:未找到具有此名称的变量:region1a"}

问题描述

我想在比较该地区是否是首都后得到信息的输出?帮我弄清楚如何正确使用“查找”?

{% if capital == lookup('vars', item) %} yes {% else %} no {% endif %}

或者

{% if capital.action == {{ item }} %} yes {% else %} no {% endif %}

我收到以下错误

failed: [localhost] (item=region1a) => {"ansible_loop_var": "item", "changed": false, "item": "region1a", "msg": AnsibleError: template error while templating string: expected token ':', got '}'

这里 {{ item }} 是一个变量 = region1a

我有这些变量

vars:
        AllCountry:
          - name1
          - name2
        name1:
          - region1a
          - region1b 
        name2:
          - region2a
          - region2b
        capital:
          - region1a
          - region2a

我错了什么?

标签: ansiblejinja2ansible-template

解决方案


在我看来,这就是您想要实现的目标:

{% if item in capital %} yes {% else %} no {% endif %}

但这确实不是万无一失的。想象一下,你在两个国家有两个同名的地区,一个是其中一个国家的首都,而另一个不是另一个国家的首都,你会在这里怎么做?

我真的会使用更紧密的字典,例如:

countries:
  country1:
    regions:
      - region1
      - region2
      - region3
    capital: region1
  country2:
    regions:
      - region4
      - region5
    capital: region5

但是,如果没有您的实际用例以及您尝试使用所有这些构建的内容,很难就构建正确类型的数据结构提出建议。


推荐阅读