Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mtayseer/b94a5f436a9433a71d55 to your computer and use it in GitHub Desktop.
Save mtayseer/b94a5f436a9433a71d55 to your computer and use it in GitHub Desktop.
#! /bin/python
# 7 minutes Ansible module to list groups in inventory (Python version) :D
# You can print output like "pretty-print" outside Ansible by using:
#./listgroups /path/to/ansible.cfg | python -m json.tool
import sys
import re
import json
#get hosts inventory from ansible.cfg file.
ansible_conf_file = open(sys.argv[1]).read()
hosts_file = re.findall('hostfile\s*=\s*(.*)', ansible_conf_file)[0]
#Get groups from inventory file and add it to array.
cat_hosts_file = open(hosts_file).readlines()
group = 'Default' # for hosts without a group
groups_list = {group: 0}
for line in cat_hosts_file:
# Skip comments & empty lines
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('['): # group
group = re.sub(r'[\[\]]', '', line)
groups_list[group] = 0
else: # host
groups_list[group] += 1
#Print output in json format.
print '{"Inventory Groups": ' + json.dumps(groups_list) + '}'
@aabouzaid
Copy link

When I run the script I get:

python mtayseer_simplified_script.py ansible.cfg
Traceback (most recent call last):
File "mtayseer_simplified_script.py", line 15, in
cat_hosts_file = open(hosts_file).read()
IOError: [Errno 2] No such file or directory: '/etc/ansible/hosts'


ansible.cfg file looks like:

[defaults]

some basic default values...

hostfile

hostfile = /etc/ansible/hosts

hostfile = /tmp/hosts


Python version: 2.7.6
System: Ubuntu 14.04

@mtayseer
Copy link
Author

Updated

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