| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# based on code vmware_deploy_ovf from Matt Martz <[email protected]> |
| 5 |
# Copyright: (c) 2023, Alexander Nikitin <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r''' |
| 14 |
author: |
| 15 |
- Alexander Nikitin (@ihumster) |
| 16 |
- Matt Martz (@sivel) |
| 17 |
short_description: 'Deploys a VMware virtual machine from an OVF or OVA file, placed on file system or HTTP server' |
| 18 |
description: |
| 19 |
- 'This module can be used to deploy a VMware VM from an OVF or OVA file, placed on file system or HTTP server' |
| 20 |
module: vmware_deploy_ovf |
| 21 |
notes: |
| 22 |
- 'For use https as source need enable in firewall incoming 443 port' |
| 23 |
options: |
| 24 |
allow_duplicates: |
| 25 |
default: "True" |
| 26 |
description: |
| 27 |
- Whether or not to allow duplicate VM names. ESXi allows duplicates, vCenter may not. |
| 28 |
type: bool |
| 29 |
datacenter: |
| 30 |
default: ha-datacenter |
| 31 |
description: |
| 32 |
- Datacenter to deploy to. |
| 33 |
type: str |
| 34 |
cluster: |
| 35 |
description: |
| 36 |
- Cluster to deploy to. |
| 37 |
- This is a required parameter, if O(esxi_hostname) is not set and O(hostname) is set to the vCenter server. |
| 38 |
- O(esxi_hostname) and O(cluster) are mutually exclusive parameters. |
| 39 |
type: str |
| 40 |
esxi_hostname: |
| 41 |
description: |
| 42 |
- The ESXi hostname where the virtual machine will run. |
| 43 |
- This is a required parameter, if O(cluster) is not set and O(hostname) is set to the vCenter server. |
| 44 |
- O(esxi_hostname) and O(cluster) are mutually exclusive parameters. |
| 45 |
type: str |
| 46 |
datastore: |
| 47 |
default: datastore1 |
| 48 |
description: |
| 49 |
- Datastore to deploy to. |
| 50 |
type: str |
| 51 |
deployment_option: |
| 52 |
description: |
| 53 |
- The key of the chosen deployment option. |
| 54 |
type: str |
| 55 |
disk_provisioning: |
| 56 |
choices: |
| 57 |
- flat |
| 58 |
- eagerZeroedThick |
| 59 |
- monolithicSparse |
| 60 |
- twoGbMaxExtentSparse |
| 61 |
- twoGbMaxExtentFlat |
| 62 |
- thin |
| 63 |
- sparse |
| 64 |
- thick |
| 65 |
- seSparse |
| 66 |
- monolithicFlat |
| 67 |
default: thin |
| 68 |
description: |
| 69 |
- Disk provisioning type. |
| 70 |
type: str |
| 71 |
enable_hidden_properties: |
| 72 |
description: |
| 73 |
- Enable source properties that are marked as C(ovf:userConfigurable=false). |
| 74 |
default: false |
| 75 |
version_added: '3.11.0' |
| 76 |
type: bool |
| 77 |
fail_on_spec_warnings: |
| 78 |
description: |
| 79 |
- Cause the module to treat OVF Import Spec warnings as errors. |
| 80 |
default: false |
| 81 |
type: bool |
| 82 |
folder: |
| 83 |
description: |
| 84 |
- Absolute path of folder to place the virtual machine. |
| 85 |
- If not specified, defaults to the value of C(datacenter.vmFolder). |
| 86 |
- 'Examples:' |
| 87 |
- ' folder: /ha-datacenter/vm' |
| 88 |
- ' folder: ha-datacenter/vm' |
| 89 |
- ' folder: /datacenter1/vm' |
| 90 |
- ' folder: datacenter1/vm' |
| 91 |
- ' folder: /datacenter1/vm/folder1' |
| 92 |
- ' folder: datacenter1/vm/folder1' |
| 93 |
- ' folder: /folder1/datacenter1/vm' |
| 94 |
- ' folder: folder1/datacenter1/vm' |
| 95 |
- ' folder: /folder1/datacenter1/vm/folder2' |
| 96 |
type: str |
| 97 |
inject_ovf_env: |
| 98 |
description: |
| 99 |
- Force the given properties to be inserted into an OVF Environment and injected through VMware Tools. |
| 100 |
type: bool |
| 101 |
default: false |
| 102 |
name: |
| 103 |
description: |
| 104 |
- Name of the VM to work with. |
| 105 |
- Virtual machine names in vCenter are not necessarily unique, which may be problematic. |
| 106 |
type: str |
| 107 |
networks: |
| 108 |
default: |
| 109 |
VM Network: VM Network |
| 110 |
description: |
| 111 |
- 'C(key: value) mapping of OVF network name, to the vCenter network name.' |
| 112 |
type: dict |
| 113 |
ovf: |
| 114 |
description: |
| 115 |
- 'Path to OVF or OVA file to deploy.' |
| 116 |
- Required if O(url) is not set. |
| 117 |
- O(ovf) and O(url) are mutually exclusive parameters. |
| 118 |
aliases: |
| 119 |
- ova |
| 120 |
type: path |
| 121 |
url: |
| 122 |
description: |
| 123 |
- 'URL for OVA file to deploy.' |
| 124 |
- Required if O(ovf) is not set. |
| 125 |
- O(url) and O(ovf) are mutually exclusive parameters. |
| 126 |
type: str |
| 127 |
version_added: '3.9.0' |
| 128 |
power_on: |
| 129 |
default: true |
| 130 |
description: |
| 131 |
- 'Whether or not to power on the virtual machine after creation.' |
| 132 |
type: bool |
| 133 |
properties: |
| 134 |
description: |
| 135 |
- The assignment of values to the properties found in the OVF as key value pairs. |
| 136 |
type: dict |
| 137 |
resource_pool: |
| 138 |
default: Resources |
| 139 |
description: |
| 140 |
- Resource Pool to deploy to. |
| 141 |
type: str |
| 142 |
wait: |
| 143 |
default: true |
| 144 |
description: |
| 145 |
- 'Wait for the host to power on.' |
| 146 |
type: bool |
| 147 |
wait_for_ip_address: |
| 148 |
default: false |
| 149 |
description: |
| 150 |
- Wait until vCenter detects an IP address for the VM. |
| 151 |
- This requires vmware-tools (vmtoolsd) to properly work after creation. |
| 152 |
type: bool |
| 153 |
extends_documentation_fragment: |
| 154 |
- vmware.vmware.base_options |
| 155 |
|
| 156 |
''' |
| 157 |
|
| 158 |
EXAMPLES = r''' |
| 159 |
- community.vmware.vmware_deploy_ovf: |
| 160 |
hostname: '{{ vcenter_hostname }}' |
| 161 |
username: '{{ vcenter_username }}' |
| 162 |
password: '{{ vcenter_password }}' |
| 163 |
ovf: /path/to/ubuntu-16.04-amd64.ovf |
| 164 |
wait_for_ip_address: true |
| 165 |
delegate_to: localhost |
| 166 |
|
| 167 |
# Deploys a new VM named 'NewVM' in specific datacenter/cluster, with network mapping taken from variable and using ova template from an absolute path |
| 168 |
- community.vmware.vmware_deploy_ovf: |
| 169 |
hostname: '{{ vcenter_hostname }}' |
| 170 |
username: '{{ vcenter_username }}' |
| 171 |
password: '{{ vcenter_password }}' |
| 172 |
datacenter: Datacenter1 |
| 173 |
cluster: Cluster1 |
| 174 |
datastore: vsandatastore |
| 175 |
name: NewVM |
| 176 |
networks: "{u'VM Network':u'{{ ProvisioningNetworkLabel }}'}" |
| 177 |
power_on: false |
| 178 |
ovf: /absolute/path/to/template/mytemplate.ova |
| 179 |
delegate_to: localhost |
| 180 |
|
| 181 |
- community.vmware.vmware_deploy_ovf: |
| 182 |
hostname: '{{ vcenter_hostname }}' |
| 183 |
username: '{{ vcenter_username }}' |
| 184 |
password: '{{ vcenter_password }}' |
| 185 |
datacenter: Datacenter1 |
| 186 |
esxi_hostname: test-server |
| 187 |
datastore: test-datastore |
| 188 |
ovf: /path/to/ubuntu-16.04-amd64.ovf |
| 189 |
delegate_to: localhost |
| 190 |
|
| 191 |
- community.vmware.vmware_deploy_ovf: |
| 192 |
hostname: '{{ vcenter_hostname }}' |
| 193 |
username: '{{ vcenter_username }}' |
| 194 |
password: '{{ vcenter_password }}' |
| 195 |
url: https://cloud-images.ubuntu.com/releases/xenial/release/ubuntu-16.04-server-cloudimg-amd64.ova |
| 196 |
wait_for_ip_address: true |
| 197 |
delegate_to: localhost |
| 198 |
''' |
| 199 |
|
| 200 |
|
| 201 |
RETURN = r''' |
| 202 |
instance: |
| 203 |
description: metadata about the new virtual machine |
| 204 |
returned: always |
| 205 |
type: dict |
| 206 |
sample: None |
| 207 |
''' |
| 208 |
|
| 209 |
import hashlib |
| 210 |
import io |
| 211 |
import os |
| 212 |
import re |
| 213 |
import ssl |
| 214 |
import sys |
| 215 |
import tarfile |
| 216 |
import time |
| 217 |
import traceback |
| 218 |
|
| 219 |
import xml.etree.ElementTree as ET |
| 220 |
|
| 221 |
from threading import Thread |
| 222 |
|
| 223 |
from ansible.module_utils.common.text.converters import to_native |
| 224 |
from ansible.module_utils.basic import AnsibleModule |
| 225 |
from urllib.request import Request, urlopen |
| 226 |
from ansible.module_utils.urls import generic_urlparse, open_url, urlparse, urlunparse |
| 227 |
from ansible_collections.community.vmware.plugins.module_utils.vmware import ( |
| 228 |
find_all_networks_by_name, |
| 229 |
find_vm_by_name, |
| 230 |
PyVmomi, |
| 231 |
gather_vm_facts, |
| 232 |
wait_for_task, |
| 233 |
wait_for_vm_ip, |
| 234 |
set_vm_power_state) |
| 235 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec |
| 236 |
try: |
| 237 |
from ansible_collections.community.vmware.plugins.module_utils.vmware import vim |
| 238 |
from pyVmomi import vmodl |
| 239 |
except ImportError: |
| 240 |
pass |
| 241 |
|
| 242 |
|
| 243 |
def path_exists(value): |
| 244 |
if not isinstance(value, str): |
| 245 |
value = str(value) |
| 246 |
value = os.path.expanduser(os.path.expandvars(value)) |
| 247 |
if not os.path.exists(value): |
| 248 |
raise ValueError(f"'{value}' is not a valid path") |
| 249 |
return value |
| 250 |
|
| 251 |
|
| 252 |
class WebHandle(object): |
| 253 |
def __init__(self, url): |
| 254 |
self.url = url |
| 255 |
self.thumbprint = None |
| 256 |
self.ssl_context = None |
| 257 |
|
| 258 |
self.parsed_url = self._parse_url(url) |
| 259 |
self.https = self.parsed_url.group('scheme') == 'https://' |
| 260 |
|
| 261 |
if self.https: |
| 262 |
self.ssl_context = ssl._create_default_https_context() |
| 263 |
self.ssl_context.check_hostname = False |
| 264 |
self.ssl_context.verify_mode = ssl.CERT_NONE |
| 265 |
|
| 266 |
self.thumbprint = self._get_thumbprint( |
| 267 |
self.parsed_url.group('hostname')) |
| 268 |
r = urlopen(Request(url, method="HEAD"), context=self.ssl_context) |
| 269 |
else: |
| 270 |
r = urlopen(Request(url, method="HEAD")) |
| 271 |
|
| 272 |
if r.code != 200: |
| 273 |
raise FileNotFoundError(url) |
| 274 |
self.headers = self._headers_to_dict(r) |
| 275 |
|
| 276 |
if 'content-length' not in self.headers: |
| 277 |
raise Exception("Missing content-length in response") |
| 278 |
self.st_size = int(self.headers['content-length']) |
| 279 |
|
| 280 |
# Perform a real range test instead of checking 'accept-ranges' |
| 281 |
if not self._supports_range_request(): |
| 282 |
raise Exception("Site does not support range requests (no valid response to Range header)") |
| 283 |
|
| 284 |
self.offset = 0 |
| 285 |
|
| 286 |
def _supports_range_request(self): |
| 287 |
req = Request(self.url) |
| 288 |
req.add_header('Range', 'bytes=0-0') |
| 289 |
try: |
| 290 |
if self.ssl_context: |
| 291 |
r = urlopen(req, context=self.ssl_context) |
| 292 |
else: |
| 293 |
r = urlopen(req) |
| 294 |
return r.status == 206 # Partial Content |
| 295 |
except Exception: |
| 296 |
return False |
| 297 |
|
| 298 |
def _parse_url(self, url): |
| 299 |
HTTP_SCHEMA_PATTERN = ( |
| 300 |
r"(?P<url>(?:(?P<scheme>[a-zA-Z]+:\/\/)?(?P<hostname>(?:[-a-zA-Z0-9@%_\+~#=]{1,256}\.){1,256}(?:[-a-zA-Z0-9@%_\+~#=]{1,256})))" |
| 301 |
r"(?::(?P<port>[[:digit:]]+))?(?P<path>(?:\/[-a-zA-Z0-9!$&'()*+,\\\/:;=@\[\]._~%]*)*)" |
| 302 |
r"(?P<query>(?:(?:\#|\?)[-a-zA-Z0-9!$&'()*+,\\\/:;=@\[\]._~]*)*))" |
| 303 |
) |
| 304 |
return re.match(HTTP_SCHEMA_PATTERN, url) |
| 305 |
|
| 306 |
def _get_thumbprint(self, hostname): |
| 307 |
pem = ssl.get_server_certificate((hostname, 443)) |
| 308 |
sha1 = hashlib.sha1(ssl.PEM_cert_to_DER_cert(pem)).hexdigest().upper() |
| 309 |
colon_notion = ':'.join(sha1[i:i + 2] for i in range(0, len(sha1), 2)) |
| 310 |
return None if sha1 is None else colon_notion |
| 311 |
|
| 312 |
def _headers_to_dict(self, r): |
| 313 |
result = {} |
| 314 |
if hasattr(r, 'getheaders'): |
| 315 |
for n, v in r.getheaders(): |
| 316 |
result[n.lower()] = v.strip() |
| 317 |
else: |
| 318 |
for line in r.info().headers: |
| 319 |
if line.find(':') != -1: |
| 320 |
n, v = line.split(': ', 1) |
| 321 |
result[n.lower()] = v.strip() |
| 322 |
return result |
| 323 |
|
| 324 |
def tell(self): |
| 325 |
return self.offset |
| 326 |
|
| 327 |
def seek(self, offset, whence=0): |
| 328 |
if whence == 0: |
| 329 |
self.offset = offset |
| 330 |
elif whence == 1: |
| 331 |
self.offset += offset |
| 332 |
elif whence == 2: |
| 333 |
self.offset = self.st_size - offset |
| 334 |
return self.offset |
| 335 |
|
| 336 |
def seekable(self): |
| 337 |
return True |
| 338 |
|
| 339 |
def read(self, amount): |
| 340 |
start = self.offset |
| 341 |
end = self.offset + amount - 1 |
| 342 |
req = Request(self.url, |
| 343 |
headers={'Range': 'bytes=%d-%d' % (start, end)}) |
| 344 |
r = urlopen(req) if not self.ssl_context else urlopen( |
| 345 |
req, context=self.ssl_context) |
| 346 |
self.offset += amount |
| 347 |
result = r.read(amount) |
| 348 |
r.close() |
| 349 |
return result |
| 350 |
|
| 351 |
# A slightly more accurate percentage |
| 352 |
def progress(self): |
| 353 |
return int(100.0 * self.offset / self.st_size) |
| 354 |
|
| 355 |
|
| 356 |
class ProgressReader(io.FileIO): |
| 357 |
def __init__(self, name, mode='r', closefd=True): |
| 358 |
self.bytes_read = 0 |
| 359 |
io.FileIO.__init__(self, name, mode=mode, closefd=closefd) |
| 360 |
|
| 361 |
def read(self, size=10240): |
| 362 |
chunk = io.FileIO.read(self, size) |
| 363 |
self.bytes_read += len(chunk) |
| 364 |
return chunk |
| 365 |
|
| 366 |
|
| 367 |
class TarFileProgressReader(tarfile.ExFileObject): |
| 368 |
def __init__(self, *args): |
| 369 |
self.bytes_read = 0 |
| 370 |
tarfile.ExFileObject.__init__(self, *args) |
| 371 |
|
| 372 |
def __enter__(self): |
| 373 |
return self |
| 374 |
|
| 375 |
def __exit__(self, exc_type, exc_value, traceback): |
| 376 |
try: |
| 377 |
self.close() |
| 378 |
except Exception: |
| 379 |
pass |
| 380 |
|
| 381 |
def read(self, size=10240): |
| 382 |
chunk = tarfile.ExFileObject.read(self, size) |
| 383 |
self.bytes_read += len(chunk) |
| 384 |
return chunk |
| 385 |
|
| 386 |
|
| 387 |
class VMDKUploader(Thread): |
| 388 |
def __init__(self, vmdk, url, validate_certs=True, tarinfo=None, create=False): |
| 389 |
Thread.__init__(self) |
| 390 |
|
| 391 |
self.vmdk = vmdk |
| 392 |
|
| 393 |
if tarinfo: |
| 394 |
self.size = tarinfo.size |
| 395 |
else: |
| 396 |
self.size = os.stat(vmdk).st_size |
| 397 |
|
| 398 |
self.url = url |
| 399 |
self.validate_certs = validate_certs |
| 400 |
self.tarinfo = tarinfo |
| 401 |
|
| 402 |
self.f = None |
| 403 |
self.e = None |
| 404 |
|
| 405 |
self._create = create |
| 406 |
|
| 407 |
@property |
| 408 |
def bytes_read(self): |
| 409 |
try: |
| 410 |
return self.f.bytes_read |
| 411 |
except AttributeError: |
| 412 |
return 0 |
| 413 |
|
| 414 |
def _request_opts(self): |
| 415 |
''' |
| 416 |
Requests for vmdk files differ from other file types. Build the request options here to handle that |
| 417 |
''' |
| 418 |
headers = { |
| 419 |
'Content-Length': self.size, |
| 420 |
'Content-Type': 'application/octet-stream', |
| 421 |
} |
| 422 |
|
| 423 |
if self._create: |
| 424 |
# Non-VMDK |
| 425 |
method = 'PUT' |
| 426 |
headers['Overwrite'] = 't' |
| 427 |
else: |
| 428 |
# VMDK |
| 429 |
method = 'POST' |
| 430 |
headers['Content-Type'] = 'application/x-vnd.vmware-streamVmdk' |
| 431 |
|
| 432 |
return { |
| 433 |
'method': method, |
| 434 |
'headers': headers, |
| 435 |
} |
| 436 |
|
| 437 |
def _open_url(self): |
| 438 |
open_url(self.url, data=self.f, validate_certs=self.validate_certs, **self._request_opts()) |
| 439 |
|
| 440 |
def run(self): |
| 441 |
if self.tarinfo: |
| 442 |
try: |
| 443 |
with TarFileProgressReader(self.vmdk, self.tarinfo) as self.f: |
| 444 |
self._open_url() |
| 445 |
except Exception: |
| 446 |
self.e = sys.exc_info() |
| 447 |
else: |
| 448 |
try: |
| 449 |
with ProgressReader(self.vmdk, 'rb') as self.f: |
| 450 |
self._open_url() |
| 451 |
except Exception: |
| 452 |
self.e = sys.exc_info() |
| 453 |
|
| 454 |
|
| 455 |
class VMwareDeployOvf(PyVmomi): |
| 456 |
def __init__(self, module): |
| 457 |
super(VMwareDeployOvf, self).__init__(module) |
| 458 |
self.module = module |
| 459 |
self.params = module.params |
| 460 |
|
| 461 |
self.handle = None |
| 462 |
self.datastore = None |
| 463 |
self.datacenter = None |
| 464 |
self.resource_pool = None |
| 465 |
self.network_mappings = [] |
| 466 |
|
| 467 |
self.ovf_descriptor = None |
| 468 |
self.tar = None |
| 469 |
|
| 470 |
self.lease = None |
| 471 |
self.import_spec = None |
| 472 |
self.entity = None |
| 473 |
|
| 474 |
def get_objects(self): |
| 475 |
# Get datacenter firstly |
| 476 |
self.datacenter = self.find_datacenter_by_name(self.params['datacenter']) |
| 477 |
if self.datacenter is None: |
| 478 |
self.module.fail_json(msg=f"Datacenter '{self.params['datacenter']}' could not be located") |
| 479 |
|
| 480 |
# Get cluster in datacenter if cluster configured |
| 481 |
if self.params['cluster']: |
| 482 |
cluster = self.find_cluster_by_name(self.params['cluster'], datacenter_name=self.datacenter) |
| 483 |
if cluster is None: |
| 484 |
self.module.fail_json(msg=f"Unable to find cluster '{self.params['cluster']}'") |
| 485 |
self.resource_pool = self.find_resource_pool_by_cluster(self.params['resource_pool'], cluster=cluster) |
| 486 |
# Or get ESXi host in datacenter if ESXi host configured |
| 487 |
elif self.params['esxi_hostname']: |
| 488 |
host = self.find_hostsystem_by_name(self.params['esxi_hostname'], datacenter=self.datacenter) |
| 489 |
if host is None: |
| 490 |
self.module.fail_json(msg=f"Unable to find host '{self.params['esxi_hostname']}' in datacenter" |
| 491 |
" '{self.params['datacenter']}'") |
| 492 |
self.resource_pool = self.find_resource_pool_by_name(self.params['resource_pool'], folder=host.parent) |
| 493 |
else: |
| 494 |
# For more than one datacenter env, specify 'folder' to datacenter hostFolder |
| 495 |
self.resource_pool = self.find_resource_pool_by_name(self.params['resource_pool'], folder=self.datacenter.hostFolder) |
| 496 |
|
| 497 |
if not self.resource_pool: |
| 498 |
self.module.fail_json(msg=f"Resource pool '{self.params['resource_pool']}' could not be located") |
| 499 |
|
| 500 |
self.datastore = None |
| 501 |
datastore_cluster_obj = self.find_datastore_cluster_by_name(self.params['datastore'], datacenter=self.datacenter) |
| 502 |
if datastore_cluster_obj: |
| 503 |
datastore = None |
| 504 |
datastore_freespace = 0 |
| 505 |
for ds in datastore_cluster_obj.childEntity: |
| 506 |
if isinstance(ds, vim.Datastore) and ds.summary.freeSpace > datastore_freespace: |
| 507 |
# If datastore field is provided, filter destination datastores |
| 508 |
if ds.summary.maintenanceMode != 'normal' or not ds.summary.accessible: |
| 509 |
continue |
| 510 |
datastore = ds |
| 511 |
datastore_freespace = ds.summary.freeSpace |
| 512 |
if datastore: |
| 513 |
self.datastore = datastore |
| 514 |
else: |
| 515 |
self.datastore = self.find_datastore_by_name(self.params['datastore'], datacenter_name=self.datacenter) |
| 516 |
|
| 517 |
if self.datastore is None: |
| 518 |
self.module.fail_json(msg=f"Datastore '{self.params['datastore']}' could not be located on specified ESXi host or" |
| 519 |
" datacenter") |
| 520 |
|
| 521 |
for key, value in self.params['networks'].items(): |
| 522 |
# If we have the same network name defined in multiple clusters, check all networks to get the right one |
| 523 |
networks = find_all_networks_by_name(self.content, value, datacenter_name=self.datacenter) |
| 524 |
if not networks: |
| 525 |
self.module.fail_json(msg=f"Network '{value}' could not be located") |
| 526 |
# Search for the network key of the same network name, that resides in a cluster parameter |
| 527 |
for network in networks: |
| 528 |
if self.params['cluster']: |
| 529 |
if network in cluster.network: |
| 530 |
network_mapping = vim.OvfManager.NetworkMapping() |
| 531 |
network_mapping.name = key |
| 532 |
network_mapping.network = network |
| 533 |
self.network_mappings.append(network_mapping) |
| 534 |
else: |
| 535 |
network_mapping = vim.OvfManager.NetworkMapping() |
| 536 |
network_mapping.name = key |
| 537 |
network_mapping.network = network |
| 538 |
self.network_mappings.append(network_mapping) |
| 539 |
return self.datastore, self.datacenter, self.resource_pool, self.network_mappings |
| 540 |
|
| 541 |
def get_ovf_descriptor(self): |
| 542 |
if self.params['url'] is None: |
| 543 |
# Check whether ovf/ova file exists |
| 544 |
try: |
| 545 |
path_exists(self.params['ovf']) |
| 546 |
except ValueError as e: |
| 547 |
self.module.fail_json(msg="%s" % e) |
| 548 |
|
| 549 |
if tarfile.is_tarfile(self.params['ovf']): |
| 550 |
self.tar = tarfile.open(self.params['ovf']) |
| 551 |
ovf = None |
| 552 |
for candidate in self.tar.getmembers(): |
| 553 |
dummy, ext = os.path.splitext(candidate.name) |
| 554 |
if ext.lower() == '.ovf': |
| 555 |
ovf = candidate |
| 556 |
break |
| 557 |
if not ovf: |
| 558 |
self.module.fail_json(msg='Could not locate OVF file in %(ovf)s' % self.params) |
| 559 |
|
| 560 |
self.ovf_descriptor = to_native(self.tar.extractfile(ovf).read()) |
| 561 |
else: |
| 562 |
with open(self.params['ovf'], encoding="utf-8") as f: |
| 563 |
self.ovf_descriptor = f.read() |
| 564 |
|
| 565 |
return self.ovf_descriptor |
| 566 |
else: |
| 567 |
self.handle = WebHandle(self.params['url']) |
| 568 |
self.tar = tarfile.open(fileobj=self.handle) |
| 569 |
ovffilename = list( |
| 570 |
filter(lambda x: x.endswith('.ovf'), self.tar.getnames()))[0] |
| 571 |
ovffile = self.tar.extractfile(ovffilename) |
| 572 |
self.ovf_descriptor = ovffile.read().decode() |
| 573 |
|
| 574 |
if self.ovf_descriptor: |
| 575 |
return self.ovf_descriptor |
| 576 |
else: |
| 577 |
self.module.fail_json( |
| 578 |
msg='Could not locate OVF file in %(url)s' % self.params) |
| 579 |
|
| 580 |
def get_lease(self): |
| 581 |
datastore, datacenter, resource_pool, network_mappings = self.get_objects() |
| 582 |
|
| 583 |
params = { |
| 584 |
'diskProvisioning': self.params['disk_provisioning'], |
| 585 |
} |
| 586 |
if self.params['name']: |
| 587 |
params['entityName'] = self.params['name'] |
| 588 |
if network_mappings: |
| 589 |
params['networkMapping'] = network_mappings |
| 590 |
if self.params['deployment_option']: |
| 591 |
params['deploymentOption'] = self.params['deployment_option'] |
| 592 |
if self.params['properties']: |
| 593 |
params['propertyMapping'] = [] |
| 594 |
for key, value in self.params['properties'].items(): |
| 595 |
property_mapping = vim.KeyValue() |
| 596 |
property_mapping.key = key |
| 597 |
property_mapping.value = str(value) if isinstance(value, bool) else value |
| 598 |
params['propertyMapping'].append(property_mapping) |
| 599 |
|
| 600 |
if self.params['folder']: |
| 601 |
folder = self.content.searchIndex.FindByInventoryPath(self.params['folder']) |
| 602 |
if not folder: |
| 603 |
self.module.fail_json(msg=f"Unable to find the specified folder {self.params['folder']}") |
| 604 |
else: |
| 605 |
folder = datacenter.vmFolder |
| 606 |
|
| 607 |
spec_params = vim.OvfManager.CreateImportSpecParams(**params) |
| 608 |
|
| 609 |
ovf_descriptor = self.get_ovf_descriptor() |
| 610 |
|
| 611 |
self.import_spec = self.content.ovfManager.CreateImportSpec( |
| 612 |
ovf_descriptor, |
| 613 |
resource_pool, |
| 614 |
datastore, |
| 615 |
spec_params |
| 616 |
) |
| 617 |
|
| 618 |
if self.params['enable_hidden_properties']: |
| 619 |
for prop in self.import_spec.importSpec.configSpec.vAppConfig.property: |
| 620 |
prop.info.userConfigurable = True |
| 621 |
|
| 622 |
errors = [to_native(e.msg) for e in getattr(self.import_spec, 'error', [])] |
| 623 |
if self.params['fail_on_spec_warnings']: |
| 624 |
errors.extend( |
| 625 |
(to_native(w.msg) for w in getattr(self.import_spec, 'warning', [])) |
| 626 |
) |
| 627 |
if errors: |
| 628 |
self.module.fail_json( |
| 629 |
msg=f"Failure validating OVF import spec: {'. '.join(errors)}" |
| 630 |
) |
| 631 |
|
| 632 |
for warning in getattr(self.import_spec, 'warning', []): |
| 633 |
self.module.warn(f"Problem validating OVF import spec: {to_native(warning.msg)}") |
| 634 |
|
| 635 |
name = self.params.get('name') |
| 636 |
if not self.params['allow_duplicates']: |
| 637 |
name = self.import_spec.importSpec.configSpec.name |
| 638 |
match = find_vm_by_name(self.content, name, folder=folder) |
| 639 |
if match: |
| 640 |
self.module.exit_json(instance=gather_vm_facts(self.content, match), changed=False) |
| 641 |
|
| 642 |
if self.module.check_mode: |
| 643 |
self.module.exit_json(changed=True, instance={'hw_name': name}) |
| 644 |
|
| 645 |
try: |
| 646 |
self.lease = resource_pool.ImportVApp( |
| 647 |
self.import_spec.importSpec, |
| 648 |
folder |
| 649 |
) |
| 650 |
except vmodl.fault.SystemError as err: |
| 651 |
self.module.fail_json( |
| 652 |
msg=f"Failed to start import: {to_native(err.msg)}" |
| 653 |
) |
| 654 |
|
| 655 |
while self.lease.state != vim.HttpNfcLease.State.ready: |
| 656 |
time.sleep(0.1) |
| 657 |
|
| 658 |
self.entity = self.lease.info.entity |
| 659 |
|
| 660 |
return self.lease, self.import_spec |
| 661 |
|
| 662 |
def _normalize_url(self, url): |
| 663 |
''' |
| 664 |
The hostname in URLs from vmware may be ``*`` update it accordingly |
| 665 |
''' |
| 666 |
url_parts = generic_urlparse(urlparse(url)) |
| 667 |
if url_parts.hostname == '*': |
| 668 |
if url_parts.port: |
| 669 |
url_parts.netloc = '%s:%d' % (self.params['hostname'], url_parts.port) |
| 670 |
else: |
| 671 |
url_parts.netloc = self.params['hostname'] |
| 672 |
|
| 673 |
return urlunparse(url_parts.as_list()) |
| 674 |
|
| 675 |
def vm_existence_check(self): |
| 676 |
vm_obj = self.get_vm() |
| 677 |
if vm_obj: |
| 678 |
self.entity = vm_obj |
| 679 |
facts = self.deploy() |
| 680 |
self.module.exit_json(**facts) |
| 681 |
|
| 682 |
def upload(self): |
| 683 |
if self.params['ovf'] is None: |
| 684 |
# Upload from url |
| 685 |
lease, import_spec = self.get_lease() |
| 686 |
|
| 687 |
ssl_thumbprint = self.handle.thumbprint if self.handle.thumbprint else None |
| 688 |
source_files = [] |
| 689 |
for file_item in import_spec.fileItem: |
| 690 |
source_file = vim.HttpNfcLease.SourceFile( |
| 691 |
url=self.handle.url, |
| 692 |
targetDeviceId=file_item.deviceId, |
| 693 |
create=file_item.create, |
| 694 |
size=file_item.size, |
| 695 |
sslThumbprint=ssl_thumbprint, |
| 696 |
memberName=file_item.path |
| 697 |
) |
| 698 |
source_files.append(source_file) |
| 699 |
|
| 700 |
wait_for_task(lease.HttpNfcLeasePullFromUrls_Task(source_files)) |
| 701 |
else: |
| 702 |
ovf_dir = os.path.dirname(self.params['ovf']) |
| 703 |
|
| 704 |
lease, import_spec = self.get_lease() |
| 705 |
|
| 706 |
uploaders = [] |
| 707 |
|
| 708 |
for file_item in import_spec.fileItem: |
| 709 |
device_upload_url = None |
| 710 |
for device_url in lease.info.deviceUrl: |
| 711 |
if file_item.deviceId == device_url.importKey: |
| 712 |
device_upload_url = self._normalize_url(device_url.url) |
| 713 |
break |
| 714 |
|
| 715 |
if not device_upload_url: |
| 716 |
lease.HttpNfcLeaseAbort( |
| 717 |
vmodl.fault.SystemError(reason=f"Failed to find deviceUrl for file '{file_item.path}'") |
| 718 |
) |
| 719 |
self.module.fail_json( |
| 720 |
msg=f"Failed to find deviceUrl for file '{file_item.path}'" |
| 721 |
) |
| 722 |
|
| 723 |
vmdk_tarinfo = None |
| 724 |
if self.tar: |
| 725 |
vmdk = self.tar |
| 726 |
try: |
| 727 |
vmdk_tarinfo = self.tar.getmember(file_item.path) |
| 728 |
except KeyError: |
| 729 |
lease.HttpNfcLeaseAbort( |
| 730 |
vmodl.fault.SystemError(reason=f"Failed to find VMDK file '{file_item.path}' in OVA") |
| 731 |
) |
| 732 |
self.module.fail_json( |
| 733 |
msg=f"Failed to find VMDK file '{file_item.path}' in OVA" |
| 734 |
) |
| 735 |
else: |
| 736 |
vmdk = os.path.join(ovf_dir, file_item.path) |
| 737 |
try: |
| 738 |
path_exists(vmdk) |
| 739 |
except ValueError: |
| 740 |
lease.HttpNfcLeaseAbort( |
| 741 |
vmodl.fault.SystemError(reason=f"Failed to find VMDK file at '{vmdk}'") |
| 742 |
) |
| 743 |
self.module.fail_json( |
| 744 |
msg=f"Failed to find VMDK file at '{vmdk}'" |
| 745 |
) |
| 746 |
|
| 747 |
uploaders.append( |
| 748 |
VMDKUploader( |
| 749 |
vmdk, |
| 750 |
device_upload_url, |
| 751 |
self.params['validate_certs'], |
| 752 |
tarinfo=vmdk_tarinfo, |
| 753 |
create=file_item.create |
| 754 |
) |
| 755 |
) |
| 756 |
|
| 757 |
total_size = sum(u.size for u in uploaders) |
| 758 |
total_bytes_read = [0] * len(uploaders) |
| 759 |
for i, uploader in enumerate(uploaders): |
| 760 |
uploader.start() |
| 761 |
while uploader.is_alive(): |
| 762 |
time.sleep(0.1) |
| 763 |
total_bytes_read[i] = uploader.bytes_read |
| 764 |
lease.HttpNfcLeaseProgress(int(100.0 * sum(total_bytes_read) / total_size)) |
| 765 |
|
| 766 |
if uploader.e: |
| 767 |
lease.HttpNfcLeaseAbort( |
| 768 |
vmodl.fault.SystemError(reason='%s' % to_native(uploader.e[1])) |
| 769 |
) |
| 770 |
self.module.fail_json( |
| 771 |
msg='%s' % to_native(uploader.e[1]), |
| 772 |
exception=''.join(traceback.format_tb(uploader.e[2])) |
| 773 |
) |
| 774 |
|
| 775 |
def complete(self): |
| 776 |
self.lease.HttpNfcLeaseComplete() |
| 777 |
|
| 778 |
def inject_ovf_env(self): |
| 779 |
attrib = { |
| 780 |
'xmlns': 'http://schemas.dmtf.org/ovf/environment/1', |
| 781 |
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', |
| 782 |
'xmlns:oe': 'http://schemas.dmtf.org/ovf/environment/1', |
| 783 |
'xmlns:ve': 'http://www.vmware.com/schema/ovfenv', |
| 784 |
'oe:id': '', |
| 785 |
've:esxId': self.entity._moId |
| 786 |
} |
| 787 |
env = ET.Element('Environment', **attrib) |
| 788 |
|
| 789 |
platform = ET.SubElement(env, 'PlatformSection') |
| 790 |
ET.SubElement(platform, 'Kind').text = self.content.about.name |
| 791 |
ET.SubElement(platform, 'Version').text = self.content.about.version |
| 792 |
ET.SubElement(platform, 'Vendor').text = self.content.about.vendor |
| 793 |
ET.SubElement(platform, 'Locale').text = 'US' |
| 794 |
|
| 795 |
prop_section = ET.SubElement(env, 'PropertySection') |
| 796 |
for key, value in self.params['properties'].items(): |
| 797 |
params = { |
| 798 |
'oe:key': key, |
| 799 |
'oe:value': str(value) if isinstance(value, bool) else value |
| 800 |
} |
| 801 |
ET.SubElement(prop_section, 'Property', **params) |
| 802 |
|
| 803 |
opt = vim.option.OptionValue() |
| 804 |
opt.key = 'guestinfo.ovfEnv' |
| 805 |
opt.value = '<?xml version="1.0" encoding="UTF-8"?>' + to_native(ET.tostring(env)) |
| 806 |
|
| 807 |
config_spec = vim.vm.ConfigSpec() |
| 808 |
config_spec.extraConfig = [opt] |
| 809 |
|
| 810 |
task = self.entity.ReconfigVM_Task(config_spec) |
| 811 |
wait_for_task(task) |
| 812 |
|
| 813 |
def deploy(self): |
| 814 |
facts = {} |
| 815 |
|
| 816 |
if self.params['power_on']: |
| 817 |
facts = set_vm_power_state(self.content, self.entity, 'poweredon', force=False) |
| 818 |
if self.params['wait_for_ip_address']: |
| 819 |
_facts = wait_for_vm_ip(self.content, self.entity) |
| 820 |
if not _facts: |
| 821 |
self.module.fail_json(msg='Waiting for IP address timed out') |
| 822 |
|
| 823 |
if not facts: |
| 824 |
facts.update(dict(instance=gather_vm_facts(self.content, self.entity))) |
| 825 |
|
| 826 |
return facts |
| 827 |
|
| 828 |
|
| 829 |
def main(): |
| 830 |
argument_spec = base_argument_spec() |
| 831 |
argument_spec.update({ |
| 832 |
'name': {}, |
| 833 |
'datastore': { |
| 834 |
'default': 'datastore1', |
| 835 |
}, |
| 836 |
'datacenter': { |
| 837 |
'default': 'ha-datacenter', |
| 838 |
}, |
| 839 |
'cluster': { |
| 840 |
'default': None, |
| 841 |
}, |
| 842 |
'esxi_hostname': { |
| 843 |
'default': None, |
| 844 |
}, |
| 845 |
'deployment_option': { |
| 846 |
'default': None, |
| 847 |
}, |
| 848 |
'folder': { |
| 849 |
'default': None, |
| 850 |
}, |
| 851 |
'inject_ovf_env': { |
| 852 |
'default': False, |
| 853 |
'type': 'bool', |
| 854 |
}, |
| 855 |
'resource_pool': { |
| 856 |
'default': 'Resources', |
| 857 |
}, |
| 858 |
'networks': { |
| 859 |
'default': { |
| 860 |
'VM Network': 'VM Network', |
| 861 |
}, |
| 862 |
'type': 'dict', |
| 863 |
}, |
| 864 |
'ovf': { |
| 865 |
'type': 'path', |
| 866 |
'aliases': ['ova'], |
| 867 |
}, |
| 868 |
'url': { |
| 869 |
'type': 'str', |
| 870 |
}, |
| 871 |
'disk_provisioning': { |
| 872 |
'choices': [ |
| 873 |
'flat', |
| 874 |
'eagerZeroedThick', |
| 875 |
'monolithicSparse', |
| 876 |
'twoGbMaxExtentSparse', |
| 877 |
'twoGbMaxExtentFlat', |
| 878 |
'thin', |
| 879 |
'sparse', |
| 880 |
'thick', |
| 881 |
'seSparse', |
| 882 |
'monolithicFlat' |
| 883 |
], |
| 884 |
'default': 'thin', |
| 885 |
}, |
| 886 |
'enable_hidden_properties': { |
| 887 |
'default': False, |
| 888 |
'type': 'bool', |
| 889 |
}, |
| 890 |
'power_on': { |
| 891 |
'type': 'bool', |
| 892 |
'default': True, |
| 893 |
}, |
| 894 |
'properties': { |
| 895 |
'type': 'dict', |
| 896 |
}, |
| 897 |
'wait': { |
| 898 |
'type': 'bool', |
| 899 |
'default': True, |
| 900 |
}, |
| 901 |
'wait_for_ip_address': { |
| 902 |
'type': 'bool', |
| 903 |
'default': False, |
| 904 |
}, |
| 905 |
'allow_duplicates': { |
| 906 |
'type': 'bool', |
| 907 |
'default': True, |
| 908 |
}, |
| 909 |
'fail_on_spec_warnings': { |
| 910 |
'type': 'bool', |
| 911 |
'default': False, |
| 912 |
}, |
| 913 |
}) |
| 914 |
module = AnsibleModule( |
| 915 |
argument_spec=argument_spec, |
| 916 |
supports_check_mode=True, |
| 917 |
required_one_of=[ |
| 918 |
['ovf', 'url'], |
| 919 |
], |
| 920 |
mutually_exclusive=[ |
| 921 |
['cluster', 'esxi_hostname'], |
| 922 |
['ovf', 'url'], |
| 923 |
], |
| 924 |
) |
| 925 |
|
| 926 |
deploy_ovf = VMwareDeployOvf(module) |
| 927 |
deploy_ovf.vm_existence_check() |
| 928 |
deploy_ovf.upload() |
| 929 |
deploy_ovf.complete() |
| 930 |
|
| 931 |
if module.params['inject_ovf_env']: |
| 932 |
deploy_ovf.inject_ovf_env() |
| 933 |
|
| 934 |
facts = deploy_ovf.deploy() |
| 935 |
facts.update(changed=True) |
| 936 |
module.exit_json(**facts) |
| 937 |
|
| 938 |
|
| 939 |
if __name__ == '__main__': |
| 940 |
main() |