Ansible: get current target host's IP address

SJC picture SJC · Oct 2, 2016 · Viewed 256.4k times · Source

How do you get the current host's IP address in a role?

I know you can get the list of groups the host is a member of and the hostname of the host but I am unable to find a solution to getting the IP address.

You can get the hostname by using {{inventory_hostname}} and the group by using {{group_names}}

I have tried things like {{ hostvars[{{ inventory_hostname }}]['ansible_ssh_host'] }} and ip="{{ hostvars.{{ inventory_hostname }}.ansible_ssh_host }}"

Answer

techraf picture techraf · Oct 3, 2016

A list of all addresses is stored in a fact ansible_all_ipv4_addresses, a default address in ansible_default_ipv4.address.

---
- hosts: localhost
  connection: local
  tasks:
    - debug: var=ansible_all_ipv4_addresses
    - debug: var=ansible_default_ipv4.address

Then there are addresses assigned to each network interface... In such cases you can display all the facts and find the one that has the value you want to use.