3
votes

I am trying to get a list of the IP's of all the hosts in my inventory file from a playbook that only runs in a single group.

Assume the following inventory file:

[dbservers]
db1.example.com
db2.example.com

[webservers]
www1.example.com
www2.example.com

And the playbook:

---

- hosts: dbservers
  roles:
  - dosomething

And the dosomething role:

- name: print all host ips
  template: src=hosts.j2 dest=/tmp/hosts.txt

And the hosts.j2 template:

{% for host in hostvars %}

{{ hostvars[host].ansible_eth0.ipv4.address }}

{% endfor %}

Problem:

When running this, I only ever get the dbserver ip's listed, not all ip's

Question:

How can I gain access to the entire inventory from within this playbook? Changing the hosts to all in the playbook works, but then the dosomething playbook also runs on all hosts, which is not what I want. I only want the list on the dbservers.

2

2 Answers

2
votes

In order to gain access to all the hosts in hostvars, you first have to create a task for all hosts. I created a simple role that would simple echo something on all hosts. This role then forces gather facts on all hosts and add each to the hostvars group.

Please note that if you then run the playbook with a tag limit, the hostvars group is again effected.

I got the tip here: https://groups.google.com/forum/#!msg/Ansible-project/f90Y4T4SJfQ/L1YomumcPEQJ

1
votes

The special variable groups is probably what you want to do this, in your case the value of groups will be:

"groups" : {
    "dbservers": [
        "db1.example.com",
        "db2.example.com"
    ],
    "webservers": [
        "www1.example.com",
        "www2.example.com"
    ]
}

which you can loop over in your jinja template.