Last active
August 29, 2015 14:13
-
-
Save aabouzaid/758ba28e4e4f6f753750 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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) + '}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output example: