Accessing the entire Ansible Inventory from a group play

I am trying to get a list of the IPs of all the hosts in my inventory file from a playbook that only works in one group.

Suppose the following inventory file is:

[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 doing this, I only ever get the dbserver IP, not all ip

Question:

How can I access all the inventory from this piece? Changing hosts to everything in playbook works, but then dosomething bootbook also works on all hosts, which is not what I want. I only need a list on dbservers.

+3


source to share


2 answers


To access all hosts in hosts, you first need to create a task for all hosts. I created a simple role that would just reflect something across all hosts. This role then combines the facts on all hosts and adds them to the host group.

Note that if you run the player with a tag limit, the host group will be created again.



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

+2


source


A special variable groups

, you probably want to do this, in your case the value groups

will be:

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

      



which you can iterate over in your jinja template.

+1


source







All Articles