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 here>>>.
Code:
- name: Test hosts list debug: msg: "{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address'] }}"
Run it:
[simterm]
... 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" } ...
[/simterm]
Example 2 – lookup
and dig
Another approach could be using the lookup
and its plugin dig
.
See the documentation here>>>.
Code:
... - name: Test hosts list debug: msg: "{{ lookup('dig', ansible_host) }}" ...
Run it:
[simterm]
... 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" } ...
[/simterm]
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.