Debian Codegraph @

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

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright (C): 2017, Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 # Requirements
8 # - pyvmomi >= 6.0.0.2016.4
9
10 # TODO:
11 # * more jq examples
12 # * optional folder hierarchy
13
14 from __future__ import (absolute_import, division, print_function)
15 __metaclass__ = type
16
17 """
18 $ jq '._meta.hostvars[].config' data.json | head
19 {
20 "alternateguestname": "",
21 "instanceuuid": "5035a5cd-b8e8-d717-e133-2d383eb0d675",
22 "memoryhotaddenabled": false,
23 "guestfullname": "Red Hat Enterprise Linux 7 (64-bit)",
24 "changeversion": "2016-05-16T18:43:14.977925Z",
25 "uuid": "4235fc97-5ddb-7a17-193b-9a3ac97dc7b4",
26 "cpuhotremoveenabled": false,
27 "vpmcenabled": false,
28 "firmware": "bios",
29 """
30
31
32 import atexit
33 import datetime
34 import itertools
35 import json
36 import os
37 import re
38 import ssl
39 import sys
40 import uuid
41 from time import time
42
43 from jinja2 import Environment
44
45 import configparser
46
47 try:
48 import argparse
49 except ImportError:
50 sys.exit('Error: This inventory script required "argparse" python module. Please install it or upgrade to python-2.7')
51
52 try:
53 from pyVmomi import vim, vmodl
54 from pyVim.connect import SmartConnect, Disconnect
55 except ImportError:
56 sys.exit("ERROR: This inventory script required 'pyVmomi' Python module, it was not able to load it")
57
58
59 def regex_match(s, pattern):
60 '''Custom filter for regex matching'''
61 reg = re.compile(pattern)
62 if reg.match(s):
63 return True
64 else:
65 return False
66
67
68 def select_chain_match(inlist, key, pattern):
69 '''Get a key from a list of dicts, squash values to a single list, then filter'''
70 outlist = [x[key] for x in inlist]
71 outlist = list(itertools.chain(*outlist))
72 outlist = [x for x in outlist if regex_match(x, pattern)]
73 return outlist
74
75
76 class VMwareMissingHostException(Exception):
77 pass
78
79
80 class VMWareInventory(object):
81 __name__ = 'VMWareInventory'
82
83 guest_props = False
84 instances = []
85 debug = False
86 load_dumpfile = None
87 write_dumpfile = None
88 maxlevel = 1
89 lowerkeys = True
90 config = None
91 cache_max_age = None
92 cache_path_cache = None
93 cache_path_index = None
94 cache_dir = None
95 server = None
96 port = None
97 username = None
98 password = None
99 validate_certs = True
100 host_filters = []
101 skip_keys = []
102 groupby_patterns = []
103 groupby_custom_field_excludes = []
104
105 safe_types = [bool, str, float, int, None]
106 iter_types = [dict, list]
107
108 bad_types = ['Array', 'disabledMethod', 'declaredAlarmState']
109
110 vimTableMaxDepth = {
111 "vim.HostSystem": 2,
112 "vim.VirtualMachine": 2,
113 }
114
115 custom_fields = {}
116
117 # use jinja environments to allow for custom filters
118 env = Environment()
119 env.filters['regex_match'] = regex_match
120 env.filters['select_chain_match'] = select_chain_match
121
122 # translation table for attributes to fetch for known vim types
123
124 vimTable = {
125 vim.Datastore: ['_moId', 'name'],
126 vim.ResourcePool: ['_moId', 'name'],
127 vim.HostSystem: ['_moId', 'name'],
128 }
129
130 @staticmethod
131 def _empty_inventory():
132 return {"_meta": {"hostvars": {}}}
133
134 def __init__(self, load=True):
135 self.inventory = VMWareInventory._empty_inventory()
136
137 if load:
138 # Read settings and parse CLI arguments
139 self.parse_cli_args()
140 self.read_settings()
141
142 # Check the cache
143 cache_valid = self.is_cache_valid()
144
145 # Handle Cache
146 if self.args.refresh_cache or not cache_valid:
147 self.do_api_calls_update_cache()
148 else:
149 self.debugl('loading inventory from cache')
150 self.inventory = self.get_inventory_from_cache()
151
152 def debugl(self, text):
153 if self.args.debug:
154 try:
155 text = str(text)
156 except UnicodeEncodeError:
157 text = text.encode('utf-8')
158 print('%s %s' % (datetime.datetime.now(), text))
159
160 def show(self):
161 # Data to print
162 self.debugl('dumping results')
163 data_to_print = None
164 if self.args.host:
165 data_to_print = self.get_host_info(self.args.host)
166 elif self.args.list:
167 # Display list of instances for inventory
168 data_to_print = self.inventory
169 return json.dumps(data_to_print, indent=2)
170
171 def is_cache_valid(self):
172 ''' Determines if the cache files have expired, or if it is still valid '''
173
174 valid = False
175
176 if os.path.isfile(self.cache_path_cache):
177 mod_time = os.path.getmtime(self.cache_path_cache)
178 current_time = time()
179 if (mod_time + self.cache_max_age) > current_time:
180 valid = True
181
182 return valid
183
184 def do_api_calls_update_cache(self):
185 ''' Get instances and cache the data '''
186 self.inventory = self.instances_to_inventory(self.get_instances())
187 self.write_to_cache(self.inventory)
188
189 def write_to_cache(self, data):
190 ''' Dump inventory to json file '''
191 with open(self.cache_path_cache, 'w') as f:
192 f.write(json.dumps(data, indent=2))
193
194 def get_inventory_from_cache(self):
195 ''' Read in jsonified inventory '''
196
197 jdata = None
198 with open(self.cache_path_cache, 'r') as f:
199 jdata = f.read()
200 return json.loads(jdata)
201
202 def read_settings(self):
203 ''' Reads the settings from the vmware_inventory.ini file '''
204
205 scriptbasename = __file__
206 scriptbasename = os.path.basename(scriptbasename)
207 scriptbasename = scriptbasename.replace('.py', '')
208
209 defaults = {'vmware': {
210 'server': '',
211 'port': 443,
212 'username': '',
213 'password': '',
214 'validate_certs': True,
215 'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename),
216 'cache_name': 'ansible-vmware',
217 'cache_path': '~/.ansible/tmp',
218 'cache_max_age': 3600,
219 'max_object_level': 1,
220 'skip_keys': 'declaredalarmstate,'
221 'disabledmethod,'
222 'dynamicproperty,'
223 'dynamictype,'
224 'environmentbrowser,'
225 'managedby,'
226 'parent,'
227 'childtype,'
228 'resourceconfig',
229 'alias_pattern': '{{ config.name + "_" + config.uuid }}',
230 'host_pattern': '{{ guest.ipaddress }}',
231 'host_filters': '{{ runtime.powerstate == "poweredOn" }}',
232 'groupby_patterns': '{{ guest.guestid }},{{ "templates" if config.template else "guests"}}',
233 'lower_var_keys': True,
234 'custom_field_group_prefix': 'vmware_tag_',
235 'groupby_custom_field_excludes': '',
236 'groupby_custom_field': False}
237 }
238
239 config = configparser.ConfigParser()
240
241 # where is the config?
242 vmware_ini_path = os.environ.get('VMWARE_INI_PATH', defaults['vmware']['ini_path'])
243 vmware_ini_path = os.path.expanduser(os.path.expandvars(vmware_ini_path))
244 config.read(vmware_ini_path)
245
246 if 'vmware' not in config.sections():
247 config.add_section('vmware')
248
249 # apply defaults
250 for k, v in defaults['vmware'].items():
251 if not config.has_option('vmware', k):
252 config.set('vmware', k, str(v))
253
254 # where is the cache?
255 self.cache_dir = os.path.expanduser(config.get('vmware', 'cache_path'))
256 if self.cache_dir and not os.path.exists(self.cache_dir):
257 os.makedirs(self.cache_dir)
258
259 # set the cache filename and max age
260 cache_name = config.get('vmware', 'cache_name')
261 self.cache_path_cache = self.cache_dir + "/%s.cache" % cache_name
262 self.debugl('cache path is %s' % self.cache_path_cache)
263 self.cache_max_age = int(config.getint('vmware', 'cache_max_age'))
264
265 # mark the connection info
266 self.server = os.environ.get('VMWARE_SERVER', config.get('vmware', 'server'))
267 self.debugl('server is %s' % self.server)
268 self.port = int(os.environ.get('VMWARE_PORT', config.get('vmware', 'port')))
269 self.username = os.environ.get('VMWARE_USERNAME', config.get('vmware', 'username'))
270 self.debugl('username is %s' % self.username)
271 self.password = os.environ.get('VMWARE_PASSWORD', config.get('vmware', 'password', raw=True))
272 self.validate_certs = os.environ.get('VMWARE_VALIDATE_CERTS', config.get('vmware', 'validate_certs'))
273 if self.validate_certs in ['no', 'false', 'False', False]:
274 self.validate_certs = False
275
276 self.debugl('cert validation is %s' % self.validate_certs)
277
278 # behavior control
279 self.maxlevel = int(config.get('vmware', 'max_object_level'))
280 self.debugl('max object level is %s' % self.maxlevel)
281 self.lowerkeys = config.get('vmware', 'lower_var_keys')
282 if not isinstance(self.lowerkeys, bool):
283 if str(self.lowerkeys).lower() in ['yes', 'true', '1']:
284 self.lowerkeys = True
285 else:
286 self.lowerkeys = False
287 self.debugl('lower keys is %s' % self.lowerkeys)
288 self.skip_keys = list(config.get('vmware', 'skip_keys').split(','))
289 self.debugl('skip keys is %s' % self.skip_keys)
290 temp_host_filters = list(config.get('vmware', 'host_filters').split('}},'))
291 for host_filter in temp_host_filters:
292 host_filter = host_filter.rstrip()
293 if host_filter != "":
294 if not host_filter.endswith("}}"):
295 host_filter += "}}"
296 self.host_filters.append(host_filter)
297 self.debugl('host filters are %s' % self.host_filters)
298
299 temp_groupby_patterns = list(config.get('vmware', 'groupby_patterns').split('}},'))
300 for groupby_pattern in temp_groupby_patterns:
301 groupby_pattern = groupby_pattern.rstrip()
302 if groupby_pattern != "":
303 if not groupby_pattern.endswith("}}"):
304 groupby_pattern += "}}"
305 self.groupby_patterns.append(groupby_pattern)
306 self.debugl('groupby patterns are %s' % self.groupby_patterns)
307 temp_groupby_custom_field_excludes = config.get('vmware', 'groupby_custom_field_excludes')
308 self.groupby_custom_field_excludes = [x.strip('"') for x in [y.strip("'") for y in temp_groupby_custom_field_excludes.split(",")]]
309 self.debugl('groupby exclude strings are %s' % self.groupby_custom_field_excludes)
310
311 # Special feature to disable the brute force serialization of the
312 # virtual machine objects. The key name for these properties does not
313 # matter because the values are just items for a larger list.
314 if config.has_section('properties'):
315 self.guest_props = []
316 for prop in config.items('properties'):
317 self.guest_props.append(prop[1])
318
319 # save the config
320 self.config = config
321
322 def parse_cli_args(self):
323 ''' Command line argument processing '''
324
325 parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on PyVmomi')
326 parser.add_argument('--debug', action='store_true', default=False,
327 help='show debug info')
328 parser.add_argument('--list', action='store_true', default=True,
329 help='List instances (default: True)')
330 parser.add_argument('--host', action='store',
331 help='Get all the variables about a specific instance')
332 parser.add_argument('--refresh-cache', action='store_true', default=False,
333 help='Force refresh of cache by making API requests to VSphere (default: False - use cache files)')
334 parser.add_argument('--max-instances', default=None, type=int,
335 help='maximum number of instances to retrieve')
336 self.args = parser.parse_args()
337
338 def get_instances(self):
339 ''' Get a list of vm instances with pyvmomi '''
340 kwargs = {'host': self.server,
341 'user': self.username,
342 'pwd': self.password,
343 'port': int(self.port)}
344
345 if self.validate_certs and hasattr(ssl, 'SSLContext'):
346 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
347 context.verify_mode = ssl.CERT_REQUIRED
348 context.check_hostname = True # noqa # pylint: disable=assigning-non-slot
349 kwargs['sslContext'] = context
350 elif self.validate_certs and not hasattr(ssl, 'SSLContext'):
351 sys.exit('pyVim does not support changing verification mode with python < 2.7.9. Either update '
352 'python or use validate_certs=false.')
353 elif not self.validate_certs and hasattr(ssl, 'SSLContext'):
354 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
355 context.verify_mode = ssl.CERT_NONE
356 context.check_hostname = False # noqa # pylint: disable=assigning-non-slot
357 kwargs['sslContext'] = context
358 elif not self.validate_certs and not hasattr(ssl, 'SSLContext'):
359 # Python 2.7.9 < or RHEL/CentOS 7.4 <
360 pass
361
362 return self._get_instances(kwargs)
363
364 def _get_instances(self, inkwargs):
365 ''' Make API calls '''
366 instances = []
367 si = None
368 try:
369 si = SmartConnect(**inkwargs)
370 except ssl.SSLError as connection_error:
371 if '[SSL: CERTIFICATE_VERIFY_FAILED]' in str(connection_error) and self.validate_certs:
372 sys.exit("Unable to connect to ESXi server due to %s, "
373 "please specify validate_certs=False and try again" % connection_error)
374
375 except Exception as exc:
376 self.debugl("Unable to connect to ESXi server due to %s" % exc)
377 sys.exit("Unable to connect to ESXi server due to %s" % exc)
378
379 self.debugl('retrieving all instances')
380 if not si:
381 sys.exit("Could not connect to the specified host using specified "
382 "username and password")
383 atexit.register(Disconnect, si)
384 content = si.RetrieveContent()
385
386 # Create a search container for virtualmachines
387 self.debugl('creating containerview for virtualmachines')
388 container = content.rootFolder
389 viewType = [vim.VirtualMachine]
390 recursive = True
391 containerView = content.viewManager.CreateContainerView(container, viewType, recursive)
392 children = containerView.view
393 for child in children:
394 # If requested, limit the total number of instances
395 if self.args.max_instances:
396 if len(instances) >= self.args.max_instances:
397 break
398 instances.append(child)
399 self.debugl("%s total instances in container view" % len(instances))
400
401 if self.args.host:
402 instances = [x for x in instances if x.name == self.args.host]
403
404 instance_tuples = []
405 for instance in instances:
406 if self.guest_props:
407 ifacts = self.facts_from_proplist(instance)
408 else:
409 ifacts = self.facts_from_vobj(instance)
410 instance_tuples.append((instance, ifacts))
411 self.debugl('facts collected for all instances')
412
413 try:
414 cfm = content.customFieldsManager
415 if cfm is not None and cfm.field:
416 for f in cfm.field:
417 if not f.managedObjectType or f.managedObjectType == vim.VirtualMachine:
418 self.custom_fields[f.key] = f.name
419 self.debugl('%d custom fields collected' % len(self.custom_fields))
420 except vmodl.RuntimeFault as exc:
421 self.debugl("Unable to gather custom fields due to %s" % exc.msg)
422 except IndexError as exc:
423 self.debugl("Unable to gather custom fields due to %s" % exc)
424
425 return instance_tuples
426
427 def instances_to_inventory(self, instances):
428 ''' Convert a list of vm objects into a json compliant inventory '''
429 self.debugl('re-indexing instances based on ini settings')
430 inventory = VMWareInventory._empty_inventory()
431 inventory['all'] = {}
432 inventory['all']['hosts'] = []
433 for idx, instance in enumerate(instances):
434 # make a unique id for this object to avoid vmware's
435 # numerous uuid's which aren't all unique.
436 thisid = str(uuid.uuid4())
437 idata = instance[1]
438
439 # Put it in the inventory
440 inventory['all']['hosts'].append(thisid)
441 inventory['_meta']['hostvars'][thisid] = idata.copy()
442 inventory['_meta']['hostvars'][thisid]['ansible_uuid'] = thisid
443
444 # Make a map of the uuid to the alias the user wants
445 name_mapping = self.create_template_mapping(
446 inventory,
447 self.config.get('vmware', 'alias_pattern')
448 )
449
450 # Make a map of the uuid to the ssh hostname the user wants
451 host_mapping = self.create_template_mapping(
452 inventory,
453 self.config.get('vmware', 'host_pattern')
454 )
455
456 # Reset the inventory keys
457 for k, v in name_mapping.items():
458
459 if not host_mapping or k not in host_mapping:
460 continue
461
462 # set ansible_host (2.x)
463 try:
464 inventory['_meta']['hostvars'][k]['ansible_host'] = host_mapping[k]
465 # 1.9.x backwards compliance
466 inventory['_meta']['hostvars'][k]['ansible_ssh_host'] = host_mapping[k]
467 except Exception:
468 continue
469
470 if k == v:
471 continue
472
473 # add new key
474 inventory['all']['hosts'].append(v)
475 inventory['_meta']['hostvars'][v] = inventory['_meta']['hostvars'][k]
476
477 # cleanup old key
478 inventory['all']['hosts'].remove(k)
479 inventory['_meta']['hostvars'].pop(k, None)
480
481 self.debugl('pre-filtered hosts:')
482 for i in inventory['all']['hosts']:
483 self.debugl(' * %s' % i)
484 # Apply host filters
485 for hf in self.host_filters:
486 if not hf:
487 continue
488 self.debugl('filter: %s' % hf)
489 filter_map = self.create_template_mapping(inventory, hf, dtype='boolean')
490 for k, v in filter_map.items():
491 if not v:
492 # delete this host
493 inventory['all']['hosts'].remove(k)
494 inventory['_meta']['hostvars'].pop(k, None)
495
496 self.debugl('post-filter hosts:')
497 for i in inventory['all']['hosts']:
498 self.debugl(' * %s' % i)
499
500 # Create groups
501 for gbp in self.groupby_patterns:
502 groupby_map = self.create_template_mapping(inventory, gbp)
503 for k, v in groupby_map.items():
504 if v not in inventory:
505 inventory[v] = {}
506 inventory[v]['hosts'] = []
507 if k not in inventory[v]['hosts']:
508 inventory[v]['hosts'].append(k)
509
510 if self.config.get('vmware', 'groupby_custom_field'):
511 for k, v in inventory['_meta']['hostvars'].items():
512 if 'customvalue' in v:
513 for tv in v['customvalue']:
514 newkey = None
515 field_name = self.custom_fields[tv['key']] if tv['key'] in self.custom_fields else tv['key']
516 if field_name in self.groupby_custom_field_excludes:
517 continue
518 values = []
519 keylist = map(lambda x: x.strip(), tv['value'].split(','))
520 for kl in keylist:
521 try:
522 newkey = "%s%s_%s" % (self.config.get('vmware', 'custom_field_group_prefix'), str(field_name), kl)
523 newkey = newkey.strip()
524 except Exception as e:
525 self.debugl(e)
526 values.append(newkey)
527 for tag in values:
528 if not tag:
529 continue
530 if tag not in inventory:
531 inventory[tag] = {}
532 inventory[tag]['hosts'] = []
533 if k not in inventory[tag]['hosts']:
534 inventory[tag]['hosts'].append(k)
535
536 return inventory
537
538 def create_template_mapping(self, inventory, pattern, dtype='string'):
539 ''' Return a hash of uuid to templated string from pattern '''
540 mapping = {}
541 for k, v in inventory['_meta']['hostvars'].items():
542 t = self.env.from_string(pattern)
543 newkey = None
544 try:
545 newkey = t.render(v)
546 newkey = newkey.strip()
547 except Exception as e:
548 self.debugl(e)
549 if not newkey:
550 continue
551 if dtype == 'integer':
552 newkey = int(newkey)
553 elif dtype == 'boolean':
554 if newkey.lower() == 'false':
555 newkey = False
556 elif newkey.lower() == 'true':
557 newkey = True
558 elif dtype == 'string':
559 pass
560 mapping[k] = newkey
561 return mapping
562
563 def facts_from_proplist(self, vm):
564 '''Get specific properties instead of serializing everything'''
565
566 rdata = {}
567 for prop in self.guest_props:
568 self.debugl('getting %s property for %s' % (prop, vm.name))
569 key = prop
570 if self.lowerkeys:
571 key = key.lower()
572
573 if '.' not in prop:
574 # props without periods are direct attributes of the parent
575 vm_property = getattr(vm, prop)
576 if isinstance(vm_property, vim.CustomFieldsManager.Value.Array):
577 temp_vm_property = []
578 for vm_prop in vm_property:
579 temp_vm_property.append({'key': vm_prop.key,
580 'value': vm_prop.value})
581 rdata[key] = temp_vm_property
582 else:
583 rdata[key] = vm_property
584 else:
585 # props with periods are subkeys of parent attributes
586 parts = prop.split('.')
587 total = len(parts) - 1
588
589 # pointer to the current object
590 val = None
591 # pointer to the current result key
592 lastref = rdata
593
594 for idx, x in enumerate(parts):
595
596 if isinstance(val, dict):
597 if x in val:
598 val = val.get(x)
599 elif x.lower() in val:
600 val = val.get(x.lower())
601 else:
602 # if the val wasn't set yet, get it from the parent
603 if not val:
604 try:
605 val = getattr(vm, x)
606 except AttributeError as e:
607 self.debugl(e)
608 else:
609 # in a subkey, get the subprop from the previous attrib
610 try:
611 val = getattr(val, x)
612 except AttributeError as e:
613 self.debugl(e)
614
615 # make sure it serializes
616 val = self._process_object_types(val)
617
618 # lowercase keys if requested
619 if self.lowerkeys:
620 x = x.lower()
621
622 # change the pointer or set the final value
623 if idx != total:
624 if x not in lastref:
625 lastref[x] = {}
626 lastref = lastref[x]
627 else:
628 lastref[x] = val
629 if self.args.debug:
630 self.debugl("For %s" % vm.name)
631 for key in list(rdata.keys()):
632 if isinstance(rdata[key], dict):
633 for ikey in list(rdata[key].keys()):
634 self.debugl("Property '%s.%s' has value '%s'" % (key, ikey, rdata[key][ikey]))
635 else:
636 self.debugl("Property '%s' has value '%s'" % (key, rdata[key]))
637 return rdata
638
639 def facts_from_vobj(self, vobj, level=0):
640 ''' Traverse a VM object and return a json compliant data structure '''
641
642 # pyvmomi objects are not yet serializable, but may be one day ...
643 # https://github.com/vmware/pyvmomi/issues/21
644
645 # WARNING:
646 # Accessing an object attribute will trigger a SOAP call to the remote.
647 # Increasing the attributes collected or the depth of recursion greatly
648 # increases runtime duration and potentially memory+network utilization.
649
650 if level == 0:
651 try:
652 self.debugl("get facts for %s" % vobj.name)
653 except Exception as e:
654 self.debugl(e)
655
656 rdata = {}
657
658 methods = dir(vobj)
659 methods = [str(x) for x in methods if not x.startswith('_')]
660 methods = [x for x in methods if x not in self.bad_types]
661 methods = [x for x in methods if not x.lower() in self.skip_keys]
662 methods = sorted(methods)
663
664 for method in methods:
665 # Attempt to get the method, skip on fail
666 try:
667 methodToCall = getattr(vobj, method)
668 except Exception as e:
669 continue
670
671 # Skip callable methods
672 if callable(methodToCall):
673 continue
674
675 if self.lowerkeys:
676 method = method.lower()
677
678 rdata[method] = self._process_object_types(
679 methodToCall,
680 thisvm=vobj,
681 inkey=method,
682 )
683
684 return rdata
685
686 def _process_object_types(self, vobj, thisvm=None, inkey='', level=0):
687 ''' Serialize an object '''
688 rdata = {}
689
690 if type(vobj).__name__ in self.vimTableMaxDepth and level >= self.vimTableMaxDepth[type(vobj).__name__]:
691 return rdata
692
693 if vobj is None:
694 rdata = None
695 elif type(vobj) in self.vimTable:
696 rdata = {}
697 for key in self.vimTable[type(vobj)]:
698 try:
699 rdata[key] = getattr(vobj, key)
700 except Exception as e:
701 self.debugl(e)
702
703 elif issubclass(type(vobj), str) or isinstance(vobj, str):
704 if vobj.isalnum():
705 rdata = vobj
706 else:
707 rdata = vobj.encode('utf-8').decode('utf-8')
708 elif issubclass(type(vobj), bool) or isinstance(vobj, bool):
709 rdata = vobj
710 elif issubclass(type(vobj), int) or isinstance(vobj, int):
711 rdata = vobj
712 elif issubclass(type(vobj), float) or isinstance(vobj, float):
713 rdata = vobj
714 elif issubclass(type(vobj), list) or issubclass(type(vobj), tuple):
715 rdata = []
716 try:
717 vobj = sorted(vobj)
718 except Exception:
719 pass
720
721 for idv, vii in enumerate(vobj):
722 if level + 1 <= self.maxlevel:
723 vid = self._process_object_types(
724 vii,
725 thisvm=thisvm,
726 inkey=inkey + '[' + str(idv) + ']',
727 level=(level + 1)
728 )
729
730 if vid:
731 rdata.append(vid)
732
733 elif issubclass(type(vobj), dict):
734 pass
735
736 elif issubclass(type(vobj), object):
737 methods = dir(vobj)
738 methods = [str(x) for x in methods if not x.startswith('_')]
739 methods = [x for x in methods if x not in self.bad_types]
740 methods = [x for x in methods if not inkey + '.' + x.lower() in self.skip_keys]
741 methods = sorted(methods)
742
743 for method in methods:
744 # Attempt to get the method, skip on fail
745 try:
746 methodToCall = getattr(vobj, method)
747 except Exception as e:
748 continue
749
750 if callable(methodToCall):
751 continue
752
753 if self.lowerkeys:
754 method = method.lower()
755 if level + 1 <= self.maxlevel:
756 try:
757 rdata[method] = self._process_object_types(
758 methodToCall,
759 thisvm=thisvm,
760 inkey=inkey + '.' + method,
761 level=(level + 1)
762 )
763 except vim.fault.NoPermission:
764 self.debugl("Skipping method %s (NoPermission)" % method)
765 else:
766 pass
767
768 return rdata
769
770 def get_host_info(self, host):
771 ''' Return hostvars for a single host '''
772
773 if host in self.inventory['_meta']['hostvars']:
774 return self.inventory['_meta']['hostvars'][host]
775 elif self.args.host and self.inventory['_meta']['hostvars']:
776 match = None
777 for k, v in self.inventory['_meta']['hostvars'].items():
778 if self.inventory['_meta']['hostvars'][k]['name'] == self.args.host:
779 match = k
780 break
781 if match:
782 return self.inventory['_meta']['hostvars'][match]
783 else:
784 raise VMwareMissingHostException('%s not found' % host)
785 else:
786 raise VMwareMissingHostException('%s not found' % host)
787
788
789 if __name__ == "__main__":
790 # Run the script
791 print(VMWareInventory().show())