Forked from aabouzaid/Ansible module to list groups in inventory (Python version :D)
Last active
December 14, 2016 00:18
This file contains 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 | |
# 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) + '}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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