#! /usr/bin/env python
import xml.etree.cElementTree as ET
import argparse
import sys
try:
import json
except ImportError:
import simplejson as json
tree = ET.ElementTree(file='resources.xml')
root = tree.getroot()
resources_tags = []
def assign_to_list(x):
group_name = str(x)
group_attributes = {
'hosts': [],
'vars': {
'ansible_ssh_user': 'rdansible'
}
}
return {group_name: group_attributes}
for child_of_root in root:
if not child_of_root.attrib['tags']:
pass
else:
tag_list = child_of_root.attrib['tags'].split(',')
for tags in tag_list:
resources_tags.append(tags)
GroupNames_lists = set(resources_tags)
GroupMetaData = [assign_to_list(groups) for groups in GroupNames_lists]
ANSIBLE_INV = {}
for groupData in GroupMetaData:
ANSIBLE_INV.update(groupData)
for child_of_root in root:
if not child_of_root.attrib['tags']:
pass
else:
tag_list = child_of_root.attrib['tags'].split(',')
for tag in tag_list:
if tag in child_of_root.attrib['tags']:
ANSIBLE_INV[tag]['hosts'].append(child_of_root.attrib['hostname'])
def get_group_info():
# Output the --list data structure as JSON
print json.dumps(ANSIBLE_INV, indent=4)
def get_host_info(host):
# Find the given variables for the given host and output them as JSON
host_ip_address_list = []
for child_of_root in root:
if not child_of_root.attrib['hostname']:
pass
else:
host_ip_address = child_of_root.attrib['hostname']
host_ip_address_list.append(host_ip_address)
unique_host_list = set(host_ip_address_list)
HOST_VARS = {}
if host in unique_host_list:
host_var = {
'ansible_ssh_user': 'rdansible'
}
print json.dumps(host_var, indent=4)
else:
sys.exit(1)
if __name__ == '__main__':
# Argument parsing
parser = argparse.ArgumentParser(description="Ansible dynamic inventory")
parser.add_argument("--list", help="Ansible inventory of all of the groups",
action="store_true", dest="list_inventory")
parser.add_argument("--host", help="Ansible inventory of a particular host", action="store",
dest="ansible_host", type=str)
cli_args = parser.parse_args()
list_inventory = cli_args.list_inventory
ansible_host = cli_args.ansible_host
if len(sys.argv) == 2 and (sys.argv[1] == '--list'):
get_group_info()
elif len(sys.argv) == 3 and (sys.argv[1] == '--host'):
get_host_info(ansible_host)
else:
print "Usage: %s --list or --host <hostname>" % sys.argv[0]
sys.exit(1)