-
Notifications
You must be signed in to change notification settings - Fork 7
/
netbox-awx.py
90 lines (75 loc) · 2.72 KB
/
netbox-awx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/usr/bin/env python
import json
import requests
# Netbox URL
URL = ''
# Netbox API Token
TOKEN = ''
# AWX Filter Tags
FILTER_TAGS = []
headers = {
'Accept': 'application/json ; indent=4',
'Authorization': 'Token %s' % (TOKEN),
}
device_url = URL + '/api/dcim/devices/'
devices = []
sites = {}
racks = {}
platforms = {}
tenants = {}
tags = {}
inventory = {}
hostvars = {}
# Get data from netbox
def get_data(api_url):
out = []
while api_url:
api_output = requests.get(api_url, headers=headers, verify=False)
api_output_data = api_output.json()
if isinstance(api_output_data, dict) and "results" in api_output_data:
out += api_output_data["results"]
api_url = api_output_data["next"]
return out
hosts_list = get_data(device_url)
# Filter hosts for AWX
for i in hosts_list:
if FILTER_TAGS:
tag_list = []
if i['tags']:
for tag_item in i['tags']:
tag_list.append(tag_item['name'])
if any(item in FILTER_TAGS for item in tag_list):
if i['status']:
if i['status']['label'] == 'Active':
devices.append(i)
else:
if i['status']:
if i['status']['label'] == 'Active':
devices.append(i)
# Populate inventory
for i in devices:
if i['name']:
if i['config_context']:
hostvars.setdefault('_meta', {'hostvars': {}})['hostvars'][i['name']] = i['config_context']
if i['site']:
sites.setdefault(i['site']['slug'], {'hosts': []})['hosts'].append(i['name'])
hostvars['_meta']['hostvars'][i['name']].setdefault('tags', {})['site'] = i['site']['slug']
if i['rack']:
racks.setdefault(i['rack']['name'], {'hosts': []})['hosts'].append(i['name'])
hostvars['_meta']['hostvars'][i['name']].setdefault('tags', {})['rack'] = i['rack']['name']
if i['platform']:
platforms.setdefault(i['platform']['slug'], {'hosts': []})['hosts'].append(i['name'])
hostvars['_meta']['hostvars'][i['name']].setdefault('tags', {})['platform'] = i['platform']['slug']
if i['tenant']:
tenants.setdefault(i['tenant']['slug'], {'hosts': []})['hosts'].append(i['name'])
hostvars['_meta']['hostvars'][i['name']].setdefault('tags', {})['tenant'] = i['tenant']['slug']
for t in i['tags']:
tags.setdefault(t['name'], {'hosts': []})['hosts'].append(i['name'])
hostvars['_meta']['hostvars'][i['name']].setdefault('tags', {})[t['name']] = True
inventory.update(sites)
inventory.update(racks)
inventory.update(platforms)
inventory.update(tenants)
inventory.update(tags)
inventory.update(hostvars)
print(json.dumps(inventory, indent=4))