indhuja senthil
indhuja senthil

Reputation: 23

How to match inventory list elements with vars yml list in ansible

I have a list in inventory file [email protected] list_1=['abc','def','xyz'] I have list in vars yml file

list_2:

abc:
  - name: abc
  - alias: a
def:
  - name: def
  - alias: b
xyz:
  - name: xyz
  - alias: b 

I want to match the elements of list_1 with teh attributes of vars yml of list_1. Say, when 'abc' is picked as first element from list_1, 'abc' should get matched with list_2 and it should fetch name and alias from list_2 of it. similar way this should be achieved for the entire list_1. How to do this in ansible? Anyidea or suggestion?

Upvotes: 1

Views: 142

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68024

Q: "Element from list_1 ... matched with list_2 ... fetch name and alias ...for the entire list_1"

A: list_2 is the wrong structure for this use-case. Instead, put the values into the dictionaries, e.g.

    dict_2:
      abc:
        name: abc
        alias: a
      def:
        name: def
        alias: b
      xyz:
        name: xyz
        alias: b

Then, the task below does the job, e.g.

    - debug:
        msg: "element: {{ item }}
              name: {{ dict_2[item]['name'] }}
              alias: {{ dict_2[item]['alias']  }}"
      loop: "{{ list_1 }}"

gives

  msg: 'element: abc name: abc alias: a'
  msg: 'element: def name: def alias: b'
  msg: 'element: xyz name: xyz alias: b'

If you can't change the structure of the data convert it first, e.g.

    - set_fact:
        dict_2: "{{ dict_2|default({})|
                    combine({item.0.key: item.1}, recursive=True) }}"
      with_subelements:
        - "{{ list_2|dict2items }}"
        - value

Upvotes: 1

Related Questions