We have answer of your question!

100% solved queries, no empty question

Question: How can I get ansible to group hosts based on ansible facts?


0

Advertisement


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.

Question author Peter-mabbott | Source

Answer


1


Advertisement


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}}"
Answer author Petro026

Advertisement


Tickanswer.com is providing the only single recommended solution of the question How can I get ansible to group hosts based on ansible facts? under the categories i.e ansible , jinja2 , ansible-2.x , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer!