I have an Ansible environment in which machines are listed by hostname in the inventories. Occasionally, it is necessary to determine the IP address of a target machine in a playbook (note: in this context, I am only interested in the address of the interface that the Ansible control machine uses to connect to the client machine).
It seems that this is not easy to do in an OS-independent way: Linux clients define the dictionary default_ipv4
in their hostvars
, but Windows machines define the array ip_addresses
.
This is how the relevant section of a hostvars
dump from a Linux client looks:
ok: [sampleboxlin] => {
"hostvars[inventory_hostname].ansible_facts": {
"all_ipv4_addresses": [
"123.234.99.99"
],
and this is how things look on a Windows client:
ok: [sampleboxwin] => {
"hostvars[inventory_hostname]": {
// shortened
"hostname": "sampleboxwin",
"interfaces": [
{
"connection_name": "Ethernet0",
"default_gateway": "123.234.99.1",
"dns_domain": null,
"interface_index": 13,
"interface_name": "Intel(R) 82574L Gigabit Network Connection",
"macaddress": "0b:fu:sc:at:ed:00"
}
],
"ip_addresses": [
"123.234.99.9"
],
So, what is the best-practice way of mapping hostnames to the host's IP address [1] in a playbook, in a robust and OS-independent way?
[1] again, we always assume that the client only has one relevant IP address, and we are interested in the one used to communicate with the Ansible controller