HiveBrain v1.2.0
Get Started
← Back to all entries
snippetMinor

How can I determine an Ansible client's IP address in an OS-independent manner?

Submitted by: @import:stackexchange-devops··
0
Viewed 0 times
canaddressindependentmannerclientdeterminehowansible

Problem

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

Solution

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') }}"


gives
ok: [localhost] =>
msg: 10.1.0.71


If the play is running at the client delegate to localhost, e.g.
- debug:
msg: "{{ lookup('community.general.dig', inventory_hostname) }}"
delegate_to: localhost


gives
ok: [test_21 -> localhost] =>
msg: 10.1.0.71

Context

StackExchange DevOps Q#15084, answer score: 5

Revisions (0)

No revisions yet.