Use a variable from another host's variables

19 views
Skip to first unread message

adsqu...@gmail.com

unread,
Feb 23, 2019, 12:53:20 PM2/23/19
to Ansible Project
Hello all,

I have an inventory file populated with two hosts and I would like to use the value of host B's variable on host A. I had no luck with using hostvars in the template.

Example inventory file. Note this will be a dynamically generated file. 

[host_a]
x.x.x.x
[host_a:vars]
eth0=192.168.1.1
eth1=192.168.2.1


[host_b]
x.x.x.x
[host_b:vars]
eth0=192.168.1.2
eth1=192.168.2.2

I want to use 192.168.2.1 from host_a's variable in a template that will generate a config file on both host a and b. For example, the config on both hosts will have an entry like this: clustered_ips = 192.168.2.1, 192.168.2.2

I tried this in the template file but get undefined variable.

{{ hostvars[host_a][eth0] }}


How can I accomplish this?

Thanks in advance.

Steven

Kai Stian Olstad

unread,
Feb 23, 2019, 1:04:57 PM2/23/19
to ansible...@googlegroups.com
Without quotes inside [] they are taken as variables, so host_a and eth0 is taken as variables.
So you're looking for this

{{ hostvars['host_a']['eth0'] }}

--
Kai Stian Olstad

adsqu...@gmail.com

unread,
Feb 25, 2019, 8:46:21 AM2/25/19
to Ansible Project
The issue was not so much with the quoting ( I tried that as well before posting ) but the value host_a after hostvars. Ansible was looking for the IP address under the host heading. 
Ex. {{ hostvars['x.x.x.x'][eth0] }}

Is there another way to do this? I would prefer not to put the IP or a DNS name in the template so real values don't get checked into source code.

Thanks,

Kai Stian Olstad

unread,
Feb 25, 2019, 9:02:37 AM2/25/19
to ansible...@googlegroups.com
On 25.02.2019 14:46, adsqu...@gmail.com wrote:
> The issue was not so much with the quoting ( I tried that as well before
> posting ) but the value host_a after hostvars. Ansible was looking for the
> IP address under the host heading.
> Ex. {{ hostvars['x.x.x.x'][eth0] }}

Of course, is't a group name.


> Is there another way to do this? I would prefer not to put the IP or a DNS
> name in the template so real values don't get checked into source code.

If you only have one host in the group this should work.

{{ hostvars[group['host_a'][0]]['eth0'] }}


--
Kai Stian Olstad
Reply all
Reply to author
Forward
0 new messages