Most people think that ansible_default_ipv4 is some magical way to guess what IP address is the 'main' IP for a server. It is not. It is the IP address which resides on interface where the default route points to.
With hostvars , you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.
Using the Ansible playbook The gather_facts module from the Ansible playbook runs the setup module by default at the start of each playbook to gather the facts about remote hosts. Fetch the Ansible facts and display them using a playbook.
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 ッ
Just use ansible_ssh_host
variable
playbook_example.yml
- hosts: host1
tasks:
- name: Show host's ip
debug:
msg: "{{ ansible_ssh_host }}"
hosts.yml
[hosts]
host1 ansible_host=1.2.3.4
Result
TASK [Show host's ip] *********************************************************************************************************************************************************************************************
ok: [host1] => {
"msg": "1.2.3.4"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With