Created
February 5, 2020 22:40
-
-
Save rpetti/fb538b1e72c73f25350b944be18d4b0e to your computer and use it in GitHub Desktop.
Export Ansible AWX/Tower Inventory to a standard Inventory
This file contains hidden or 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/python | |
import requests | |
import argparse | |
import sys | |
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() | |
r = requests.get('{}/api/v2/inventories/'.format(args.url), 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() | |
for key in sorted(hosts): | |
if key == 'all': | |
continue | |
if key == '_meta': | |
continue | |
if 'hosts' in hosts[key]: | |
print('[{}]'.format(key)) | |
for host in hosts[key]['hosts']: | |
print 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 '' |
Thanks for the code. Very helpful.
host variables are here hosts["_meta"]["hostvars"]
Thank you this was very helpful.
I have updated your script to use python3 and added the following functionality:
- query more than one inventory page for inventory id
- extract host variables and add to ini file
- list that holds host variable terms that should be excluded for ini file generation
source: https://gist.github.com/afreller-1wa/69452a5c4677ff54c19084bd12e635b4
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure. Check the contents of 'hosts' and see if it has the information you need, then add to the print statements accordingly. If the host-level variables aren't there, then you will likely need to check the AWX API to see if there's another request you can use to get the variables for each host.