Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aabouzaid/82c6085cccbd1b0deb3c to your computer and use it in GitHub Desktop.
Save aabouzaid/82c6085cccbd1b0deb3c to your computer and use it in GitHub Desktop.
#! /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