Score:1

Ansible : host variable reference confusion

us flag

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.

Score:2
br flag

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.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.