Ansible: get current target host's IP address

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.


You can get the IP address from hostvars, dict ansible_default_ipv4 and key address

hostvars[inventory_hostname]['ansible_default_ipv4']['address']

and IPv6 address respectively

hostvars[inventory_hostname]['ansible_default_ipv6']['address']

An example playbook:

---
- hosts: localhost
  tasks:
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv4']['address']
    - debug: var=hostvars[inventory_hostname]['ansible_default_ipv6']['address']

You can use in your template.j2 {{ ansible_eth0.ipv4.address }} the same way you use {{inventory_hostname}}.

ps: Please refer to the following blogpost to have more information about HOW TO COLLECT INFORMATION ABOUT REMOTE HOSTS WITH ANSIBLE GATHERS FACTS .

'hoping it’ll help someone one day ッ