Ansible – Host Variable Reference Confusion

ansible

I'm new to Ansible, and found it a great tool, but I've stumbled upon a problem that I find very confusing.

In my inventory, there's just:

host1
host2
host3

host1 and host2 both have two network interfaces, one of them connected to host3 that is acting as a router. In my playbook, I wanted a task on host3 that would configure routing and test it via ping. In order to do so, I wanted to:

a) get IP addresses of network interfaces connected to host3 for both host1 and host2. Name of the interface connected to host3 is set via host variable 'routed_if' and it's IP via 'routed_ip4'.

b) Use these variables to set up routing and send few pings from host1 to host2 to verify it works.

I decided to debug these variables doing so:

(...)
- debug:
   var: "{{ hostvars['host1']['routed_ip4'] }}"

What I'm getting is:

ok: [host3] => {
"192.168.1.1/24": "VARIABLE IS NOT DEFINED!"
}

Which is very odd. The IP "192.168.1.1" is the correct value (for host1) set via host variable but it is being presented as though it's a key in dictionary. What I was expecting to get is just '192.168.1.1/24' (literally).

I read chapter of ansible manual for variables, but it didn't really help me that much.

Best Answer

In debug, either you use parameter msg

    msg: "{{ hostvars['host1']['routed_ip4'] }}"

, or parameter var

    var: hostvars['host1']['routed_ip4']

also, the dot notation should work

    var: hostvars.host1.routed_ip4

The syntax of the examples is self-explaining.