Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...