How to get host private network address in Ansible

I've tried something like this:

gather_facts: yes
  tasks:
    - debug: var=ansible_all_ipv4_addresses
    - set_fact:
        man_ip: "{{ item }}"
      with_items: ansible_all_ipv4_addresses
      when: "item.startswith('10.')"
    - debug: var=man_ip

It works, but I have problem with servers where I use docker, 'cause docker containers also have interface adress started with 10.x.x.x.

So, how can I get host private network address?

Upvotes: 5

Views: 12109

Answers (4)

Maxim Suslov
Maxim Suslov

Reputation: 5505

Old solution

ipaddr is deprecated now:

- debug: var="{{ ansible_all_ipv4_addresses | ipaddr('private') | first }}"

will lead to:

[DEPRECATION WARNING]: Use 'ansible.utils.ipaddr' module instead. This feature
will be removed from ansible.netcommon in a release after 2024-01-01.

New Solution

You need to install:

sudo pip install netaddr    # system wide
pip install --user netaddr  # or for current user

Then next snippet will work:

- debug: var="{{ ansible_all_ipv4_addresses | ansible.utils.ipaddr('private') | first }}"

See documentation for more filtering examples.

Upvotes: 2

Roman Rhrn Nesterov
Roman Rhrn Nesterov

Reputation: 3673

- debug: var=hostvars[inventory_hostname].private_ipv4

Upvotes: -1

TomDotTom
TomDotTom

Reputation: 6754

You could use ansible_all_ip_addresses fact and the ipaddr filter.

{{ ansible_all_ipv4_addresses | ipaddr('private') | first }}

Note: You can check what ansible facts you have available with ansible -m setup localhost

Edit: You can also filter by ip using ipaddr

{{ ansible_all_ipv4_addresses | ipaddr('10.0.0.0/8') | first }}

Upvotes: 12

helloV
helloV

Reputation: 52443

How about:

- debug: var="ansible_eth0['ipv4']['address']"

or

- debug: var=ansible_eth0.ipv4.address

Upvotes: 3

Related Questions