Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aabouzaid/758ba28e4e4f6f753750 to your computer and use it in GitHub Desktop.
Save aabouzaid/758ba28e4e4f6f753750 to your computer and use it in GitHub Desktop.
#! /bin/python
#Ansible module with Python to list groups in inventory (version 0.2 :D)
#You can print output like "pretty-print" outside Ansible by using:
#./listgroups | python -m json.too
import os
import re
import json
#Get hosts inventory from ansible.cfg file.
ansible_conf_file = open("ansible.cfg").read()
hosts_file = re.findall('^hostfile\s*=\s*(.*)', ansible_conf_file, re.MULTILINE)[0]
#Get data from hostsfile.
hosts_file = open(hosts_file)
groups_and_members = hosts_file.read().splitlines()
hosts_file.close()
#Preste for counting loop.
first_element = 0
number_of_group_members = 0
gropus_list= {}
#Get groups and number of its members from inventory file and add it to dictionary.
for line in groups_and_members:
if re.match("^\[", line) and first_element == 0:
group_name = re.sub(r'[\[\]]', '', line)
first_element=1
elif not re.match("(^\[|#|^$)", line) and first_element != 0:
number_of_group_members += 1
elif re.match("^\[", line) and first_element != 0:
gropus_list[group_name] = number_of_group_members
group_name = re.sub(r'[\[\]]', '', line)
number_of_group_members = 0
#Print output in json format.
print '{"Inventory Groups": ' + json.dumps(gropus_list) + '}'
@aabouzaid
Copy link
Author

Output example:

  • Raw:
{"Inventory Groups": {"Group1": 5, "Group2": 3, "Group3": 7}}
  • With python -m json.tool:
{
    "Inventory Groups": {
        "Group1": 5,
        "Group2": 3,
        "Group3": 7,
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment