| 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 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
|
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
import ssl |
| 13 |
import atexit |
| 14 |
import base64 |
| 15 |
|
| 16 |
try: |
| 17 |
# requests is required for exception handling of the ConnectionError |
| 18 |
import requests |
| 19 |
|
| 20 |
HAS_REQUESTS = True |
| 21 |
except ImportError: |
| 22 |
HAS_REQUESTS = False |
| 23 |
|
| 24 |
try: |
| 25 |
from pyVim import connect |
| 26 |
from pyVmomi import vim, vmodl |
| 27 |
from pyVmomi.VmomiSupport import DataObject |
| 28 |
from pyVmomi import Iso8601 |
| 29 |
|
| 30 |
HAS_PYVMOMI = True |
| 31 |
except ImportError: |
| 32 |
HAS_PYVMOMI = False |
| 33 |
|
| 34 |
try: |
| 35 |
from vmware.vapi.vsphere.client import create_vsphere_client |
| 36 |
|
| 37 |
HAS_VSPHERE = True |
| 38 |
except ImportError: |
| 39 |
HAS_VSPHERE = False |
| 40 |
|
| 41 |
from ansible.errors import AnsibleError, AnsibleParserError |
| 42 |
from ansible.module_utils.common.dict_transformations import _snake_to_camel |
| 43 |
from ansible.module_utils.common.text.converters import to_text, to_native |
| 44 |
|
| 45 |
|
| 46 |
class BaseVMwareInventory: |
| 47 |
def __init__( |
| 48 |
self, hostname, username, password, port, validate_certs, with_tags, display |
| 49 |
): |
| 50 |
self.hostname = hostname |
| 51 |
self.username = username |
| 52 |
self.password = password |
| 53 |
self.port = port |
| 54 |
self.with_tags = with_tags |
| 55 |
self.validate_certs = validate_certs |
| 56 |
self.content = None |
| 57 |
self.rest_content = None |
| 58 |
self.display = display |
| 59 |
|
| 60 |
def do_login(self): |
| 61 |
""" |
| 62 |
Check requirements and do login |
| 63 |
""" |
| 64 |
self.check_requirements() |
| 65 |
self.si, self.content = self._login() |
| 66 |
if self.with_tags: |
| 67 |
self.rest_content = self._login_vapi() |
| 68 |
|
| 69 |
def _login_vapi(self): |
| 70 |
""" |
| 71 |
Login to vCenter API using REST call |
| 72 |
Returns: connection object |
| 73 |
|
| 74 |
""" |
| 75 |
session = requests.Session() |
| 76 |
session.verify = self.validate_certs |
| 77 |
if not self.validate_certs: |
| 78 |
# Disable warning shown at stdout |
| 79 |
requests.packages.urllib3.disable_warnings() |
| 80 |
|
| 81 |
server = self.hostname |
| 82 |
if self.port: |
| 83 |
server += ":" + str(self.port) |
| 84 |
|
| 85 |
client, err = None, None |
| 86 |
try: |
| 87 |
client = create_vsphere_client( |
| 88 |
server=server, |
| 89 |
username=self.username, |
| 90 |
password=self.password, |
| 91 |
session=session, |
| 92 |
) |
| 93 |
except Exception as error: |
| 94 |
err = error |
| 95 |
|
| 96 |
if client is None: |
| 97 |
msg = "Failed to login to %s using %s" % (server, self.username) |
| 98 |
if err: |
| 99 |
msg += " due to : %s" % to_native(err) |
| 100 |
raise AnsibleError(msg) |
| 101 |
return client |
| 102 |
|
| 103 |
def _login(self): |
| 104 |
""" |
| 105 |
Login to vCenter or ESXi server |
| 106 |
Returns: connection object |
| 107 |
|
| 108 |
""" |
| 109 |
if self.validate_certs and not hasattr(ssl, "SSLContext"): |
| 110 |
raise AnsibleError( |
| 111 |
"pyVim does not support changing verification mode with python < 2.7.9. Either update " |
| 112 |
"python or set validate_certs to false in configuration YAML file." |
| 113 |
) |
| 114 |
|
| 115 |
ssl_context = None |
| 116 |
if not self.validate_certs and hasattr(ssl, "SSLContext"): |
| 117 |
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) |
| 118 |
ssl_context.verify_mode = ssl.CERT_NONE |
| 119 |
|
| 120 |
service_instance = None |
| 121 |
try: |
| 122 |
service_instance = connect.SmartConnect( |
| 123 |
host=self.hostname, |
| 124 |
user=self.username, |
| 125 |
pwd=self.password, |
| 126 |
sslContext=ssl_context, |
| 127 |
port=self.port, |
| 128 |
) |
| 129 |
|
| 130 |
except vim.fault.InvalidLogin as e: |
| 131 |
raise AnsibleParserError( |
| 132 |
"Unable to log on to vCenter or ESXi API at %s:%s as %s: %s" |
| 133 |
% (self.hostname, self.port, self.username, e.msg) |
| 134 |
) |
| 135 |
except vim.fault.NoPermission as e: |
| 136 |
raise AnsibleParserError( |
| 137 |
"User %s does not have required permission" |
| 138 |
" to log on to vCenter or ESXi API at %s:%s : %s" |
| 139 |
% (self.username, self.hostname, self.port, e.msg) |
| 140 |
) |
| 141 |
except (requests.ConnectionError, ssl.SSLError) as e: |
| 142 |
raise AnsibleParserError( |
| 143 |
"Unable to connect to vCenter or ESXi API at %s on TCP/%s: %s" |
| 144 |
% (self.hostname, self.port, e) |
| 145 |
) |
| 146 |
except vmodl.fault.InvalidRequest as e: |
| 147 |
# Request is malformed |
| 148 |
raise AnsibleParserError( |
| 149 |
"Failed to get a response from server %s:%s as " |
| 150 |
"request is malformed: %s" % (self.hostname, self.port, e.msg) |
| 151 |
) |
| 152 |
except Exception as e: |
| 153 |
raise AnsibleParserError( |
| 154 |
"Unknown error while connecting to vCenter or ESXi API at %s:%s : %s" |
| 155 |
% (self.hostname, self.port, e) |
| 156 |
) |
| 157 |
|
| 158 |
if service_instance is None: |
| 159 |
raise AnsibleParserError( |
| 160 |
"Unknown error while connecting to vCenter or ESXi API at %s:%s" |
| 161 |
% (self.hostname, self.port) |
| 162 |
) |
| 163 |
|
| 164 |
atexit.register(connect.Disconnect, service_instance) |
| 165 |
return service_instance, service_instance.RetrieveContent() |
| 166 |
|
| 167 |
def check_requirements(self): |
| 168 |
""" Check all requirements for this inventory are satisfied""" |
| 169 |
if not HAS_REQUESTS: |
| 170 |
raise AnsibleParserError( |
| 171 |
'Please install "requests" Python module as this is required' |
| 172 |
" for VMware Guest dynamic inventory plugin." |
| 173 |
) |
| 174 |
if not HAS_PYVMOMI: |
| 175 |
raise AnsibleParserError( |
| 176 |
'Please install "PyVmomi" Python module as this is required' |
| 177 |
" for VMware Guest dynamic inventory plugin." |
| 178 |
) |
| 179 |
if HAS_REQUESTS: |
| 180 |
# Pyvmomi 5.5 and onwards requires requests 2.3 |
| 181 |
# https://github.com/vmware/pyvmomi/blob/master/requirements.txt |
| 182 |
required_version = (2, 3) |
| 183 |
requests_version = requests.__version__.split(".")[:2] |
| 184 |
try: |
| 185 |
requests_major_minor = tuple(map(int, requests_version)) |
| 186 |
except ValueError: |
| 187 |
raise AnsibleParserError("Failed to parse 'requests' library version.") |
| 188 |
|
| 189 |
if requests_major_minor < required_version: |
| 190 |
raise AnsibleParserError( |
| 191 |
"'requests' library version should" |
| 192 |
" be >= %s, found: %s." |
| 193 |
% ( |
| 194 |
".".join([str(w) for w in required_version]), |
| 195 |
requests.__version__, |
| 196 |
) |
| 197 |
) |
| 198 |
|
| 199 |
if not HAS_VSPHERE and self.with_tags: |
| 200 |
raise AnsibleError( |
| 201 |
"Unable to find 'vSphere Automation SDK' Python library which is required." |
| 202 |
" Please refer this URL for installation steps" |
| 203 |
" - https://code.vmware.com/web/sdk/7.0/vsphere-automation-python" |
| 204 |
) |
| 205 |
|
| 206 |
if not all([self.hostname, self.username, self.password]): |
| 207 |
raise AnsibleError( |
| 208 |
"Missing one of the following : hostname, username, password. Please read " |
| 209 |
"the documentation for more information." |
| 210 |
) |
| 211 |
|
| 212 |
def get_managed_objects_properties( |
| 213 |
self, vim_type, properties=None, resources=None, strict=False |
| 214 |
): |
| 215 |
""" |
| 216 |
Look up a Managed Object Reference in vCenter / ESXi Environment |
| 217 |
:param vim_type: Type of vim object e.g, for datacenter - vim.Datacenter |
| 218 |
:param properties: List of properties related to vim object e.g. Name |
| 219 |
:param resources: List of resources to limit search scope |
| 220 |
:param strict: Dictates if plugin raises error or just warns |
| 221 |
:return: local content object |
| 222 |
""" |
| 223 |
traversal_spec = vmodl.query.PropertyCollector.TraversalSpec |
| 224 |
filter_spec = vmodl.query.PropertyCollector.FilterSpec |
| 225 |
object_spec = vmodl.query.PropertyCollector.ObjectSpec |
| 226 |
property_spec = vmodl.query.PropertyCollector.PropertySpec |
| 227 |
|
| 228 |
resource_filters = resources or [] |
| 229 |
type_to_name_map = {} |
| 230 |
|
| 231 |
def _handle_error(message): |
| 232 |
if strict: |
| 233 |
raise AnsibleError(message) |
| 234 |
self.display.warning(message) |
| 235 |
|
| 236 |
def get_contents(container, vim_types): |
| 237 |
return self.content.propertyCollector.RetrieveContents( |
| 238 |
[ |
| 239 |
filter_spec( |
| 240 |
objectSet=[ |
| 241 |
object_spec( |
| 242 |
obj=self.content.viewManager.CreateContainerView( |
| 243 |
container, vim_types, True |
| 244 |
), |
| 245 |
skip=False, |
| 246 |
selectSet=[ |
| 247 |
traversal_spec( |
| 248 |
type=vim.view.ContainerView, |
| 249 |
path="view", |
| 250 |
skip=False, |
| 251 |
) |
| 252 |
], |
| 253 |
) |
| 254 |
], |
| 255 |
propSet=[ |
| 256 |
property_spec(type=t, all=False, pathSet=["name"]) |
| 257 |
for t in vim_types |
| 258 |
], |
| 259 |
) |
| 260 |
] |
| 261 |
) |
| 262 |
|
| 263 |
def filter_containers(containers, typ, filter_list): |
| 264 |
if len(filter_list) > 0: |
| 265 |
objs = [] |
| 266 |
results = [] |
| 267 |
found_filters = {} |
| 268 |
|
| 269 |
for container in containers: |
| 270 |
results.extend(get_contents(container, [typ])) |
| 271 |
|
| 272 |
for res in results: |
| 273 |
if res.propSet[0].val in filter_list: |
| 274 |
objs.append(res.obj) |
| 275 |
found_filters[res.propSet[0].val] = True |
| 276 |
|
| 277 |
for fil in filter_list: |
| 278 |
if fil not in found_filters: |
| 279 |
_handle_error( |
| 280 |
"Unable to find %s %s" % (type_to_name_map[typ], fil) |
| 281 |
) |
| 282 |
|
| 283 |
return objs |
| 284 |
return containers |
| 285 |
|
| 286 |
def build_containers(containers, vim_type, names, filters): |
| 287 |
filters = filters or [] |
| 288 |
if vim_type: |
| 289 |
containers = filter_containers(containers, vim_type, names) |
| 290 |
|
| 291 |
new_containers = [] |
| 292 |
for fil in filters: |
| 293 |
new_filters = None |
| 294 |
for k, v in fil.items(): |
| 295 |
if k == "resources": |
| 296 |
new_filters = v |
| 297 |
else: |
| 298 |
vim_type = getattr(vim, _snake_to_camel(k, True)) |
| 299 |
names = v |
| 300 |
type_to_name_map[vim_type] = k.replace("_", " ") |
| 301 |
|
| 302 |
new_containers.extend( |
| 303 |
build_containers(containers, vim_type, names, new_filters) |
| 304 |
) |
| 305 |
|
| 306 |
if len(filters) > 0: |
| 307 |
return new_containers |
| 308 |
return containers |
| 309 |
|
| 310 |
containers = build_containers( |
| 311 |
[self.content.rootFolder], None, None, resource_filters |
| 312 |
) |
| 313 |
if len(containers) == 0: |
| 314 |
return [] |
| 315 |
|
| 316 |
objs_list = [ |
| 317 |
object_spec( |
| 318 |
obj=self.content.viewManager.CreateContainerView(r, [vim_type], True), |
| 319 |
selectSet=[ |
| 320 |
traversal_spec(path="view", skip=False, type=vim.view.ContainerView) |
| 321 |
], |
| 322 |
) |
| 323 |
for r in containers |
| 324 |
] |
| 325 |
|
| 326 |
is_all = not properties |
| 327 |
|
| 328 |
# Create Property Spec |
| 329 |
property_spec = property_spec( |
| 330 |
type=vim_type, all=is_all, pathSet=properties # Type of object to retrieved |
| 331 |
) |
| 332 |
|
| 333 |
# Create Filter Spec |
| 334 |
filter_spec = filter_spec( |
| 335 |
objectSet=objs_list, |
| 336 |
propSet=[property_spec], |
| 337 |
reportMissingObjectsInResults=False, |
| 338 |
) |
| 339 |
|
| 340 |
try: |
| 341 |
return self.content.propertyCollector.RetrieveContents([filter_spec]) |
| 342 |
except vmodl.query.InvalidProperty as err: |
| 343 |
_handle_error("Invalid property name: %s" % err.name) |
| 344 |
except Exception as err: # pylint: disable=broad-except |
| 345 |
_handle_error("Couldn't retrieve contents from host: %s" % to_native(err)) |
| 346 |
return [] |
| 347 |
|
| 348 |
|
| 349 |
def in_place_merge(a, b): |
| 350 |
""" |
| 351 |
Recursively merges second dict into the first. |
| 352 |
|
| 353 |
""" |
| 354 |
if not isinstance(b, dict): |
| 355 |
return b |
| 356 |
for k, v in b.items(): |
| 357 |
if k in a and isinstance(a[k], dict): |
| 358 |
a[k] = in_place_merge(a[k], v) |
| 359 |
else: |
| 360 |
a[k] = v |
| 361 |
return a |
| 362 |
|
| 363 |
|
| 364 |
def to_nested_dict(vm_properties): |
| 365 |
""" |
| 366 |
Parse properties from dot notation to dict |
| 367 |
|
| 368 |
""" |
| 369 |
|
| 370 |
host_properties = {} |
| 371 |
|
| 372 |
for vm_prop_name, vm_prop_val in vm_properties.items(): |
| 373 |
prop_parents = reversed(vm_prop_name.split(".")) |
| 374 |
prop_dict = parse_vim_property(vm_prop_val) |
| 375 |
|
| 376 |
for k in prop_parents: |
| 377 |
prop_dict = {k: prop_dict} |
| 378 |
host_properties = in_place_merge(host_properties, prop_dict) |
| 379 |
|
| 380 |
return host_properties |
| 381 |
|
| 382 |
|
| 383 |
def to_flatten_dict(d, parent_key="", sep="."): |
| 384 |
""" |
| 385 |
Parse properties dict to dot notation |
| 386 |
|
| 387 |
""" |
| 388 |
items = [] |
| 389 |
for k, v in d.items(): |
| 390 |
new_key = parent_key + sep + k if parent_key else k |
| 391 |
if v and isinstance(v, dict): |
| 392 |
items.extend(to_flatten_dict(v, new_key, sep=sep).items()) |
| 393 |
else: |
| 394 |
items.append((new_key, v)) |
| 395 |
return dict(items) |
| 396 |
|
| 397 |
|
| 398 |
def parse_vim_property(vim_prop): |
| 399 |
""" |
| 400 |
Helper method to parse VIM properties of virtual machine |
| 401 |
""" |
| 402 |
prop_type = type(vim_prop).__name__ |
| 403 |
if prop_type.startswith(("vim", "vmodl", "Link")): |
| 404 |
if isinstance(vim_prop, DataObject): |
| 405 |
r = {} |
| 406 |
for prop in vim_prop._GetPropertyList(): # pylint: disable=protected-access |
| 407 |
if prop.name not in [ |
| 408 |
"dynamicProperty", |
| 409 |
"dynamicType", |
| 410 |
"managedObjectType", |
| 411 |
]: |
| 412 |
sub_prop = getattr(vim_prop, prop.name) |
| 413 |
r[prop.name] = parse_vim_property(sub_prop) |
| 414 |
return r |
| 415 |
|
| 416 |
if isinstance(vim_prop, list): |
| 417 |
r = [] |
| 418 |
for prop in vim_prop: |
| 419 |
r.append(parse_vim_property(prop)) |
| 420 |
return r |
| 421 |
return vim_prop.__str__() |
| 422 |
|
| 423 |
elif prop_type == "datetime": |
| 424 |
return Iso8601.ISO8601Format(vim_prop) |
| 425 |
|
| 426 |
elif prop_type == "long": |
| 427 |
return int(vim_prop) |
| 428 |
elif prop_type == "long[]": |
| 429 |
return [int(x) for x in vim_prop] |
| 430 |
|
| 431 |
elif isinstance(vim_prop, list): |
| 432 |
return [parse_vim_property(x) for x in vim_prop] |
| 433 |
|
| 434 |
elif prop_type in ["bool", "int", "NoneType", "dict"]: |
| 435 |
return vim_prop |
| 436 |
|
| 437 |
elif prop_type in ["binary"]: |
| 438 |
return to_text(base64.b64encode(vim_prop)) |
| 439 |
|
| 440 |
return to_text(vim_prop) |