Ansible – Getting List of Hostnames and Corresponding ansible_host Values

ansible

My inventory looks like this:

db0 ansible_host=10.0.0.1
db1 ansible_host=10.0.0.2
app0 ansible_host=10.0.0.3
app1 ansible_host=10.0.0.4
...

From this, I need to extract a list like this:

- name: db0
  ip: 10.0.0.1
- name: db1
  ip: 10.0.0.2
- name: app0
  ip: 10.0.0.3
- name: app1
  ip: 10.0.0.4

I know I can get all hosts using groups['all'].

I can also get the ansible_host value for each host using hostvars['<hostname>']['ansible_host'].

How do I combine this to create the list I need?

Best Answer

For example

host_ip: "{{ dict(ansible_play_hosts_all|
                  zip(ansible_play_hosts_all|
                      map('extract', hostvars, 'ansible_host'))) }}"

creates the dictionary

  host_ip:
    app0: 10.0.0.3
    app1: 10.0.0.4
    db0: 10.0.0.1
    db1: 10.0.0.2

Then, use dict2items to create the list

host_ip_list: "{{ host_ip|dict2items(key_name='name',
                                     value_name='ip') }}"

gives the expected structure

  host_ip_list:
  - ip: 10.0.0.1
    name: db0
  - ip: 10.0.0.2
    name: db1
  - ip: 10.0.0.3
    name: app0
  - ip: 10.0.0.4
    name: app1