| 1 |
# Copyright: (c) 2018, Ansible Project |
| 2 |
# Copyright: (c) 2020, dacrystal |
| 3 |
# Copyright: (c) 2021, Abhijeet Kasurde <[email protected]> |
| 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 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
name: vmware_host_inventory |
| 13 |
deprecated: |
| 14 |
removed_in: 7.0.0 |
| 15 |
why: This module has been moved to the L(new vmware.vmware collection,https://forum.ansible.com/t/5880) |
| 16 |
alternative: Use P(vmware.vmware.esxi_hosts#inventory) instead. |
| 17 |
short_description: VMware ESXi hostsystem inventory source |
| 18 |
author: |
| 19 |
- Abhijeet Kasurde (@Akasurde) |
| 20 |
description: |
| 21 |
- Get VMware ESXi hostsystem as inventory hosts from VMware environment. |
| 22 |
- Uses any file which ends with vmware.yml, vmware.yaml, vmware_host_inventory.yml, or vmware_host_inventory.yaml as a YAML configuration file. |
| 23 |
extends_documentation_fragment: |
| 24 |
- inventory_cache |
| 25 |
- constructed |
| 26 |
requirements: |
| 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 hosts. |
| 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: ['name'] |
| 82 |
properties: |
| 83 |
description: |
| 84 |
- Specify the list of VMware schema properties associated with the ESXi hostsystem. |
| 85 |
- These properties will be populated in hostvars of the given ESXi hostsystem. |
| 86 |
- Each value in the list can be a path to a specific property in hostsystem object or a path to a collection of hostsystem objects. |
| 87 |
- V(summary.runtime.powerState) are required if O(keyed_groups) is set to default. |
| 88 |
- Please make sure that all the properties that are used in other parameters are included in this options. |
| 89 |
- In addition to ESXi hostsystem's properties, the following are special values |
| 90 |
- Use V(customValue) to populate ESXi hostsystem's custom attributes. V(customValue) is only supported by vCenter and not by ESXi. |
| 91 |
- Use V(all) to populate all the properties of the virtual machine. |
| 92 |
The value V(all) is time consuming operation, do not use unless required absolutely. |
| 93 |
type: list |
| 94 |
elements: string |
| 95 |
default: [ 'name', 'customValue', 'summary.runtime.powerState' ] |
| 96 |
with_nested_properties: |
| 97 |
description: |
| 98 |
- This option transform flatten properties name to nested dictionary. |
| 99 |
type: bool |
| 100 |
default: true |
| 101 |
keyed_groups: |
| 102 |
description: |
| 103 |
- Add hosts to group based on the values of a variable. |
| 104 |
type: list |
| 105 |
default: [ |
| 106 |
{key: 'summary.runtime.powerState', separator: ''}, |
| 107 |
] |
| 108 |
filters: |
| 109 |
description: |
| 110 |
- This option allows client-side filtering hosts with jinja templating. |
| 111 |
- When server-side filtering is introduced, it should be preferred over this. |
| 112 |
type: list |
| 113 |
elements: str |
| 114 |
default: [] |
| 115 |
resources: |
| 116 |
description: |
| 117 |
- A list of resources to limit search scope. |
| 118 |
- Each resource item is represented by exactly one C('vim_type_snake_case):C(list of resource names) pair and optional nested I(resources) |
| 119 |
- Key name is based on snake case of a vim type name; e.g V(host_system) correspond to C(vim.HostSystem) |
| 120 |
required: false |
| 121 |
type: list |
| 122 |
elements: dict |
| 123 |
default: [] |
| 124 |
with_path: |
| 125 |
description: |
| 126 |
- Include ESXi hostsystem's path. |
| 127 |
- Set this option to a string value to replace root name from I('Datacenters'). |
| 128 |
default: false |
| 129 |
type: bool |
| 130 |
with_sanitized_property_name: |
| 131 |
description: |
| 132 |
- This option allows property name sanitization to create safe property names for use in Ansible. |
| 133 |
- Also, transforms property name to snake case. |
| 134 |
type: bool |
| 135 |
default: false |
| 136 |
proxy_host: |
| 137 |
description: |
| 138 |
- Address of a proxy that will receive all HTTPS requests and relay them. |
| 139 |
- The format is a hostname or a IP. |
| 140 |
type: str |
| 141 |
required: false |
| 142 |
env: |
| 143 |
- name: VMWARE_PROXY_HOST |
| 144 |
proxy_port: |
| 145 |
description: |
| 146 |
- Port of the HTTP proxy that will receive all HTTPS requests and relay them. |
| 147 |
type: int |
| 148 |
required: false |
| 149 |
env: |
| 150 |
- name: VMWARE_PROXY_PORT |
| 151 |
enable_backward_compatibility: |
| 152 |
description: |
| 153 |
- Flatten the host properties for backward compatibility. |
| 154 |
type: bool |
| 155 |
default: true |
| 156 |
""" |
| 157 |
|
| 158 |
EXAMPLES = r""" |
| 159 |
# Sample configuration file for VMware Host dynamic inventory |
| 160 |
plugin: community.vmware.vmware_host_inventory |
| 161 |
strict: false |
| 162 |
hostname: 10.65.223.31 |
| 163 |
username: [email protected] |
| 164 |
password: Esxi@123$% |
| 165 |
validate_certs: false |
| 166 |
with_tags: true |
| 167 |
|
| 168 |
# Sample configuration file for VMware Guest dynamic inventory using Jinja to template the username and password. |
| 169 |
plugin: community.vmware.vmware_host_inventory |
| 170 |
strict: false |
| 171 |
hostname: 10.65.223.31 |
| 172 |
username: '{{ (lookup("file","~/.config/vmware.yaml") | from_yaml).username }}' |
| 173 |
password: '{{ (lookup("file","~/.config/vmware.yaml") | from_yaml).password }}' |
| 174 |
validate_certs: false |
| 175 |
with_tags: true |
| 176 |
|
| 177 |
# Using compose |
| 178 |
plugin: community.vmware.vmware_host_inventory |
| 179 |
hostname: 10.65.223.31 |
| 180 |
username: [email protected] |
| 181 |
password: Esxi@123$% |
| 182 |
validate_certs: false |
| 183 |
properties: |
| 184 |
- name |
| 185 |
- summary |
| 186 |
- config.lockdownMode |
| 187 |
compose: |
| 188 |
ansible_user: "'root'" |
| 189 |
ansible_connection: "'ssh'" |
| 190 |
""" |
| 191 |
|
| 192 |
try: |
| 193 |
from com.vmware.vapi.std_client import DynamicID |
| 194 |
except ImportError: |
| 195 |
# Already handled in module_utils/inventory.py |
| 196 |
pass |
| 197 |
|
| 198 |
try: |
| 199 |
from pyVmomi import vim |
| 200 |
except ImportError: |
| 201 |
# Already handled in module_utils/inventory.py |
| 202 |
pass |
| 203 |
|
| 204 |
from ansible.errors import AnsibleError |
| 205 |
from ansible.module_utils.common.text.converters import to_text, to_native |
| 206 |
from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict |
| 207 |
from ansible_collections.community.vmware.plugins.plugin_utils.inventory import ( |
| 208 |
to_nested_dict, |
| 209 |
to_flatten_dict, |
| 210 |
) |
| 211 |
from ansible_collections.community.vmware.plugins.inventory.vmware_vm_inventory import BaseVMwareInventory |
| 212 |
from ansible.plugins.inventory import BaseInventoryPlugin, Constructable, Cacheable |
| 213 |
from ansible.parsing.yaml.objects import AnsibleVaultEncryptedUnicode |
| 214 |
|
| 215 |
|
| 216 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 217 |
|
| 218 |
NAME = "community.vmware.vmware_host_inventory" |
| 219 |
|
| 220 |
def verify_file(self, path): |
| 221 |
""" |
| 222 |
Verify plugin configuration file and mark this plugin active |
| 223 |
Args: |
| 224 |
path: Path of configuration YAML file |
| 225 |
Returns: True if everything is correct, else False |
| 226 |
""" |
| 227 |
valid = False |
| 228 |
if super(InventoryModule, self).verify_file(path): |
| 229 |
if path.endswith( |
| 230 |
( |
| 231 |
"vmware.yaml", |
| 232 |
"vmware.yml", |
| 233 |
"vmware_host_inventory.yaml", |
| 234 |
"vmware_host_inventory.yml", |
| 235 |
) |
| 236 |
): |
| 237 |
valid = True |
| 238 |
|
| 239 |
return valid |
| 240 |
|
| 241 |
def parse(self, inventory, loader, path, cache=True): |
| 242 |
""" |
| 243 |
Parses the inventory file |
| 244 |
""" |
| 245 |
super(InventoryModule, self).parse(inventory, loader, path, cache=cache) |
| 246 |
|
| 247 |
cacheable_results = None |
| 248 |
|
| 249 |
cache_key = self.get_cache_key(path) |
| 250 |
|
| 251 |
config_data = self._read_config_data(path) |
| 252 |
|
| 253 |
# set _options from config data |
| 254 |
self._consume_options(config_data) |
| 255 |
|
| 256 |
username = self.get_option("username") |
| 257 |
password = self.get_option("password") |
| 258 |
|
| 259 |
if self.templar.is_template(password): |
| 260 |
password = self.templar.template(variable=password, disable_lookups=False) |
| 261 |
elif isinstance(password, AnsibleVaultEncryptedUnicode): |
| 262 |
password = password.data |
| 263 |
|
| 264 |
if self.templar.is_template(username): |
| 265 |
username = self.templar.template(variable=username, disable_lookups=False) |
| 266 |
elif isinstance(username, AnsibleVaultEncryptedUnicode): |
| 267 |
username = username.data |
| 268 |
|
| 269 |
self.pyv = BaseVMwareInventory( |
| 270 |
hostname=self.get_option("hostname"), |
| 271 |
username=username, |
| 272 |
password=password, |
| 273 |
port=self.get_option("port"), |
| 274 |
with_tags=self.get_option("with_tags"), |
| 275 |
validate_certs=self.get_option("validate_certs"), |
| 276 |
http_proxy_host=self.get_option("proxy_host"), |
| 277 |
http_proxy_port=self.get_option("proxy_port") |
| 278 |
) |
| 279 |
|
| 280 |
self.pyv.do_login() |
| 281 |
|
| 282 |
if cache: |
| 283 |
cache = self.get_option("cache") |
| 284 |
|
| 285 |
update_cache = False |
| 286 |
if cache: |
| 287 |
try: |
| 288 |
cacheable_results = self._cache[cache_key] |
| 289 |
except KeyError: |
| 290 |
update_cache = True |
| 291 |
|
| 292 |
if cache and not update_cache: |
| 293 |
self._populate_from_cache(cacheable_results) |
| 294 |
else: |
| 295 |
cacheable_results = self._populate_from_source() |
| 296 |
|
| 297 |
if update_cache or (not cache and self.get_option("cache")): |
| 298 |
self._cache[cache_key] = cacheable_results |
| 299 |
|
| 300 |
def _populate_from_cache(self, cache_data): |
| 301 |
""" |
| 302 |
Populate cache using source data |
| 303 |
|
| 304 |
""" |
| 305 |
for host, host_properties in cache_data.items(): |
| 306 |
self._populate_host_properties(host_properties, host) |
| 307 |
|
| 308 |
def _populate_from_source(self): |
| 309 |
""" |
| 310 |
Populate inventory data from direct source |
| 311 |
|
| 312 |
""" |
| 313 |
hostvars = {} |
| 314 |
strict = self.get_option("strict") |
| 315 |
|
| 316 |
host_properties = self.get_option("properties") |
| 317 |
if not isinstance(host_properties, list): |
| 318 |
host_properties = [host_properties] |
| 319 |
|
| 320 |
if len(host_properties) == 0: |
| 321 |
host_properties = ["name"] |
| 322 |
|
| 323 |
if "all" in host_properties: |
| 324 |
query_props = None |
| 325 |
host_properties.remove("all") |
| 326 |
else: |
| 327 |
if "runtime.connectionState" not in host_properties: |
| 328 |
host_properties.append("runtime.connectionState") |
| 329 |
query_props = [x for x in host_properties if x != "customValue"] |
| 330 |
|
| 331 |
objects = self.pyv.get_managed_objects_properties( |
| 332 |
vim_type=vim.HostSystem, |
| 333 |
properties=query_props, |
| 334 |
resources=self.get_option("resources"), |
| 335 |
strict=strict, |
| 336 |
) |
| 337 |
|
| 338 |
tags_info = dict() |
| 339 |
if self.pyv.with_tags: |
| 340 |
tag_svc = self.pyv.rest_content.tagging.Tag |
| 341 |
cat_svc = self.pyv.rest_content.tagging.Category |
| 342 |
|
| 343 |
tags = tag_svc.list() |
| 344 |
for tag in tags: |
| 345 |
tag_obj = tag_svc.get(tag) |
| 346 |
tags_info[tag_obj.id] = ( |
| 347 |
tag_obj.name, |
| 348 |
cat_svc.get(tag_obj.category_id).name, |
| 349 |
) |
| 350 |
|
| 351 |
hostnames = self.get_option("hostnames") |
| 352 |
|
| 353 |
for host_obj in objects: |
| 354 |
properties = dict() |
| 355 |
for host_obj_property in host_obj.propSet: |
| 356 |
properties[host_obj_property.name] = host_obj_property.val |
| 357 |
|
| 358 |
if ( |
| 359 |
properties.get("runtime.connectionState") |
| 360 |
or properties["runtime"].connectionState |
| 361 |
) in ("disconnected", "notResponding"): |
| 362 |
continue |
| 363 |
|
| 364 |
# Custom values |
| 365 |
if "customValue" in host_properties: |
| 366 |
field_mgr = [] |
| 367 |
if self.pyv.content.customFieldsManager: # not an ESXi |
| 368 |
field_mgr = self.pyv.content.customFieldsManager.field |
| 369 |
for cust_value in host_obj.obj.customValue: |
| 370 |
properties[ |
| 371 |
[y.name for y in field_mgr if y.key == cust_value.key][0] |
| 372 |
] = cust_value.value |
| 373 |
|
| 374 |
# Tags |
| 375 |
if self.pyv.with_tags: |
| 376 |
properties["tags"] = [] |
| 377 |
properties["categories"] = [] |
| 378 |
properties["tag_category"] = {} |
| 379 |
|
| 380 |
if tags_info: |
| 381 |
# Add virtual machine to appropriate tag group |
| 382 |
host_mo_id = host_obj.obj._GetMoId() # pylint: disable=protected-access |
| 383 |
host_dynamic_id = DynamicID(type="HostSystem", id=host_mo_id) |
| 384 |
tag_association = self.pyv.rest_content.tagging.TagAssociation |
| 385 |
for tag_id in tag_association.list_attached_tags(host_dynamic_id): |
| 386 |
if tag_id not in tags_info: |
| 387 |
# Ghost Tags |
| 388 |
continue |
| 389 |
# Add tags related to VM |
| 390 |
properties["tags"].append(tags_info[tag_id][0]) |
| 391 |
# Add categories related to VM |
| 392 |
properties["categories"].append(tags_info[tag_id][1]) |
| 393 |
# Add tag and categories related to VM |
| 394 |
if tags_info[tag_id][1] not in properties["tag_category"]: |
| 395 |
properties["tag_category"][tags_info[tag_id][1]] = [] |
| 396 |
properties["tag_category"][tags_info[tag_id][1]].append( |
| 397 |
tags_info[tag_id][0] |
| 398 |
) |
| 399 |
|
| 400 |
# Path |
| 401 |
with_path = self.get_option("with_path") |
| 402 |
if with_path: |
| 403 |
path = [] |
| 404 |
parent = host_obj.obj.parent |
| 405 |
while parent: |
| 406 |
path.append(parent.name) |
| 407 |
parent = parent.parent |
| 408 |
path.reverse() |
| 409 |
properties["path"] = "/".join(path) |
| 410 |
|
| 411 |
host_properties = to_nested_dict(properties) |
| 412 |
|
| 413 |
# Check if we can add host as per filters |
| 414 |
host_filters = self.get_option("filters") |
| 415 |
if not self._can_add_host(host_filters, host_properties, strict=strict): |
| 416 |
continue |
| 417 |
|
| 418 |
host = self._get_hostname(host_properties, hostnames, strict=strict) |
| 419 |
|
| 420 |
if host not in hostvars: |
| 421 |
hostvars[host] = host_properties |
| 422 |
self._populate_host_properties(host_properties, host) |
| 423 |
self.inventory.set_variable( |
| 424 |
host, "ansible_host", self.get_management_ip(host_obj.obj) |
| 425 |
) |
| 426 |
|
| 427 |
return hostvars |
| 428 |
|
| 429 |
def _get_hostname(self, properties, hostnames, strict=False): |
| 430 |
hostname = None |
| 431 |
errors = [] |
| 432 |
|
| 433 |
for preference in hostnames: |
| 434 |
try: |
| 435 |
hostname = self._compose(preference, properties) |
| 436 |
except Exception as e: # pylint: disable=broad-except |
| 437 |
if strict: |
| 438 |
raise AnsibleError( |
| 439 |
"Could not compose %s as hostnames - %s" |
| 440 |
% (preference, to_native(e)) |
| 441 |
) |
| 442 |
|
| 443 |
errors.append((preference, str(e))) |
| 444 |
if hostname: |
| 445 |
return to_text(hostname) |
| 446 |
|
| 447 |
raise AnsibleError( |
| 448 |
"Could not template any hostname for host, errors for each preference: %s" |
| 449 |
% (", ".join(["%s: %s" % (pref, err) for pref, err in errors])) |
| 450 |
) |
| 451 |
|
| 452 |
def _can_add_host(self, host_filters, host_properties, strict=False): |
| 453 |
can_add_host = True |
| 454 |
for host_filter in host_filters: |
| 455 |
try: |
| 456 |
can_add_host = self._compose(host_filter, host_properties) |
| 457 |
except Exception as e: # pylint: disable=broad-except |
| 458 |
if strict: |
| 459 |
raise AnsibleError( |
| 460 |
"Could not evaluate %s as host filters - %s" |
| 461 |
% (host_filter, to_native(e)) |
| 462 |
) |
| 463 |
|
| 464 |
if not can_add_host: |
| 465 |
return False |
| 466 |
return True |
| 467 |
|
| 468 |
@staticmethod |
| 469 |
def get_management_ip(host): |
| 470 |
try: |
| 471 |
vnic_manager = host.configManager.virtualNicManager |
| 472 |
net_config = vnic_manager.QueryNetConfig("management") |
| 473 |
# filter nics that are selected |
| 474 |
for nic in net_config.candidateVnic: |
| 475 |
if nic.key in net_config.selectedVnic: |
| 476 |
# add hostvar 'management_ip' to each host |
| 477 |
return nic.spec.ip.ipAddress |
| 478 |
except Exception: |
| 479 |
return "" |
| 480 |
return "" |
| 481 |
|
| 482 |
def _populate_host_properties(self, host_properties, host): |
| 483 |
# Load VM properties in host_vars |
| 484 |
self.inventory.add_host(host) |
| 485 |
|
| 486 |
# Use constructed if applicable |
| 487 |
strict = self.get_option("strict") |
| 488 |
|
| 489 |
# Composed variables |
| 490 |
compose = self.get_option("compose") |
| 491 |
self._set_composite_vars(compose, host_properties, host, strict=strict) |
| 492 |
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group |
| 493 |
self._add_host_to_composed_groups( |
| 494 |
self.get_option("groups"), host_properties, host, strict=strict |
| 495 |
) |
| 496 |
# Create groups based on variable values and add the corresponding hosts to it |
| 497 |
self._add_host_to_keyed_groups( |
| 498 |
self.get_option("keyed_groups"), host_properties, host, strict=strict |
| 499 |
) |
| 500 |
|
| 501 |
with_path = self.get_option("with_path") |
| 502 |
if with_path: |
| 503 |
parents = host_properties["path"].split("/") |
| 504 |
if parents: |
| 505 |
if isinstance(with_path, str): |
| 506 |
parents = [with_path] + parents |
| 507 |
|
| 508 |
c_name = self._sanitize_group_name("/".join(parents)) |
| 509 |
c_group = self.inventory.add_group(c_name) |
| 510 |
self.inventory.add_host(host, c_group) |
| 511 |
parents.pop() |
| 512 |
|
| 513 |
while len(parents) > 0: |
| 514 |
p_name = self._sanitize_group_name("/".join(parents)) |
| 515 |
p_group = self.inventory.add_group(p_name) |
| 516 |
|
| 517 |
self.inventory.add_child(p_group, c_group) |
| 518 |
c_group = p_group |
| 519 |
parents.pop() |
| 520 |
|
| 521 |
can_sanitize = self.get_option("with_sanitized_property_name") |
| 522 |
|
| 523 |
# Sanitize host properties: to snake case |
| 524 |
if can_sanitize: # to snake case |
| 525 |
host_properties = camel_dict_to_snake_dict(host_properties) |
| 526 |
|
| 527 |
with_nested_properties = self.get_option("with_nested_properties") |
| 528 |
if with_nested_properties: |
| 529 |
for k, v in host_properties.items(): |
| 530 |
k = self._sanitize_group_name(k) if can_sanitize else k |
| 531 |
self.inventory.set_variable(host, k, v) |
| 532 |
|
| 533 |
# For backward compatability |
| 534 |
backward_compatibility = self.get_option("enable_backward_compatibility") |
| 535 |
if backward_compatibility: |
| 536 |
host_properties = to_flatten_dict(host_properties) |
| 537 |
for k, v in host_properties.items(): |
| 538 |
k = self._sanitize_group_name(k) if can_sanitize else k |
| 539 |
self.inventory.set_variable(host, k, v) |