Debian Codegraph @

ansible_collections/community/vmware/plugins/inventory/vmware_vm_inventory.py

raw
1 # Copyright: (c) 2018, Ansible Project
2 # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
3 # Copyright: (c) 2020, dacrystal
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import (absolute_import, division, print_function)
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 name: vmware_vm_inventory
12 deprecated:
13 removed_in: 7.0.0
14 why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880)
15 alternative: Use P(vmware.vmware.vms#inventory) instead.
16 short_description: VMware Guest inventory source
17 author:
18 - Abhijeet Kasurde (@Akasurde)
19 description:
20 - Get virtual machines as inventory hosts from VMware environment.
21 - Uses any file which ends with vmware.yml, vmware.yaml, vmware_vm_inventory.yml, or vmware_vm_inventory.yaml as a YAML configuration file.
22 extends_documentation_fragment:
23 - inventory_cache
24 - constructed
25 requirements:
26 - "requests >= 2.3"
27 - "vSphere Automation SDK - For tag feature"
28 options:
29 hostname:
30 description: Name of vCenter or ESXi server.
31 required: true
32 env:
33 - name: VMWARE_HOST
34 - name: VMWARE_SERVER
35 username:
36 description:
37 - Name of vSphere user.
38 - Accepts vault encrypted variable.
39 - Accepts Jinja to template the value
40 required: true
41 env:
42 - name: VMWARE_USER
43 - name: VMWARE_USERNAME
44 password:
45 description:
46 - Password of vSphere user.
47 - Accepts vault encrypted variable.
48 - Accepts Jinja to template the value
49 required: true
50 env:
51 - name: VMWARE_PASSWORD
52 port:
53 description: Port number used to connect to vCenter or ESXi Server.
54 default: 443
55 type: int
56 env:
57 - name: VMWARE_PORT
58 validate_certs:
59 description:
60 - Allows connection when SSL certificates are not valid.
61 - Set to V(false) when certificates are not trusted.
62 default: true
63 type: bool
64 env:
65 - name: VMWARE_VALIDATE_CERTS
66 with_tags:
67 description:
68 - Include tags and associated virtual machines.
69 - Requires 'vSphere Automation SDK' library to be installed on the given controller machine.
70 - Please refer following URLs for installation steps
71 - U(https://code.vmware.com/web/sdk/7.0/vsphere-automation-python)
72 default: false
73 type: bool
74 hostnames:
75 description:
76 - A list of templates in order of precedence to compose inventory_hostname.
77 - Ignores template if resulted in an empty string or None value.
78 - You can use property specified in O(properties) as variables in the template.
79 type: list
80 elements: string
81 default: ['config.name + "_" + config.uuid']
82 properties:
83 description:
84 - Specify the list of VMware schema properties associated with the VM.
85 - These properties will be populated in hostvars of the given VM.
86 - Each value in the list can be a path to a specific property in VM object or a path to a collection of VM objects.
87 - V(config.name), V(config.uuid) are required properties if O(hostnames) is set to default.
88 - V(config.guestId), V(summary.runtime.powerState) are required if O(keyed_groups) is set to default.
89 - Please make sure that all the properties that are used in other parameters are included in this options.
90 - In addition to VM properties, the following are special values
91 - Use V(customValue) to populate virtual machine's custom attributes. V(customValue) is only supported by vCenter and not by ESXi.
92 - Use V(all) to populate all the properties of the virtual machine.
93 The value V(all) is time consuming operation, do not use unless required absolutely.
94 - Please refer more VMware guest attributes which can be used as properties
95 U(https://docs.ansible.com/ansible/latest/collections/community/vmware/docsite/vmware_scenarios/vmware_inventory_vm_attributes.html)
96 type: list
97 elements: string
98 default: [ 'name', 'config.cpuHotAddEnabled', 'config.cpuHotRemoveEnabled',
99 'config.instanceUuid', 'config.hardware.numCPU', 'config.template',
100 'config.name', 'config.uuid', 'guest.hostName', 'guest.ipAddress',
101 'guest.guestId', 'guest.guestState', 'runtime.maxMemoryUsage',
102 'customValue', 'summary.runtime.powerState', 'config.guestId',
103 ]
104 subproperties:
105 version_added: 4.2.0
106 description:
107 - List of subproperties from an normal property.
108 - These subproperties will also populated to the hostvars of the given VM.
109 type: list
110 elements: dict
111 default: []
112 suboptions:
113 property:
114 description:
115 - Name of the Property
116 type: str
117 required: true
118 subelements:
119 description:
120 - List of subelements
121 type: list
122 elements: str
123 with_nested_properties:
124 description:
125 - This option transform flatten properties name to nested dictionary.
126 type: bool
127 default: true
128 keyed_groups:
129 description:
130 - Add hosts to group based on the values of a variable.
131 type: list
132 default: [
133 {key: 'config.guestId', separator: ''},
134 {key: 'summary.runtime.powerState', separator: ''},
135 ]
136 filters:
137 description:
138 - This option allows client-side filtering hosts with jinja templating.
139 - When server-side filtering is introduced, it should be preferred over this.
140 type: list
141 elements: str
142 default: []
143 resources:
144 description:
145 - A list of resources to limit search scope.
146 - Each resource item is represented by exactly one C('vim_type_snake_case):C(list of resource names) pair and optional nested I(resources)
147 - Key name is based on snake case of a vim type name; e.g V(host_system) correspond to C(vim.HostSystem)
148 - See L(VIM Types,https://pubs.vmware.com/vi-sdk/visdk250/ReferenceGuide/index-mo_types.html)
149 required: false
150 type: list
151 elements: dict
152 default: []
153 with_path:
154 description:
155 - Include virtual machines path.
156 - Set this option to a string value to replace root name from I('Datacenters').
157 default: false
158 type: bool
159 with_sanitized_property_name:
160 description:
161 - This option allows property name sanitization to create safe property names for use in Ansible.
162 - Also, transforms property name to snake case.
163 type: bool
164 default: false
165 proxy_host:
166 description:
167 - Address of a proxy that will receive all HTTPS requests and relay them.
168 - The format is a hostname or a IP.
169 type: str
170 required: false
171 env:
172 - name: VMWARE_PROXY_HOST
173 proxy_port:
174 description:
175 - Port of the HTTP proxy that will receive all HTTPS requests and relay them.
176 type: int
177 required: false
178 env:
179 - name: VMWARE_PROXY_PORT
180 enable_backward_compatibility:
181 description:
182 - Flatten the host properties for backward compatibility.
183 type: bool
184 default: true
185 '''
186
187 EXAMPLES = r'''
188 # Sample configuration file for VMware Guest dynamic inventory
189 plugin: community.vmware.vmware_vm_inventory
190 strict: false
191 hostname: 10.65.223.31
192 username: [email protected]
193 password: Esxi@123$%
194 validate_certs: false
195 with_tags: true
196
197 # Sample configuration file for VMware Guest dynamic inventory using Jinja to template the username and password.
198 plugin: community.vmware.vmware_vm_inventory
199 strict: false
200 hostname: 10.65.223.31
201 username: '{{ (lookup("file","~/.config/vmware.yaml") | from_yaml).username }}'
202 password: '{{ (lookup("file","~/.config/vmware.yaml") | from_yaml).password }}'
203 validate_certs: false
204 with_tags: true
205
206 # Gather minimum set of properties for VMware guest
207 plugin: community.vmware.vmware_vm_inventory
208 strict: false
209 hostname: 10.65.223.31
210 username: [email protected]
211 password: Esxi@123$%
212 validate_certs: false
213 properties:
214 - 'name'
215 - 'guest.ipAddress'
216 - 'config.name'
217 - 'config.uuid'
218
219 # Gather subproperties such as the parent (mostly cluster) of an ESXi
220 plugin: community.vmware.vmware_vm_inventory
221 strict: false
222 hostname: 10.65.223.31
223 username: [email protected]
224 password: Esxi@123$%
225 validate_certs: false
226 properties:
227 - 'name'
228 - 'guest.ipAddress'
229 - 'config.name'
230 - 'config.uuid'
231 subproperties:
232 - property: 'summary.runtime.host'
233 subelements:
234 - 'name'
235 - 'parent.name'
236
237 # Create Groups based upon VMware Tools status
238 plugin: community.vmware.vmware_vm_inventory
239 strict: false
240 hostname: 10.65.223.31
241 username: [email protected]
242 password: Esxi@123$%
243 validate_certs: false
244 properties:
245 - 'name'
246 - 'config.name'
247 - 'guest.toolsStatus'
248 - 'guest.toolsRunningStatus'
249 hostnames:
250 - config.name
251 keyed_groups:
252 - key: guest.toolsStatus
253 separator: ''
254 - key: guest.toolsRunningStatus
255 separator: ''
256
257 # Filter VMs based upon condition
258 plugin: community.vmware.vmware_vm_inventory
259 strict: false
260 hostname: 10.65.223.31
261 username: [email protected]
262 password: Esxi@123$%
263 validate_certs: false
264 properties:
265 - 'runtime.powerState'
266 - 'config.name'
267 filters:
268 - runtime.powerState == "poweredOn"
269 hostnames:
270 - config.name
271
272 # Filter VM's based on OR conditions
273 plugin: community.vmware.vmware_vm_inventory
274 strict: false
275 hostname: 10.65.223.31
276 username: [email protected]
277 password: Esxi@123$%
278 validate_certs: false
279 properties:
280 - 'name'
281 - 'config.name'
282 - 'guest.ipAddress'
283 - 'guest.toolsStatus'
284 - 'guest.toolsRunningStatus'
285 - 'config.guestFullName'
286 - 'config.guestId'
287 hostnames:
288 - 'config.name'
289 filters:
290 - config.guestId == "rhel7_64Guest" or config.name == "rhel_20_04_empty"
291
292 # Filter VM's based on regex conditions
293 plugin: community.vmware.vmware_vm_inventory
294 strict: false
295 hostname: 10.65.223.31
296 username: [email protected]
297 password: Esxi@123$%
298 validate_certs: false
299 properties:
300 - 'config.name'
301 - 'config.guestId'
302 - 'guest.ipAddress'
303 - 'summary.runtime.powerState'
304 filters:
305 - guest.ipAddress is defined and (guest.ipAddress is match('192.168.*') or guest.ipAddress is match('192.169.*'))
306
307 # Using compose and groups
308 plugin: community.vmware.vmware_vm_inventory
309 strict: false
310 hostname: 10.65.223.31
311 username: [email protected]
312 password: Esxi@123$%
313 validate_certs: false
314 properties:
315 - 'name'
316 - 'config.name'
317 - 'guest.ipAddress'
318 compose:
319 # This will populate the IP address of virtual machine if available
320 # and will be used while communicating to the given virtual machine
321 ansible_host: 'guest.ipAddress'
322 composed_var: 'config.name'
323 # This will populate a host variable with a string value
324 ansible_user: "'admin'"
325 ansible_connection: "'ssh'"
326 groups:
327 VMs: true
328 hostnames:
329 - config.name
330
331 # Use Datacenter, Cluster and Folder value to list VMs
332 plugin: community.vmware.vmware_vm_inventory
333 strict: false
334 hostname: 10.65.200.241
335 username: [email protected]
336 password: Esxi@123$%
337 validate_certs: false
338 with_tags: true
339 resources:
340 - datacenter:
341 - Asia-Datacenter1
342 - Asia-Datacenter2
343 resources:
344 - compute_resource:
345 - Asia-Cluster1
346 resources:
347 - host_system:
348 - Asia-ESXI4
349 - folder:
350 - dev
351 - prod
352
353 # Use Category and it's relation with Tag
354 plugin: community.vmware.vmware_vm_inventory
355 strict: false
356 hostname: 10.65.201.128
357 username: [email protected]
358 password: Esxi@123$%
359 validate_certs: false
360 hostnames:
361 - 'config.name'
362 properties:
363 - 'config.name'
364 - 'config.guestId'
365 - 'guest.ipAddress'
366 - 'summary.runtime.powerState'
367 with_tags: true
368 keyed_groups:
369 - key: tag_category.OS
370 prefix: "vmware_tag_os_category_"
371 separator: ""
372 with_nested_properties: true
373 filters:
374 - "tag_category.OS is defined and 'Linux' in tag_category.OS"
375
376 # customizing hostnames based on VM's FQDN. The second hostnames template acts as a fallback mechanism.
377 plugin: community.vmware.vmware_vm_inventory
378 strict: false
379 hostname: 10.65.223.31
380 username: [email protected]
381 password: Esxi@123$%
382 validate_certs: false
383 hostnames:
384 - 'config.name+"."+guest.ipStack.0.dnsConfig.domainName'
385 - 'config.name'
386 properties:
387 - 'config.name'
388 - 'config.guestId'
389 - 'guest.hostName'
390 - 'guest.ipAddress'
391 - 'guest.guestFamily'
392 - 'guest.ipStack'
393
394 # Select a specific IP address for use by ansible when multiple NICs are present on the VM
395 plugin: community.vmware.vmware_vm_inventory
396 strict: false
397 hostname: 10.65.223.31
398 username: [email protected]
399 password: Esxi@123$%
400 validate_certs: false
401 compose:
402 # Set the IP address used by ansible to one that starts by 10.42. or 10.43.
403 ansible_host: >-
404 guest.net
405 | selectattr('ipAddress')
406 | map(attribute='ipAddress')
407 | flatten
408 | select('match', '^10.42.*|^10.43.*')
409 | list
410 | first
411 properties:
412 - guest.net
413
414 # Group hosts using Jinja2 conditionals
415 plugin: community.vmware.vmware_vm_inventory
416 strict: false
417 hostname: 10.65.13.37
418 username: [email protected]
419 password: Esxi@123$%
420 validate_certs: false
421 hostnames:
422 - config.name
423 properties:
424 - 'name'
425 - 'config.name'
426 - 'config.datastoreUrl'
427 groups:
428 slow_storage: "'Nas01' in config.datastoreUrl[0].name"
429 fast_storage: "'SSD' in config.datastoreUrl[0].name"
430 '''
431
432 from ansible.errors import AnsibleError, AnsibleParserError
433 from ansible.module_utils.common.text.converters import to_text, to_native
434 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
435 from ansible.module_utils.common.dict_transformations import _snake_to_camel
436 from ansible.utils.display import Display
437 from ansible_collections.community.vmware.plugins.plugin_utils.inventory import (
438 to_nested_dict,
439 to_flatten_dict,
440 parse_vim_property
441 )
442
443 display = Display()
444
445 try:
446 # requests is required for exception handling of the ConnectionError
447 import requests
448 HAS_REQUESTS = True
449 except ImportError:
450 HAS_REQUESTS = False
451
452 try:
453 from pyVmomi import vim, vmodl
454 HAS_PYVMOMI = True
455 except ImportError:
456 HAS_PYVMOMI = False
457
458 try:
459 from com.vmware.vapi.std_client import DynamicID
460 from vmware.vapi.vsphere.client import create_vsphere_client
461 HAS_VSPHERE = True
462 except ImportError:
463 HAS_VSPHERE = False
464
465
466 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable
467 from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode
468 from ansible_collections.vmware.vmware.plugins.module_utils.clients.pyvmomi import PyvmomiClient
469
470
471 class BaseVMwareInventory:
472 def __init__(self, hostname, username, password, port, validate_certs, with_tags, http_proxy_host, http_proxy_port):
473 self.hostname = hostname
474 self.username = username
475 self.password = password
476 self.port = port
477 self.with_tags = with_tags
478 self.validate_certs = validate_certs
479 self.content = None
480 self.rest_content = None
481 self.proxy_host = http_proxy_host
482 self.proxy_port = http_proxy_port
483
484 def do_login(self):
485 """
486 Check requirements and do login
487 """
488 self.check_requirements()
489 self.si, self.content = self._login()
490 if self.with_tags:
491 self.rest_content = self._login_vapi()
492
493 def _login_vapi(self):
494 """
495 Login to vCenter API using REST call
496 Returns: connection object
497
498 """
499 session = requests.Session()
500 session.verify = self.validate_certs
501 if not self.validate_certs:
502 # Disable warning shown at stdout
503 requests.packages.urllib3.disable_warnings()
504
505 server = self.hostname
506 if self.port:
507 server += ":" + str(self.port)
508
509 client, err = None, None
510 try:
511 client = create_vsphere_client(server=server,
512 username=self.username,
513 password=self.password,
514 session=session)
515 except Exception as error:
516 err = error
517
518 if client is None:
519 msg = "Failed to login to %s using %s" % (server, self.username)
520 if err:
521 msg += " due to : %s" % to_native(err)
522 raise AnsibleError(msg)
523 return client
524
525 def _login(self):
526 """
527 Login to vCenter or ESXi server
528 Returns: connection object
529
530 """
531 pyvmomi_client = PyvmomiClient(
532 hostname=self.hostname,
533 username=self.username,
534 password=self.password,
535 port=self.port, validate_certs=self.validate_certs,
536 http_proxy_host=self.proxy_host,
537 http_proxy_port=self.proxy_port)
538
539 return pyvmomi_client.si, pyvmomi_client.content
540
541 def check_requirements(self):
542 """ Check all requirements for this inventory are satisfied"""
543 if not HAS_REQUESTS:
544 raise AnsibleParserError('Please install "requests" Python module as this is required'
545 ' for VMware Guest dynamic inventory plugin.')
546 elif not HAS_PYVMOMI:
547 raise AnsibleParserError('Please install "PyVmomi" Python module as this is required'
548 ' for VMware Guest dynamic inventory plugin.')
549 if HAS_REQUESTS:
550 # Pyvmomi 5.5 and onwards requires requests 2.3
551 # https://github.com/vmware/pyvmomi/blob/master/requirements.txt
552 required_version = (2, 3)
553 requests_version = requests.__version__.split(".")[:2]
554 try:
555 requests_major_minor = tuple(map(int, requests_version))
556 except ValueError:
557 raise AnsibleParserError("Failed to parse 'requests' library version.")
558
559 if requests_major_minor < required_version:
560 raise AnsibleParserError("'requests' library version should"
561 " be >= %s, found: %s." % (".".join([str(w) for w in required_version]),
562 requests.__version__))
563
564 if not HAS_VSPHERE and self.with_tags:
565 raise AnsibleError("Unable to find 'vSphere Automation SDK' Python library which is required."
566 " Please refer this URL for installation steps"
567 " - https://code.vmware.com/web/sdk/7.0/vsphere-automation-python")
568
569 if not all([self.hostname, self.username, self.password]):
570 raise AnsibleError("Missing one of the following : hostname, username, password. Please read "
571 "the documentation for more information.")
572
573 def get_managed_objects_properties(self, vim_type, properties=None, resources=None, strict=False):
574 """
575 Look up a Managed Object Reference in vCenter / ESXi Environment
576 :param vim_type: Type of vim object e.g, for datacenter - vim.Datacenter
577 :param properties: List of properties related to vim object e.g. Name
578 :param resources: List of resources to limit search scope
579 :param strict: Dictates if plugin raises error or just warns
580 :return: local content object
581 """
582 TraversalSpec = vmodl.query.PropertyCollector.TraversalSpec
583 FilterSpec = vmodl.query.PropertyCollector.FilterSpec
584 ObjectSpec = vmodl.query.PropertyCollector.ObjectSpec
585 PropertySpec = vmodl.query.PropertyCollector.PropertySpec
586
587 resource_filters = resources or []
588 type_to_name_map = {}
589
590 def _handle_error(message):
591 if strict:
592 raise AnsibleError(message)
593 else:
594 display.warning(message)
595
596 def get_contents(container, vim_types):
597 return self.content.propertyCollector.RetrieveContents([
598 FilterSpec(
599 objectSet=[
600 ObjectSpec(
601 obj=self.content.viewManager.CreateContainerView(
602 container, vim_types, True),
603 skip=False,
604 selectSet=[TraversalSpec(
605 type=vim.view.ContainerView, path='view', skip=False)]
606 )],
607 propSet=[PropertySpec(type=t, all=False, pathSet=['name']) for t in vim_types],
608 )
609 ])
610
611 def filter_containers(containers, typ, filter_list):
612 if len(filter_list) > 0:
613 objs = []
614 results = []
615 found_filters = {}
616
617 for container in containers:
618 results.extend(get_contents(container, [typ]))
619
620 for res in results:
621 if res.propSet[0].val in filter_list:
622 objs.append(res.obj)
623 found_filters[res.propSet[0].val] = True
624
625 for fil in filter_list:
626 if fil not in found_filters:
627 _handle_error("Unable to find %s %s" % (type_to_name_map[typ], fil))
628
629 return objs
630 return containers
631
632 def build_containers(containers, vim_type, names, filters):
633 filters = filters or []
634 if vim_type:
635 containers = filter_containers(containers, vim_type, names)
636
637 new_containers = []
638 for fil in filters:
639 new_filters = None
640 for k, v in fil.items():
641 if k == "resources":
642 new_filters = v
643 else:
644 vim_type = getattr(vim, _snake_to_camel(k, True))
645 names = v
646 type_to_name_map[vim_type] = k.replace("_", " ")
647
648 new_containers.extend(build_containers(containers, vim_type, names, new_filters))
649
650 if len(filters) > 0:
651 return new_containers
652 return containers
653
654 containers = build_containers([self.content.rootFolder], None, None, resource_filters)
655 if len(containers) == 0:
656 return []
657
658 objs_list = [ObjectSpec(
659 obj=self.content.viewManager.CreateContainerView(r, [vim_type], True),
660 selectSet=[TraversalSpec(path='view', skip=False, type=vim.view.ContainerView)]) for r in containers]
661
662 is_all = False if properties else True
663
664 # Create Property Spec
665 property_spec = PropertySpec(
666 type=vim_type, # Type of object to retrieved
667 all=is_all,
668 pathSet=properties
669 )
670
671 # Create Filter Spec
672 filter_spec = FilterSpec(
673 objectSet=objs_list,
674 propSet=[property_spec],
675 reportMissingObjectsInResults=False
676 )
677
678 try:
679 return self.content.propertyCollector.RetrieveContents([filter_spec])
680 except vmodl.query.InvalidProperty as err:
681 _handle_error("Invalid property name: %s" % err.name)
682 except Exception as err: # pylint: disable=broad-except
683 _handle_error("Couldn't retrieve contents from host: %s" % to_native(err))
684 return []
685
686
687 class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable):
688
689 NAME = 'community.vmware.vmware_vm_inventory'
690
691 def verify_file(self, path):
692 """
693 Verify plugin configuration file and mark this plugin active
694 Args:
695 path: Path of configuration YAML file
696 Returns: True if everything is correct, else False
697 """
698 valid = False
699 if super(InventoryModule, self).verify_file(path):
700 if path.endswith(('vmware.yaml', 'vmware.yml', 'vmware_vm_inventory.yaml', 'vmware_vm_inventory.yml')):
701 valid = True
702
703 return valid
704
705 def parse(self, inventory, loader, path, cache=True):
706 """
707 Parses the inventory file
708 """
709 super(InventoryModule, self).parse(inventory, loader, path, cache=cache)
710
711 cacheable_results = None
712
713 cache_key = self.get_cache_key(path)
714
715 config_data = self._read_config_data(path)
716
717 # set _options from config data
718 self._consume_options(config_data)
719
720 username = self.get_option('username')
721 password = self.get_option('password')
722
723 if self.templar.is_template(password):
724 password = self.templar.template(variable=password, disable_lookups=False)
725 elif isinstance(password, AnsibleVaultEncryptedUnicode):
726 password = password.data
727
728 if self.templar.is_template(username):
729 username = self.templar.template(variable=username, disable_lookups=False)
730 elif isinstance(username, AnsibleVaultEncryptedUnicode):
731 username = username.data
732
733 self.pyv = BaseVMwareInventory(
734 hostname=self.get_option('hostname'),
735 username=username,
736 password=password,
737 port=self.get_option('port'),
738 with_tags=self.get_option('with_tags'),
739 validate_certs=self.get_option('validate_certs'),
740 http_proxy_host=self.get_option('proxy_host'),
741 http_proxy_port=self.get_option('proxy_port')
742 )
743 self.pyv.do_login()
744
745 if cache:
746 cache = self.get_option('cache')
747
748 update_cache = False
749 if cache:
750 try:
751 cacheable_results = self._cache[cache_key]
752 except KeyError:
753 update_cache = True
754
755 if cache and not update_cache:
756 self._populate_from_cache(cacheable_results)
757 else:
758 cacheable_results = self._populate_from_source()
759
760 if update_cache or (not cache and self.get_option('cache')):
761 self._cache[cache_key] = cacheable_results
762
763 def _populate_from_cache(self, cache_data):
764 """
765 Populate cache using source data
766
767 """
768 for host, host_properties in cache_data.items():
769 self._populate_host_properties(host_properties, host)
770
771 def _populate_from_source(self):
772 """
773 Populate inventory data from direct source
774
775 """
776 hostvars = {}
777 strict = self.get_option('strict')
778
779 vm_properties = self.get_option('properties')
780 vm_subproperties = {e['property']: e['subelements'] for e in self.get_option('subproperties')}
781 vm_properties.extend(vm_subproperties.keys())
782
783 if not isinstance(vm_properties, list):
784 vm_properties = [vm_properties]
785
786 if len(vm_properties) == 0:
787 vm_properties = ['name']
788
789 if 'all' in vm_properties:
790 query_props = None
791 vm_properties.remove('all')
792 else:
793 if 'runtime.connectionState' not in vm_properties:
794 vm_properties.append('runtime.connectionState')
795 query_props = [x for x in vm_properties if x != "customValue"]
796
797 objects = self.pyv.get_managed_objects_properties(
798 vim_type=vim.VirtualMachine,
799 properties=query_props,
800 resources=self.get_option('resources'),
801 strict=strict,
802 )
803
804 tags_info = dict()
805 if self.pyv.with_tags:
806 tag_svc = self.pyv.rest_content.tagging.Tag
807 cat_svc = self.pyv.rest_content.tagging.Category
808
809 tags = tag_svc.list()
810 for tag in tags:
811 tag_obj = tag_svc.get(tag)
812 tags_info[tag_obj.id] = (tag_obj.name, cat_svc.get(tag_obj.category_id).name)
813
814 hostnames = self.get_option('hostnames')
815
816 for vm_obj in objects:
817 properties = dict()
818 for vm_obj_property in vm_obj.propSet:
819 if vm_obj_property.name in vm_subproperties:
820 for subproperty in vm_subproperties[vm_obj_property.name]:
821 subproperty_parts = subproperty.split('.')
822
823 value = vm_obj_property.val
824 for subproperty_part in subproperty_parts:
825 value = value.__getattribute__(subproperty_part)
826
827 subproperty_parsed = parse_vim_property(value)
828 properties[vm_obj_property.name + "." + subproperty] = subproperty_parsed
829 else:
830 properties[vm_obj_property.name] = vm_obj_property.val
831
832 if (properties.get('runtime.connectionState') or properties['runtime'].connectionState) in ('orphaned', 'inaccessible', 'disconnected'):
833 continue
834
835 # Custom values
836 if 'customValue' in vm_properties:
837 field_mgr = []
838 if self.pyv.content.customFieldsManager: # not an ESXi
839 field_mgr = self.pyv.content.customFieldsManager.field
840 for cust_value in vm_obj.obj.customValue:
841 properties[[y.name for y in field_mgr if y.key == cust_value.key][0]] = cust_value.value
842
843 # Tags
844 if tags_info:
845 # Add virtual machine to appropriate tag group
846 vm_mo_id = vm_obj.obj._GetMoId() # pylint: disable=protected-access
847 vm_dynamic_id = DynamicID(type='VirtualMachine', id=vm_mo_id)
848 tag_association = self.pyv.rest_content.tagging.TagAssociation
849 properties['tags'] = []
850 properties['categories'] = []
851 properties['tag_category'] = {}
852 for tag_id in tag_association.list_attached_tags(vm_dynamic_id):
853 if tag_id not in tags_info:
854 # Ghost Tags - community.vmware#681
855 continue
856 # Add tags related to VM
857 properties['tags'].append(tags_info[tag_id][0])
858 # Add categories related to VM
859 properties['categories'].append(tags_info[tag_id][1])
860 # Add tag and categories related to VM
861 if tags_info[tag_id][1] not in properties['tag_category']:
862 properties['tag_category'][tags_info[tag_id][1]] = []
863 properties['tag_category'][tags_info[tag_id][1]].append(tags_info[tag_id][0])
864
865 # Path
866 with_path = self.get_option('with_path')
867 if with_path:
868 path = []
869 parent = vm_obj.obj.parent
870 while parent:
871 path.append(parent.name)
872 parent = parent.parent
873 path.reverse()
874 properties['path'] = "/".join(path)
875
876 host_properties = to_nested_dict(properties)
877
878 # Check if we can add host as per filters
879 host_filters = self.get_option('filters')
880 if not self._can_add_host(host_filters, host_properties, strict=strict):
881 continue
882
883 host = self._get_hostname(host_properties, hostnames, strict=strict)
884
885 if host not in hostvars:
886 hostvars[host] = host_properties
887 self._populate_host_properties(host_properties, host)
888
889 return hostvars
890
891 def _get_hostname(self, properties, hostnames, strict=False):
892 hostname = None
893 errors = []
894
895 for preference in hostnames:
896 try:
897 hostname = self._compose(preference, properties)
898 except Exception as e: # pylint: disable=broad-except
899 if strict:
900 raise AnsibleError("Could not compose %s as hostnames - %s" % (preference, to_native(e)))
901 else:
902 errors.append(
903 (preference, str(e))
904 )
905 if hostname:
906 return to_text(hostname)
907
908 raise AnsibleError(
909 'Could not template any hostname for host, errors for each preference: %s' % (
910 ', '.join(['%s: %s' % (pref, err) for pref, err in errors])
911 )
912 )
913
914 def _can_add_host(self, host_filters, host_properties, strict=False):
915 can_add_host = True
916 for host_filter in host_filters:
917 try:
918 can_add_host = self._compose(host_filter, host_properties)
919 except Exception as e: # pylint: disable=broad-except
920 if strict:
921 raise AnsibleError("Could not evaluate %s as host filters - %s" % (host_filter, to_native(e)))
922
923 if not can_add_host:
924 return False
925 return True
926
927 def _populate_host_properties(self, host_properties, host):
928 # Load VM properties in host_vars
929 self.inventory.add_host(host)
930
931 # Use constructed if applicable
932 strict = self.get_option('strict')
933
934 # Composed variables
935 compose = self.get_option('compose')
936 if not compose:
937 compose['ansible_host'] = 'guest.ipAddress'
938
939 self._set_composite_vars(compose, host_properties, host, strict=strict)
940 # Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
941 self._add_host_to_composed_groups(self.get_option('groups'), host_properties, host, strict=strict)
942 # Create groups based on variable values and add the corresponding hosts to it
943 self._add_host_to_keyed_groups(self.get_option('keyed_groups'), host_properties, host, strict=strict)
944
945 with_path = self.get_option('with_path')
946 if with_path:
947 parents = host_properties['path'].split('/')
948 if parents:
949 if isinstance(with_path, str):
950 parents = [with_path] + parents
951
952 c_name = self._sanitize_group_name('/'.join(parents))
953 c_group = self.inventory.add_group(c_name)
954 self.inventory.add_host(host, c_group)
955 parents.pop()
956
957 while len(parents) > 0:
958 p_name = self._sanitize_group_name('/'.join(parents))
959 p_group = self.inventory.add_group(p_name)
960
961 self.inventory.add_child(p_group, c_group)
962 c_group = p_group
963 parents.pop()
964
965 can_sanitize = self.get_option('with_sanitized_property_name')
966
967 # Sanitize host properties: to snake case
968 if can_sanitize: # to snake case
969 host_properties = camel_dict_to_snake_dict(host_properties)
970
971 with_nested_properties = self.get_option('with_nested_properties')
972 if with_nested_properties:
973 for k, v in host_properties.items():
974 k = self._sanitize_group_name(k) if can_sanitize else k
975 self.inventory.set_variable(host, k, v)
976
977 # For backward compatability
978 backward_compatibility = self.get_option("enable_backward_compatibility")
979 if backward_compatibility:
980 host_properties = to_flatten_dict(host_properties)
981 for k, v in host_properties.items():
982 k = self._sanitize_group_name(k) if can_sanitize else k
983 self.inventory.set_variable(host, k, v)