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": [

and this is how things look on a Windows client:

ok: [sampleboxwin] => {
"hostvars[inventory_hostname]": {
  // shortened
  "hostname": "sampleboxwin",
        "interfaces": [
                "connection_name": "Ethernet0",
                "default_gateway": "",
                "dns_domain": null,
                "interface_index": 13,
                "interface_name": "Intel(R) 82574L Gigabit Network Connection",
                "macaddress": "0b:fu:sc:at:ed:00"
        "ip_addresses": [

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

1 Answer 1


Q: "IP address Ansible control machine uses to connect to the client machine."

A: Find out to which IP the client resolves, e.g. running at the controller

    - debug:
        msg: "{{ lookup('community.general.dig', 'test_21') }}"


ok: [localhost] => 

If the play is running at the client delegate to localhost, e.g.

    - debug:
        msg: "{{ lookup('community.general.dig', inventory_hostname) }}"
      delegate_to: localhost


ok: [test_21 -> localhost] => 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.