-
-
Save MalfuncEddie/dfe3f3ac923325ead0a33eacf8bd5413 to your computer and use it in GitHub Desktop.
Updated python script to export ansible inventory from awx | ansible tower server.
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
#!/usr/bin/python3 | |
import requests | |
import argparse | |
import sys | |
# add terms to this list which will be ignored for ini file generation. | |
# eg. every host var that contains ther term remote_tower will be ignored | |
exclude_host_vars = [ 'remote_tower'] | |
parser = argparse.ArgumentParser(description='Convert Ansible AWX/Tower Inventory to standard inventory') | |
parser.add_argument('--url', required=True, help='base url of AWX/Tower') | |
parser.add_argument('-u', '--username', help='username') | |
parser.add_argument('-p', '--password', help='password') | |
parser.add_argument('inventory', nargs=1, help='inventory name') | |
args = parser.parse_args() | |
iid = -1 | |
#10 inventory pages assumed max | |
# if inventory spans more than one page we nee to loop | |
x = range(1,10,1) | |
for n in x: | |
if iid == -1: | |
#print ('{}/api/v2/inventories/?page={}'.format(args.url,n)) | |
r = requests.get('{}/api/v2/inventories/?page={}'.format(args.url,n), auth=(args.username, args.password)) | |
iid = -1 | |
for inventory in r.json()['results']: | |
if inventory['name'] == args.inventory[0]: | |
iid = inventory['id'] | |
break | |
if iid == -1: | |
print("no such inventory") | |
sys.exit(1) | |
r = requests.get('{}/api/v2/inventories/{}/script/?hostvars=1&towervars=1&all=1'.format(args.url, iid), auth=(args.username, args.password)) | |
hosts = r.json() | |
host_var_dict = {} | |
for key in sorted(hosts): | |
if key == 'all': | |
continue | |
if key == '_meta': | |
for var in hosts[key]['hostvars']: | |
host_vars = hosts[key]['hostvars'][var] | |
host_var_string = '' | |
for host_var_key in host_vars: | |
for exclude_term in exclude_host_vars: | |
if exclude_term in host_var_key: | |
pass | |
else: | |
host_var_string += (' {}={}'.format(host_var_key,host_vars[host_var_key])) | |
# print(host_var_string) | |
host_var_dict[var] = host_var_string | |
if 'hosts' in hosts[key]: | |
print('[{}]'.format(key)) | |
for host in hosts[key]['hosts']: | |
if host in host_var_dict: | |
print ('{}{}'.format(host,host_var_dict[host])) | |
else: | |
print ('{}'.format(host)) | |
print('') | |
if 'children' in hosts[key]: | |
print('[{}:children]'.format(key)) | |
for child in hosts[key]['children']: | |
print(child) | |
print('') | |
if 'vars' in hosts[key]: | |
print('[{}:vars]'.format(key)) | |
for var in hosts[key]['vars']: | |
print('{}={}'.format(var, hosts[key]['vars'][var])) | |
print('') | |
print('') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment