forked from ServiceNowITOM/ansible-sn-inventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
now.py
executable file
·274 lines (216 loc) · 8.87 KB
/
now.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python
# Copyright 2017 Reuben Stump, Alex Mittell
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
# or implied. See the License for the specific language governing
# permissions and limitations under the License.
'''
ServiceNow Inventory Script
=======================
Retrieve information about machines from a ServiceNow CMDB
This script will attempt to read configuration from an INI file with the same
base filename if present, or `now.ini` if not. It is possible to create
symlinks to the inventory script to support multiple configurations, e.g.:
* `now.py` (this script)
* `now.ini` (default configuration, will be read by `now.py`)
The path to an INI file may also be specified via the `NOW_INI` environment
variable, in which case the filename matching rules above will not apply.
Host and authentication parameters may be specified via the `SN_INSTANCE`,
`SN_USERNAME` and `SN_PASSWORD` environment variables; these options will
take precedence over options present in the INI file. An INI file is not
required if these options are specified using environment variables.
For additional usage details see: https://github.com/ServiceNowITOM/ansible-sn-inventory
'''
import os
import sys
import requests
import base64
import json
import re
import configparser
import time
from cookielib import LWPCookieJar
class NowInventory(object):
def __init__(self, hostname, username, password, fields=None, groups=None):
self.hostname = hostname
# requests session
self.session = requests.Session()
self.auth = requests.auth.HTTPBasicAuth(username, password)
# request headers
self.headers = {
"Accept": "application/json",
"Content-Type": "application/json",
}
# request cookies
self.cookies = LWPCookieJar(os.getenv("HOME") + "/.sn_api_session")
try:
self.cookies.load(ignore_discard=True)
except IOError:
pass
self.session.cookies = self.cookies
if fields is None:
fields = []
if groups is None:
groups = []
# extra fields (table columns)
self.fields = fields
# extra groups (table columns)
self.groups = groups
# initialize inventory
self.inventory = {'_meta': {'hostvars': {}}}
return
def _put_cache(self, name, value):
cache_dir = os.environ.get('SN_CACHE_DIR')
if not cache_dir and config.has_option('defaults', 'cache_dir'):
cache_dir = os.path.expanduser(config.get('defaults', 'cache_dir'))
if cache_dir:
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
cache_file = os.path.join(cache_dir, name)
with open(cache_file, 'w') as cache:
json.dump(value, cache)
def _get_cache(self, name, default=None):
cache_dir = os.environ.get('SN_CACHE_DIR')
if not cache_dir and config.has_option('defaults', 'cache_dir'):
cache_dir = config.get('defaults', 'cache_dir')
if cache_dir:
cache_file = os.path.join(cache_dir, name)
if os.path.exists(cache_file):
cache_max_age = int(os.environ.get('SN_CACHE_MAX_AGE'))
if not cache_max_age:
if config.has_option('defaults', 'cache_max_age'):
cache_max_age = config.getint('defaults',
'cache_max_age')
else:
cache_max_age = 0
cache_stat = os.stat(cache_file)
if (cache_stat.st_mtime + cache_max_age) >= time.time():
with open(cache_file) as cache:
return json.load(cache)
return default
def __del__(self):
self.cookies.save(ignore_discard=True)
def _invoke(self, verb, path, data):
cache_name = '__snow_inventory__'
inventory = self._get_cache(cache_name, None)
if inventory is not None:
return inventory
# build url
url = "https://%s/%s" % (self.hostname, path)
# perform REST operation
response = self.session.get(url, auth=self.auth, headers=self.headers)
if response.status_code != 200:
print >> sys.stderr, "http error (%s): %s" % (response.status_code,
response.text)
self._put_cache(cache_name, response.json())
return response.json()
def add_group(self, target, group):
''' Transform group names:
1. lower()
2. non-alphanumerical characters to '_'
'''
group = group.lower()
group = re.sub('\W', '_', group)
# Ignore empty group names
if group == '':
return
self.inventory.setdefault(group, {'hosts': []})
self.inventory[group]['hosts'].append(target)
return
def add_var(self, target, key, val):
if target not in self.inventory['_meta']['hostvars']:
self.inventory['_meta']['hostvars'][target] = {}
self.inventory['_meta']['hostvars'][target]["sn_" + key] = val
return
def generate(self):
table = 'cmdb_ci_server'
base_fields = [
'name', 'host_name', 'fqdn', 'ip_address', 'sys_class_name'
]
base_groups = ['sys_class_name']
options = "?sysparm_exclude_reference_link=true&sysparm_display_value=true"
columns = list(
set(base_fields + base_groups + self.fields + self.groups))
path = '/api/now/table/' + table + options + \
"&sysparm_fields=" + ','.join(columns)
# Default, mandatory group 'sys_class_name'
groups = list(set(base_groups + self.groups))
content = self._invoke('GET', path, None)
for record in content['result']:
''' Ansible host target selection order:
1. ip_address
2. fqdn
3. host_name
TODO: environment variable configuration flags to modify selection order
'''
target = None
selection = ['host_name', 'fqdn', 'ip_address']
for k in selection:
if record[k] != '':
target = record[k]
# Skip if no target available
if target is None:
continue
# hostvars
for k in record.keys():
self.add_var(target, k, record[k])
# groups
for k in groups:
self.add_group(target, record[k])
return
def json(self):
return json.dumps(self.inventory)
def main(args):
# instance = os.environ['SN_INSTANCE']
# username = os.environ['SN_USERNAME']
# password = os.environ['SN_PASSWORD']
global config
config = configparser.SafeConfigParser()
if os.environ.get('NOW_INI', ''):
config_files = [os.environ['NOW_INI']]
else:
config_files = [
os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'now.ini'
]
for config_file in config_files:
if os.path.exists(config_file):
config.read(config_file)
break
# Read authentication information from environment variables (if set),
# otherwise from INI file.
instance = os.environ.get('SN_INSTANCE')
if not instance and config.has_option('auth', 'instance'):
instance = config.get('auth', 'instance')
username = os.environ.get('SN_USERNAME')
if not username and config.has_option('auth', 'user'):
username = config.get('auth', 'user')
password = os.environ.get('SN_PASSWORD')
if not password and config.has_option('auth', 'password'):
password = config.get('auth', 'password')
# SN_GROUPS
groups = os.environ.get("SN_GROUPS", [])
if not groups and config.has_option('config', 'groups'):
groups = config.get('config', 'groups')
if isinstance(groups, str):
groups = groups.split(',')
# SN_FIELDS
fields = os.environ.get("SN_FIELDS", [])
if not fields and config.has_option('config', 'fields'):
fields = config.get('config', 'fields')
if isinstance(fields, str):
fields = fields.split(',')
inventory = NowInventory(
hostname=instance,
username=username,
password=password,
fields=fields,
groups=groups)
inventory.generate()
print(inventory.json())
if __name__ == "__main__":
main(sys.argv)