Extract server IP from the group in the inventory file

82 Views Asked by At

I have the following inventory file:

[group_01]
g01_h01         ansible_ssh_host='10.1.0.1'
g01_h01         ansible_ssh_host='10.1.0.2'

[group_02]
g02_h01         ansible_ssh_host='10.2.0.1'
g02_h01         ansible_ssh_host='10.2.0.2'

[group_03:children]
group_01
group_02

[group_03:vars]
fst_group2={{groups['group_02'][0]}}
snd_group1={{groups['group_01'][1]}}

I would like that in my playbook variables had the following values:

fst_group2=10.2.0.1
snd_group1=10.1.0.2

Instead I get:

fst_group2=g02_h01
snd_group1=g01_h02

Any ideas, a workaround?

1

There are 1 best solutions below

0
Konstantin Suvorov On BEST ANSWER

Very strange task indeed... Anyway,

groups variable – is a list of hosts, which are g01_h01, g01_h02, etc.
To achieve what you expect, you may use this:

[group_03:vars]
fst_group2={{hostvars[groups['group_02'][0]]['ansible_ssh_host']}}
snd_group1={{hostvars[groups['group_01'][1]]['ansible_ssh_host']}}

And keep in mind that ansible_ssh_host is deprecated in favor of ansible_host.