Debian Codegraph @

ansible_collections/community/vmware/scripts/inventory/vmware.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 from __future__ import absolute_import, division, print_function
5 __metaclass__ = type
6
7
8 '''
9 VMware Inventory Script
10 =======================
11
12 Retrieve information about virtual machines from a vCenter server or
13 standalone ESX host. When `group_by=false` (in the INI file), host systems
14 are also returned in addition to VMs.
15
16 This script will attempt to read configuration from an INI file with the same
17 base filename if present, or `vmware.ini` if not. It is possible to create
18 symlinks to the inventory script to support multiple configurations, e.g.:
19
20 * `vmware.py` (this script)
21 * `vmware.ini` (default configuration, will be read by `vmware.py`)
22 * `vmware_test.py` (symlink to `vmware.py`)
23 * `vmware_test.ini` (test configuration, will be read by `vmware_test.py`)
24 * `vmware_other.py` (symlink to `vmware.py`, will read `vmware.ini` since no
25 `vmware_other.ini` exists)
26
27 The path to an INI file may also be specified via the `VMWARE_INI` environment
28 variable, in which case the filename matching rules above will not apply.
29
30 Host and authentication parameters may be specified via the `VMWARE_HOST`,
31 `VMWARE_USER` and `VMWARE_PASSWORD` environment variables; these options will
32 take precedence over options present in the INI file. An INI file is not
33 required if these options are specified using environment variables.
34 '''
35
36 import json
37 import logging
38 import optparse
39 import os
40 import ssl
41 import sys
42 import time
43
44 from collections.abc import MutableMapping
45 import configparser
46
47 # Disable logging message trigged by pSphere/suds.
48 try:
49 from logging import NullHandler
50 except ImportError:
51 from logging import Handler
52
53 class NullHandler(Handler):
54 def emit(self, record):
55 pass
56
57 logging.getLogger('psphere').addHandler(NullHandler())
58 logging.getLogger('suds').addHandler(NullHandler())
59
60 from psphere.client import Client
61 from psphere.errors import ObjectNotFoundError
62 from psphere.managedobjects import HostSystem, VirtualMachine, ManagedObject, ClusterComputeResource
63 from suds.sudsobject import Object as SudsObject
64
65
66 class VMwareInventory(object):
67
68 def __init__(self, guests_only=None):
69 self.config = configparser.ConfigParser()
70 if os.environ.get('VMWARE_INI', ''):
71 config_files = [os.environ['VMWARE_INI']]
72 else:
73 config_files = [os.path.abspath(sys.argv[0]).rstrip('.py') + '.ini', 'vmware.ini']
74 for config_file in config_files:
75 if os.path.exists(config_file):
76 self.config.read(config_file)
77 break
78
79 # Retrieve only guest VMs, or include host systems?
80 if guests_only is not None:
81 self.guests_only = guests_only
82 elif self.config.has_option('defaults', 'guests_only'):
83 self.guests_only = self.config.getboolean('defaults', 'guests_only')
84 else:
85 self.guests_only = True
86
87 # Read authentication information from VMware environment variables
88 # (if set), otherwise from INI file.
89 auth_host = os.environ.get('VMWARE_HOST')
90 if not auth_host and self.config.has_option('auth', 'host'):
91 auth_host = self.config.get('auth', 'host')
92 auth_user = os.environ.get('VMWARE_USER')
93 if not auth_user and self.config.has_option('auth', 'user'):
94 auth_user = self.config.get('auth', 'user')
95 auth_password = os.environ.get('VMWARE_PASSWORD')
96 if not auth_password and self.config.has_option('auth', 'password'):
97 auth_password = self.config.get('auth', 'password')
98 sslcheck = os.environ.get('VMWARE_SSLCHECK')
99 if not sslcheck and self.config.has_option('auth', 'sslcheck'):
100 sslcheck = self.config.get('auth', 'sslcheck')
101 if not sslcheck:
102 sslcheck = True
103 else:
104 if sslcheck.lower() in ['no', 'false']:
105 sslcheck = False
106 else:
107 sslcheck = True
108
109 # Limit the clusters being scanned
110 self.filter_clusters = os.environ.get('VMWARE_CLUSTERS')
111 if not self.filter_clusters and self.config.has_option('defaults', 'clusters'):
112 self.filter_clusters = self.config.get('defaults', 'clusters')
113 if self.filter_clusters:
114 self.filter_clusters = [x.strip() for x in self.filter_clusters.split(',') if x.strip()]
115
116 # Override certificate checks
117 if not sslcheck:
118 if hasattr(ssl, '_create_unverified_context'):
119 ssl._create_default_https_context = ssl._create_unverified_context
120
121 # Create the VMware client connection.
122 self.client = Client(auth_host, auth_user, auth_password)
123
124 def _put_cache(self, name, value):
125 '''
126 Saves the value to cache with the name given.
127 '''
128 if self.config.has_option('defaults', 'cache_dir'):
129 cache_dir = os.path.expanduser(self.config.get('defaults', 'cache_dir'))
130 if not os.path.exists(cache_dir):
131 os.makedirs(cache_dir)
132 cache_file = os.path.join(cache_dir, name)
133 with open(cache_file, 'w') as cache:
134 json.dump(value, cache)
135
136 def _get_cache(self, name, default=None):
137 '''
138 Retrieves the value from cache for the given name.
139 '''
140 if self.config.has_option('defaults', 'cache_dir'):
141 cache_dir = self.config.get('defaults', 'cache_dir')
142 cache_file = os.path.join(cache_dir, name)
143 if os.path.exists(cache_file):
144 if self.config.has_option('defaults', 'cache_max_age'):
145 cache_max_age = self.config.getint('defaults', 'cache_max_age')
146 else:
147 cache_max_age = 0
148 cache_stat = os.stat(cache_file)
149 if (cache_stat.st_mtime + cache_max_age) >= time.time():
150 with open(cache_file) as cache:
151 return json.load(cache)
152 return default
153
154 def _flatten_dict(self, d, parent_key='', sep='_'):
155 '''
156 Flatten nested dicts by combining keys with a separator. Lists with
157 only string items are included as is; any other lists are discarded.
158 '''
159 items = []
160 for k, v in d.items():
161 if k.startswith('_'):
162 continue
163 new_key = parent_key + sep + k if parent_key else k
164 if isinstance(v, MutableMapping):
165 items.extend(self._flatten_dict(v, new_key, sep).items())
166 elif isinstance(v, (list, tuple)):
167 if all((isinstance(x, str) for x in v)):
168 items.append((new_key, v))
169 else:
170 items.append((new_key, v))
171 return dict(items)
172
173 def _get_obj_info(self, obj, depth=99, seen=None):
174 '''
175 Recursively build a data structure for the given pSphere object (depth
176 only applies to ManagedObject instances).
177 '''
178 seen = seen or set()
179 if isinstance(obj, ManagedObject):
180 try:
181 obj_unicode = str(getattr(obj, 'name'))
182 except AttributeError:
183 obj_unicode = ()
184 if obj in seen:
185 return obj_unicode
186 seen.add(obj)
187 if depth <= 0:
188 return obj_unicode
189 d = {}
190 for attr in dir(obj):
191 if attr.startswith('_'):
192 continue
193 try:
194 val = getattr(obj, attr)
195 obj_info = self._get_obj_info(val, depth - 1, seen)
196 if obj_info != ():
197 d[attr] = obj_info
198 except Exception as e:
199 pass
200 return d
201 elif isinstance(obj, SudsObject):
202 d = {}
203 for key, val in iter(obj):
204 obj_info = self._get_obj_info(val, depth, seen)
205 if obj_info != ():
206 d[key] = obj_info
207 return d
208 elif isinstance(obj, (list, tuple)):
209 l = []
210 for val in iter(obj):
211 obj_info = self._get_obj_info(val, depth, seen)
212 if obj_info != ():
213 l.append(obj_info)
214 return l
215 elif isinstance(obj, (type(None), bool, float, str, int)):
216 return obj
217 else:
218 return ()
219
220 def _get_host_info(self, host, prefix='vmware'):
221 '''
222 Return a flattened dict with info about the given host system.
223 '''
224 host_info = {
225 'name': host.name,
226 }
227 for attr in ('datastore', 'network', 'vm'):
228 try:
229 value = getattr(host, attr)
230 host_info['%ss' % attr] = self._get_obj_info(value, depth=0)
231 except AttributeError:
232 host_info['%ss' % attr] = []
233 for k, v in self._get_obj_info(host.summary, depth=0).items():
234 if isinstance(v, MutableMapping):
235 for k2, v2 in v.items():
236 host_info[k2] = v2
237 elif k != 'host':
238 host_info[k] = v
239 try:
240 host_info['ipAddress'] = host.config.network.vnic[0].spec.ip.ipAddress
241 except Exception as e:
242 print(e, file=sys.stderr)
243 host_info = self._flatten_dict(host_info, prefix)
244 if ('%s_ipAddress' % prefix) in host_info:
245 host_info['ansible_ssh_host'] = host_info['%s_ipAddress' % prefix]
246 return host_info
247
248 def _get_vm_info(self, vm, prefix='vmware'):
249 '''
250 Return a flattened dict with info about the given virtual machine.
251 '''
252 vm_info = {
253 'name': vm.name,
254 }
255 for attr in ('datastore', 'network'):
256 try:
257 value = getattr(vm, attr)
258 vm_info['%ss' % attr] = self._get_obj_info(value, depth=0)
259 except AttributeError:
260 vm_info['%ss' % attr] = []
261 try:
262 vm_info['resourcePool'] = self._get_obj_info(vm.resourcePool, depth=0)
263 except AttributeError:
264 vm_info['resourcePool'] = ''
265 try:
266 vm_info['guestState'] = vm.guest.guestState
267 except AttributeError:
268 vm_info['guestState'] = ''
269 for k, v in self._get_obj_info(vm.summary, depth=0).items():
270 if isinstance(v, MutableMapping):
271 for k2, v2 in v.items():
272 if k2 == 'host':
273 k2 = 'hostSystem'
274 vm_info[k2] = v2
275 elif k != 'vm':
276 vm_info[k] = v
277 vm_info = self._flatten_dict(vm_info, prefix)
278 if ('%s_ipAddress' % prefix) in vm_info:
279 vm_info['ansible_ssh_host'] = vm_info['%s_ipAddress' % prefix]
280 return vm_info
281
282 def _add_host(self, inv, parent_group, host_name):
283 '''
284 Add the host to the parent group in the given inventory.
285 '''
286 p_group = inv.setdefault(parent_group, [])
287 if isinstance(p_group, dict):
288 group_hosts = p_group.setdefault('hosts', [])
289 else:
290 group_hosts = p_group
291 if host_name not in group_hosts:
292 group_hosts.append(host_name)
293
294 def _add_child(self, inv, parent_group, child_group):
295 '''
296 Add a child group to a parent group in the given inventory.
297 '''
298 if parent_group != 'all':
299 p_group = inv.setdefault(parent_group, {})
300 if not isinstance(p_group, dict):
301 inv[parent_group] = {'hosts': p_group}
302 p_group = inv[parent_group]
303 group_children = p_group.setdefault('children', [])
304 if child_group not in group_children:
305 group_children.append(child_group)
306 inv.setdefault(child_group, [])
307
308 def get_inventory(self, meta_hostvars=True):
309 '''
310 Reads the inventory from cache or VMware API via pSphere.
311 '''
312 # Use different cache names for guests only vs. all hosts.
313 if self.guests_only:
314 cache_name = '__inventory_guests__'
315 else:
316 cache_name = '__inventory_all__'
317
318 inv = self._get_cache(cache_name, None)
319 if inv is not None:
320 return inv
321
322 inv = {'all': {'hosts': []}}
323 if meta_hostvars:
324 inv['_meta'] = {'hostvars': {}}
325
326 default_group = os.path.basename(sys.argv[0]).rstrip('.py')
327
328 if not self.guests_only:
329 if self.config.has_option('defaults', 'hw_group'):
330 hw_group = self.config.get('defaults', 'hw_group')
331 else:
332 hw_group = default_group + '_hw'
333
334 if self.config.has_option('defaults', 'vm_group'):
335 vm_group = self.config.get('defaults', 'vm_group')
336 else:
337 vm_group = default_group + '_vm'
338
339 if self.config.has_option('defaults', 'prefix_filter'):
340 prefix_filter = self.config.get('defaults', 'prefix_filter')
341 else:
342 prefix_filter = None
343
344 if self.filter_clusters:
345 # Loop through clusters and find hosts:
346 hosts = []
347 for cluster in ClusterComputeResource.all(self.client):
348 if cluster.name in self.filter_clusters:
349 for host in cluster.host:
350 hosts.append(host)
351 else:
352 # Get list of all physical hosts
353 hosts = HostSystem.all(self.client)
354
355 # Loop through physical hosts:
356 for host in hosts:
357
358 if not self.guests_only:
359 self._add_host(inv, 'all', host.name)
360 self._add_host(inv, hw_group, host.name)
361 host_info = self._get_host_info(host)
362 if meta_hostvars:
363 inv['_meta']['hostvars'][host.name] = host_info
364 self._put_cache(host.name, host_info)
365
366 # Loop through all VMs on physical host.
367 for vm in host.vm:
368 if prefix_filter:
369 if vm.name.startswith(prefix_filter):
370 continue
371 self._add_host(inv, 'all', vm.name)
372 self._add_host(inv, vm_group, vm.name)
373 vm_info = self._get_vm_info(vm)
374 if meta_hostvars:
375 inv['_meta']['hostvars'][vm.name] = vm_info
376 self._put_cache(vm.name, vm_info)
377
378 # Group by resource pool.
379 vm_resourcePool = vm_info.get('vmware_resourcePool', None)
380 if vm_resourcePool:
381 self._add_child(inv, vm_group, 'resource_pools')
382 self._add_child(inv, 'resource_pools', vm_resourcePool)
383 self._add_host(inv, vm_resourcePool, vm.name)
384
385 # Group by datastore.
386 for vm_datastore in vm_info.get('vmware_datastores', []):
387 self._add_child(inv, vm_group, 'datastores')
388 self._add_child(inv, 'datastores', vm_datastore)
389 self._add_host(inv, vm_datastore, vm.name)
390
391 # Group by network.
392 for vm_network in vm_info.get('vmware_networks', []):
393 self._add_child(inv, vm_group, 'networks')
394 self._add_child(inv, 'networks', vm_network)
395 self._add_host(inv, vm_network, vm.name)
396
397 # Group by guest OS.
398 vm_guestId = vm_info.get('vmware_guestId', None)
399 if vm_guestId:
400 self._add_child(inv, vm_group, 'guests')
401 self._add_child(inv, 'guests', vm_guestId)
402 self._add_host(inv, vm_guestId, vm.name)
403
404 # Group all VM templates.
405 vm_template = vm_info.get('vmware_template', False)
406 if vm_template:
407 self._add_child(inv, vm_group, 'templates')
408 self._add_host(inv, 'templates', vm.name)
409
410 self._put_cache(cache_name, inv)
411 return inv
412
413 def get_host(self, hostname):
414 '''
415 Read info about a specific host or VM from cache or VMware API.
416 '''
417 inv = self._get_cache(hostname, None)
418 if inv is not None:
419 return inv
420
421 if not self.guests_only:
422 try:
423 host = HostSystem.get(self.client, name=hostname)
424 inv = self._get_host_info(host)
425 except ObjectNotFoundError:
426 pass
427
428 if inv is None:
429 try:
430 vm = VirtualMachine.get(self.client, name=hostname)
431 inv = self._get_vm_info(vm)
432 except ObjectNotFoundError:
433 pass
434
435 if inv is not None:
436 self._put_cache(hostname, inv)
437 return inv or {}
438
439
440 def main():
441 parser = optparse.OptionParser()
442 parser.add_option('--list', action='store_true', dest='list',
443 default=False, help='Output inventory groups and hosts')
444 parser.add_option('--host', dest='host', default=None, metavar='HOST',
445 help='Output variables only for the given hostname')
446 # Additional options for use when running the script standalone, but never
447 # used by Ansible.
448 parser.add_option('--pretty', action='store_true', dest='pretty',
449 default=False, help='Output nicely-formatted JSON')
450 parser.add_option('--include-host-systems', action='store_true',
451 dest='include_host_systems', default=False,
452 help='Include host systems in addition to VMs')
453 parser.add_option('--no-meta-hostvars', action='store_false',
454 dest='meta_hostvars', default=True,
455 help='Exclude [\'_meta\'][\'hostvars\'] with --list')
456 options, args = parser.parse_args()
457
458 if options.include_host_systems:
459 vmware_inventory = VMwareInventory(guests_only=False)
460 else:
461 vmware_inventory = VMwareInventory()
462 if options.host is not None:
463 inventory = vmware_inventory.get_host(options.host)
464 else:
465 inventory = vmware_inventory.get_inventory(options.meta_hostvars)
466
467 json_kwargs = {}
468 if options.pretty:
469 json_kwargs.update({'indent': 4, 'sort_keys': True})
470 json.dump(inventory, sys.stdout, **json_kwargs)
471
472
473 if __name__ == '__main__':
474 main()