Skip to content

Instantly share code, notes, and snippets.

@aweiteka
Last active August 29, 2015 14:11
Show Gist options
  • Save aweiteka/60c1ec5d660bfddaf779 to your computer and use it in GitHub Desktop.
Save aweiteka/60c1ec5d660bfddaf779 to your computer and use it in GitHub Desktop.
Ansible dynamic inventory script for central CI that returns json of provisioned hosts
#!/usr/bin/python
'''
Ansible dynamic inventory script for central CI
returns json of provisioned hosts
'''
import json
import os
RESOURCE_FILE = "resources.json"
JSON_DATA = None
# If RESOURCE_FILE is not found in current working directory
# try CI-specific jenkins path
# assumes filename is RESOURCE_FILE in both cases
if not os.path.isfile(RESOURCE_FILE):
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
RESOURCE_FILE = THIS_DIR + '/../../' + RESOURCE_FILE
if not os.path.isfile(RESOURCE_FILE):
print "Cannot find resource file in current working directory or " \
"'%s'" % (RESOURCE_FILE)
exit(1)
JSON_DATA = json.load(open(RESOURCE_FILE))
HOSTS = {'cihosts': {
'hosts': [],
'vars': {}}}
for host in JSON_DATA['resources']:
if host:
# Openstack resources
if 'ip' in host:
HOSTS['cihosts']['hosts'].append(host['ip'])
HOSTS[host['name']] = {'hosts': [host['ip']],
'vars': {}}
# Beaker resources
if 'system' in host:
HOSTS['cihosts']['hosts'].append(host['system'])
HOSTS[host['system']] = {'hosts': [host['system']],
'vars': {}}
# add metadata
if 'metadata' in host:
for key, val in host['metadata'].iteritems():
if 'ansible-group' in key:
for group in val:
# need to add 'system' support for beaker resources
if group not in HOSTS:
HOSTS[group] = {'hosts': [], 'vars': {}}
HOSTS[group]['hosts'] = [host['ip']]
else:
HOSTS[group]['hosts'].append(host['ip'])
for key, val in host['metadata'].iteritems():
HOSTS[group]['vars'][key] = val
# add all vars to the host
else:
HOSTS[host['name']]['vars'][key] = val
print json.dumps(HOSTS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment