简体   繁体   中英

How can I get Ansible to group hosts based on Ansible facts?

I want to generate a report (probably using template) that groups my hosts based on facts about them.

Say I had the following servers in my /etc/ansible/hosts ( ansible_distribution and ansible_distribution_version facts as specified in brackets):

mercer (RedHat, 7.2)
grocer (RedHat, 6.2)
draper (Solaris, 10)
fishmonger (RedHat, 7.2)
goldsmith (Solaris, 11)
skinner (RedHat, 7.2)

What I want to do is end up with a file looking like:

**RedHat 6.2 Servers**
grocer

**RedHat 7.2 Servers**
mercer
fishmonger
skinner

**Solaris 10 Servers**
draper

**Solaris 11 Servers**
goldsmith

I don't know whether it would be better to try:

A) looping through play_hosts and pulling out the facts and writing into a new variable as ('fact1', 'fact2', 'hostname') and then looping over that new variable with groupby within my jinja2 template to generate the report.

B) Sorting them all in an ansible task, and then handing a pre-grouped array of arrays to template, and formatting that.

... and I can't work out how to do either.

I would use a dynamic inventory script or the group_by inventory module to do this. Let's go with the inventory module for now. One issue here is that ansible_distribution_version needs to be normalized to a proper variable. I would accomplish that with a filter. Something like this

- hosts: all
  tasks:
  - group_by:
      key: OSGROUP_{{ ansible_distribution_version | upper | regex_relace('(| |\.', '') }}

The regex probably isn't right but you get the idea. Then later you can reference the group

- hosts: OSGROUP_REDHAT72
  tasks:
  - debug: msg="Do RedHat 7.2 stuff to {{inventory_name}}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM