The task is to get a host’s IP during executing an Ansible task.
Below – two examples of how this can be done.
Contents
Example 1 – hostvars
See the documentation
Code:
- name: Test hosts list debug: msg: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
Run it:
...
TASK [test : Test hosts list] ****
ok: [dev.backend-app1-internal.example.com] => {
"msg": "10.0.2.71"
}
ok: [dev.backend-app2-internal.example.com] => {
"msg": "10.0.2.91"
}
ok: [dev.backend-console-internal.example.com] => {
"msg": "10.0.2.104"
}
ok: [dev.backend-bastion.example.com] => {
"msg": "10.0.2.126"
}
...
Example 2 – lookup
and dig
Another approach could be using the lookup
and its plugin dig
.
See the documentation
Code:
... - name: Test hosts list debug: msg: "{{ lookup('dig', ansible_host) }}" ...
Run it:
...
TASK [test : Test hosts list] ****
ok: [dev.backend-app1-internal.example.com] => {
"msg": "10.0.2.71"
}
ok: [dev.backend-app2-internal.example.com] => {
"msg": "10.0.2.91"
}
ok: [dev.backend-bastion.example.com] => {
"msg": "18.***.***.67"
}
ok: [dev.backend-console-internal.example.com] => {
"msg": "10.0.2.104"
}
...
Pay attention that in the first case the dev.backend-bastion.example.com domain was resolved to an EC2 Private IP while in the second example -to the Public IP.
The other domains has only Private IPs.