sushmitha i
sushmitha i

Reputation: 25

How to fetch values from inventory file in ansible?

I'm trying to fetch the values from the inventory host file but unable to get the values. Using ansible 2.5. Thanks in advance. Please help me with the code in jinja2 template form only.

Host file:

[all]
F01 name='["a1","a11"]'  hname='["F01"]'
F02 name='["s01","s11"]' hname='["F02"]'
F03 name='["a02","a12"]' hname='["F03"]'
F04 name='["s02","s12"]' hname='["F04"]'
[nodes]
F01
F02
F03
F04

Code, which I used is given below:

dbs is a list

dbs = ['a1', 's02', 'a11', 's01', 'a02', 's11', 'a12', 's12']
{% for node, sid in groups['nodes']|zip(dbs) %}
{% for j in hostvars[node]['hname'] if hostvars[node]['name'][0] in dbs %}
< name = "{{ sid }}", hname = "{{ j }}" >
{% endfor %}
{% endfor %}

Required Output:

For every name value it should give the respective hname.

Output should be like below.

<name = a1, hname= F01>
<name = s02, hname= F04>
<name = a11, hname= F01>
<name = s01, hname= F02>

Upvotes: 0

Views: 110

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68084

Given the host file the task below

- debug:
    msg: "<name = {{ item.0 }}, hname= {{ item.1 }}>"
  loop: "{{ hostvars|json_query('*.[name[0], hname[0]]') }}"

gives what you want

"msg": "<name = s02, hname= F04>"
"msg": "<name = a1, hname= F01>"
"msg": "<name = a02, hname= F03>"
"msg": "<name = s01, hname= F02>"

The template is, in fact, the same

{% for item in hostvars|json_query('*.[name[0], hname[0]]') %}
<name = {{ item.0 }}, hname= {{ item.1 }}>
{% endfor %}

(not tested)

To take the name value from the dbs list then based on the name value get hname value

The tasks below

- set_fact: # get list of names
    names: "{{ hostvars|json_query('*.name[0]') }}"
- set_fact: # get list of hashes {name,hname}
    hashes: "{{ hostvars|json_query('*.{name: name[0], hname: hname[0]}') }}"
- set_fact: # get list of dict name:hname
    dicts: "{{ dicts|default({})|combine({item: hashes|json_query(query)}) }}"
  vars:
    query: "[?name=='{{ item }}'].hname|[0]"
  loop: "{{ names }}"
- debug: # get hname for given name
    msg: "{{ item }}: {{ dicts[item] }}"
  loop: "{{ names }}"

give

"msg": "s02: F04"
"msg": "a1: F01"
"msg": "a02: F03"
"msg": "s01: F02"

The template is, in fact, the same

{% for item in names %}
<name = {{ item }}, hname= {{ dicts[item] }}>
{% endfor %}

(not tested).

Upvotes: 1

Related Questions