Score:1

ansible - get list of all hostnames and corresponding ansible_host values from inventory

us flag

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?

Score:1
br flag

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
us flag
While this is nice, it's not really the format I need.
br flag
Use *dict2items* to create the list. I added an example.
us flag
Great, this works.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.