AnsibleUndefinedVariable: No variable found with this name: region1a"}

705 Views Asked by At

I want to get the output of information after comparing whether the region is the capital? Help me figure out how to use "lookup" correctly?

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

or

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

I get the following error

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

here {{ item }} is a variable = region1a

I have these variables

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

what am I wrong about?

1

There are 1 best solutions below

3
On BEST ANSWER

It seems to me like this is what you are looking to achieve:

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

But that is really not foolproof. Imagine you have two regions named the same in two countries and one is the capital of one of the countries when the other is not the capital of the other one, how would you do it here?

I would really go with a more tied kind of dictionary like:

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

But without your actual use case and what you are trying to build with all this, this is hard to advise on the right type of data structure to construct.