Last active
August 29, 2015 14:13
-
-
Save aabouzaid/82c6085cccbd1b0deb3c 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 | |
#30 minutes Ansible module to list groups in inventory (Python version) :D | |
#You can print output like "pretty-print" outside Ansible by using: | |
#./listgroups | python -m json.tool | |
import os | |
import re | |
import json | |
#get hosts inventory from ansible.cfg file. | |
def get_hosts_file(ansible_cfg): | |
ansible_conf_file = open(ansible_cfg).readlines() | |
regexp = re.compile('^hostfile') | |
for line in ansible_conf_file: | |
if regexp.search(line): | |
return re.sub(r"(\n|(?<==)\s+)", "", line).split("=")[1] | |
hosts_file = get_hosts_file("ansible.cfg") | |
cat_hosts_file = open(hosts_file).readlines() | |
#Get groups from inventory file and add it to array. | |
def groups_list(): | |
regexp = re.compile('^\[') | |
gropus_array= [] | |
for line in cat_hosts_file: | |
if regexp.search(line) is not None: | |
matched_line = re.sub(r'[\n\[\]]', '', line) | |
gropus_array.append(matched_line) | |
return gropus_array | |
#Print output in json format. | |
print '{"Inventory Groups": ' + json.dumps(groups_list()) + '}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment