| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2018, Ansible Project |
| 5 |
# Copyright: (c) 2018, Diane Wang <[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 |
--- |
| 15 |
module: vmware_export_ovf |
| 16 |
short_description: Exports a VMware virtual machine to an OVF file, device files and a manifest file |
| 17 |
description: > |
| 18 |
This module can be used to export a VMware virtual machine to OVF template from vCenter server or ESXi host. |
| 19 |
author: |
| 20 |
- Diane Wang (@Tomorrow9) <[email protected]> |
| 21 |
notes: [] |
| 22 |
options: |
| 23 |
name: |
| 24 |
description: |
| 25 |
- Name of the virtual machine to export. |
| 26 |
- This is a required parameter, if parameter O(uuid) or O(moid) is not supplied. |
| 27 |
type: str |
| 28 |
uuid: |
| 29 |
description: |
| 30 |
- Uuid of the virtual machine to export. |
| 31 |
- This is a required parameter, if parameter O(name) or O(moid) is not supplied. |
| 32 |
type: str |
| 33 |
moid: |
| 34 |
description: |
| 35 |
- Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance. |
| 36 |
- This is required if O(name) or O(uuid) is not supplied. |
| 37 |
type: str |
| 38 |
datacenter: |
| 39 |
default: ha-datacenter |
| 40 |
description: |
| 41 |
- Datacenter name of the virtual machine to export. |
| 42 |
type: str |
| 43 |
folder: |
| 44 |
description: |
| 45 |
- Destination folder, absolute path to find the specified guest. |
| 46 |
- The folder should include the datacenter. ESX datacenter is ha-datacenter. |
| 47 |
- 'If multiple machines are found with same name, this parameter is used to identify' |
| 48 |
- 'Examples:' |
| 49 |
- ' folder: /ha-datacenter/vm' |
| 50 |
- ' folder: ha-datacenter/vm' |
| 51 |
- ' folder: /datacenter1/vm' |
| 52 |
- ' folder: datacenter1/vm' |
| 53 |
- ' folder: /datacenter1/vm/folder1' |
| 54 |
- ' folder: datacenter1/vm/folder1' |
| 55 |
- ' folder: /folder1/datacenter1/vm' |
| 56 |
- ' folder: folder1/datacenter1/vm' |
| 57 |
- ' folder: /folder1/datacenter1/vm/folder2' |
| 58 |
type: str |
| 59 |
export_dir: |
| 60 |
description: |
| 61 |
- Absolute path to place the exported files on the server running this task, must have write permission. |
| 62 |
- If folder not exist will create it, also create a folder under this path named with VM name. |
| 63 |
required: true |
| 64 |
type: path |
| 65 |
export_with_images: |
| 66 |
default: false |
| 67 |
description: |
| 68 |
- Export an ISO image of the media mounted on the CD/DVD Drive within the virtual machine. |
| 69 |
type: bool |
| 70 |
export_with_extraconfig: |
| 71 |
type: bool |
| 72 |
default: false |
| 73 |
description: |
| 74 |
- All extra configuration options are exported for a virtual machine. |
| 75 |
download_timeout: |
| 76 |
description: |
| 77 |
- The user defined timeout in second of exporting file. |
| 78 |
- If the vmdk file is too large, you can increase the value. |
| 79 |
default: 30 |
| 80 |
type: int |
| 81 |
extends_documentation_fragment: |
| 82 |
- vmware.vmware.base_options |
| 83 |
|
| 84 |
''' |
| 85 |
|
| 86 |
EXAMPLES = r''' |
| 87 |
- community.vmware.vmware_export_ovf: |
| 88 |
hostname: '{{ vcenter_hostname }}' |
| 89 |
username: '{{ vcenter_username }}' |
| 90 |
password: '{{ vcenter_password }}' |
| 91 |
name: '{{ vm_name }}' |
| 92 |
export_with_images: true |
| 93 |
export_dir: /path/to/ovf_template/ |
| 94 |
delegate_to: localhost |
| 95 |
''' |
| 96 |
|
| 97 |
RETURN = r''' |
| 98 |
instance: |
| 99 |
description: list of the exported files, if exported from vCenter server, device file is not named with vm name |
| 100 |
returned: always |
| 101 |
type: dict |
| 102 |
sample: None |
| 103 |
''' |
| 104 |
|
| 105 |
import os |
| 106 |
import hashlib |
| 107 |
from time import sleep |
| 108 |
from threading import Thread |
| 109 |
from ansible.module_utils.urls import open_url |
| 110 |
from ansible.module_utils.basic import AnsibleModule |
| 111 |
from ansible.module_utils.common.text.converters import to_text, to_bytes |
| 112 |
from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi |
| 113 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec |
| 114 |
try: |
| 115 |
from pyVmomi import vim |
| 116 |
from pyVim import connect |
| 117 |
except ImportError: |
| 118 |
pass |
| 119 |
|
| 120 |
|
| 121 |
class LeaseProgressUpdater(Thread): |
| 122 |
def __init__(self, http_nfc_lease, update_interval): |
| 123 |
Thread.__init__(self) |
| 124 |
self._running = True |
| 125 |
self.httpNfcLease = http_nfc_lease |
| 126 |
self.updateInterval = update_interval |
| 127 |
self.progressPercent = 0 |
| 128 |
|
| 129 |
def set_progress_percent(self, progress_percent): |
| 130 |
self.progressPercent = progress_percent |
| 131 |
|
| 132 |
def stop(self): |
| 133 |
self._running = False |
| 134 |
|
| 135 |
def run(self): |
| 136 |
while self._running: |
| 137 |
try: |
| 138 |
if self.httpNfcLease.state == vim.HttpNfcLease.State.done: |
| 139 |
return |
| 140 |
self.httpNfcLease.HttpNfcLeaseProgress(self.progressPercent) |
| 141 |
sleep_sec = 0 |
| 142 |
while True: |
| 143 |
if self.httpNfcLease.state == vim.HttpNfcLease.State.done or self.httpNfcLease.state == vim.HttpNfcLease.State.error: |
| 144 |
return |
| 145 |
sleep_sec += 1 |
| 146 |
sleep(1) |
| 147 |
if sleep_sec == self.updateInterval: |
| 148 |
break |
| 149 |
except Exception: |
| 150 |
return |
| 151 |
|
| 152 |
|
| 153 |
class VMwareExportVmOvf(PyVmomi): |
| 154 |
def __init__(self, module): |
| 155 |
super(VMwareExportVmOvf, self).__init__(module) |
| 156 |
self.mf_file = '' |
| 157 |
self.ovf_dir = '' |
| 158 |
# set read device content chunk size to 2 MB |
| 159 |
self.chunk_size = 2 * 2 ** 20 |
| 160 |
# set lease progress update interval to 15 seconds |
| 161 |
self.lease_interval = 15 |
| 162 |
self.facts = {'device_files': []} |
| 163 |
self.download_timeout = None |
| 164 |
|
| 165 |
def create_export_dir(self, vm_obj): |
| 166 |
self.ovf_dir = os.path.join(self.params['export_dir'], vm_obj.name) |
| 167 |
if not os.path.exists(self.ovf_dir): |
| 168 |
try: |
| 169 |
os.makedirs(self.ovf_dir) |
| 170 |
except OSError as err: |
| 171 |
self.module.fail_json(msg='Exception caught when create folder %s, with error %s' |
| 172 |
% (self.ovf_dir, to_text(err))) |
| 173 |
self.mf_file = os.path.join(self.ovf_dir, vm_obj.name + '.mf') |
| 174 |
|
| 175 |
def download_device_files(self, headers, temp_target_disk, device_url, lease_updater, total_bytes_written, |
| 176 |
total_bytes_to_write): |
| 177 |
mf_content = 'SHA256(' + os.path.basename(temp_target_disk) + ')= ' |
| 178 |
sha256_hash = hashlib.sha256() |
| 179 |
response = None |
| 180 |
|
| 181 |
with open(self.mf_file, 'a') as mf_handle: |
| 182 |
with open(temp_target_disk, 'wb') as handle: |
| 183 |
try: |
| 184 |
response = open_url(device_url, headers=headers, validate_certs=False, timeout=self.download_timeout) |
| 185 |
except Exception as err: |
| 186 |
lease_updater.httpNfcLease.HttpNfcLeaseAbort() |
| 187 |
lease_updater.stop() |
| 188 |
self.module.fail_json(msg='Exception caught when getting %s, %s' % (device_url, to_text(err))) |
| 189 |
if not response: |
| 190 |
lease_updater.httpNfcLease.HttpNfcLeaseAbort() |
| 191 |
lease_updater.stop() |
| 192 |
self.module.fail_json(msg='Getting %s failed' % device_url) |
| 193 |
if response.getcode() >= 400: |
| 194 |
lease_updater.httpNfcLease.HttpNfcLeaseAbort() |
| 195 |
lease_updater.stop() |
| 196 |
self.module.fail_json(msg='Getting %s return code %d' % (device_url, response.getcode())) |
| 197 |
current_bytes_written = 0 |
| 198 |
block = response.read(self.chunk_size) |
| 199 |
while block: |
| 200 |
handle.write(block) |
| 201 |
sha256_hash.update(block) |
| 202 |
handle.flush() |
| 203 |
os.fsync(handle.fileno()) |
| 204 |
current_bytes_written += len(block) |
| 205 |
block = response.read(self.chunk_size) |
| 206 |
written_percent = ((current_bytes_written + total_bytes_written) * 100) / total_bytes_to_write |
| 207 |
lease_updater.progressPercent = int(written_percent) |
| 208 |
mf_handle.write(mf_content + sha256_hash.hexdigest() + '\n') |
| 209 |
self.facts['device_files'].append(temp_target_disk) |
| 210 |
return current_bytes_written |
| 211 |
|
| 212 |
def export_to_ovf_files(self, vm_obj): |
| 213 |
self.create_export_dir(vm_obj=vm_obj) |
| 214 |
export_with_iso = False |
| 215 |
if self.params['export_with_images']: |
| 216 |
export_with_iso = True |
| 217 |
self.download_timeout = self.params['download_timeout'] |
| 218 |
|
| 219 |
ovf_files = [] |
| 220 |
# get http nfc lease firstly |
| 221 |
http_nfc_lease = vm_obj.ExportVm() |
| 222 |
# create a thread to track file download progress |
| 223 |
lease_updater = LeaseProgressUpdater(http_nfc_lease, self.lease_interval) |
| 224 |
total_bytes_written = 0 |
| 225 |
# total storage space occupied by the virtual machine across all datastores |
| 226 |
total_bytes_to_write = vm_obj.summary.storage.unshared |
| 227 |
# new deployed VM with no OS installed |
| 228 |
if total_bytes_to_write == 0: |
| 229 |
total_bytes_to_write = vm_obj.summary.storage.committed |
| 230 |
if total_bytes_to_write == 0: |
| 231 |
http_nfc_lease.HttpNfcLeaseAbort() |
| 232 |
self.module.fail_json(msg='Total storage space occupied by the VM is 0.') |
| 233 |
headers = {'Accept': 'application/x-vnd.vmware-streamVmdk'} |
| 234 |
cookies = connect.GetStub().cookie |
| 235 |
if cookies: |
| 236 |
headers['Cookie'] = cookies |
| 237 |
lease_updater.start() |
| 238 |
try: |
| 239 |
while True: |
| 240 |
if http_nfc_lease.state == vim.HttpNfcLease.State.ready: |
| 241 |
for deviceUrl in http_nfc_lease.info.deviceUrl: |
| 242 |
file_download = False |
| 243 |
if deviceUrl.targetId and deviceUrl.disk: |
| 244 |
file_download = True |
| 245 |
elif deviceUrl.url.split('/')[-1].split('.')[-1] == 'iso': |
| 246 |
if export_with_iso: |
| 247 |
file_download = True |
| 248 |
elif deviceUrl.url.split('/')[-1].split('.')[-1] == 'nvram': |
| 249 |
if self.host_version_at_least(version=(6, 7, 0), vm_obj=vm_obj): |
| 250 |
file_download = True |
| 251 |
else: |
| 252 |
continue |
| 253 |
device_file_name = deviceUrl.url.split('/')[-1] |
| 254 |
# device file named disk-0.iso, disk-1.vmdk, disk-2.vmdk, replace 'disk' with vm name |
| 255 |
if device_file_name.split('.')[0][0:5] == "disk-": |
| 256 |
device_file_name = device_file_name.replace('disk', vm_obj.name) |
| 257 |
temp_target_disk = os.path.join(self.ovf_dir, device_file_name) |
| 258 |
device_url = deviceUrl.url |
| 259 |
# if export from ESXi host, replace * with hostname in url |
| 260 |
# e.g., https://*/ha-nfc/5289bf27-da99-7c0e-3978-8853555deb8c/disk-1.vmdk |
| 261 |
if '*' in device_url: |
| 262 |
device_url = device_url.replace('*', self.params['hostname']) |
| 263 |
if file_download: |
| 264 |
current_bytes_written = self.download_device_files(headers=headers, |
| 265 |
temp_target_disk=temp_target_disk, |
| 266 |
device_url=device_url, |
| 267 |
lease_updater=lease_updater, |
| 268 |
total_bytes_written=total_bytes_written, |
| 269 |
total_bytes_to_write=total_bytes_to_write) |
| 270 |
total_bytes_written += current_bytes_written |
| 271 |
ovf_file = vim.OvfManager.OvfFile() |
| 272 |
ovf_file.deviceId = deviceUrl.key |
| 273 |
ovf_file.path = device_file_name |
| 274 |
ovf_file.size = current_bytes_written |
| 275 |
ovf_files.append(ovf_file) |
| 276 |
break |
| 277 |
if http_nfc_lease.state == vim.HttpNfcLease.State.initializing: |
| 278 |
sleep(2) |
| 279 |
continue |
| 280 |
if http_nfc_lease.state == vim.HttpNfcLease.State.error: |
| 281 |
lease_updater.stop() |
| 282 |
self.module.fail_json(msg='Get HTTP NFC lease error %s.' % http_nfc_lease.state.error[0].fault) |
| 283 |
|
| 284 |
# generate ovf file |
| 285 |
ovf_manager = self.content.ovfManager |
| 286 |
ovf_descriptor_name = vm_obj.name |
| 287 |
ovf_parameters = vim.OvfManager.CreateDescriptorParams() |
| 288 |
ovf_parameters.name = ovf_descriptor_name |
| 289 |
ovf_parameters.ovfFiles = ovf_files |
| 290 |
if self.params['export_with_extraconfig']: |
| 291 |
ovf_parameters.exportOption = ['extraconfig'] |
| 292 |
if self.params['export_with_images']: |
| 293 |
ovf_parameters.includeImageFiles = True |
| 294 |
vm_descriptor_result = ovf_manager.CreateDescriptor(obj=vm_obj, cdp=ovf_parameters) |
| 295 |
if vm_descriptor_result.error: |
| 296 |
http_nfc_lease.HttpNfcLeaseAbort() |
| 297 |
lease_updater.stop() |
| 298 |
self.module.fail_json(msg='Create VM descriptor file error %s.' % vm_descriptor_result.error) |
| 299 |
else: |
| 300 |
vm_descriptor = vm_descriptor_result.ovfDescriptor |
| 301 |
ovf_descriptor_path = os.path.join(self.ovf_dir, ovf_descriptor_name + '.ovf') |
| 302 |
sha256_hash = hashlib.sha256() |
| 303 |
with open(self.mf_file, 'a') as mf_handle: |
| 304 |
with open(ovf_descriptor_path, 'w') as handle: |
| 305 |
handle.write(vm_descriptor) |
| 306 |
sha256_hash.update(to_bytes(vm_descriptor)) |
| 307 |
mf_handle.write('SHA256(' + os.path.basename(ovf_descriptor_path) + ')= ' + sha256_hash.hexdigest() + '\n') |
| 308 |
http_nfc_lease.HttpNfcLeaseProgress(100) |
| 309 |
# self.facts = http_nfc_lease.HttpNfcLeaseGetManifest() |
| 310 |
http_nfc_lease.HttpNfcLeaseComplete() |
| 311 |
lease_updater.stop() |
| 312 |
self.facts.update({'manifest': self.mf_file, 'ovf_file': ovf_descriptor_path}) |
| 313 |
except Exception as err: |
| 314 |
kwargs = { |
| 315 |
'changed': False, |
| 316 |
'failed': True, |
| 317 |
'msg': "get exception: %s" % to_text(err), |
| 318 |
} |
| 319 |
http_nfc_lease.HttpNfcLeaseAbort() |
| 320 |
lease_updater.stop() |
| 321 |
return kwargs |
| 322 |
return {'changed': True, 'failed': False, 'instance': self.facts} |
| 323 |
|
| 324 |
|
| 325 |
def main(): |
| 326 |
argument_spec = base_argument_spec() |
| 327 |
argument_spec.update( |
| 328 |
name=dict(type='str'), |
| 329 |
uuid=dict(type='str'), |
| 330 |
moid=dict(type='str'), |
| 331 |
folder=dict(type='str'), |
| 332 |
datacenter=dict(type='str', default='ha-datacenter'), |
| 333 |
export_dir=dict(type='path', required=True), |
| 334 |
export_with_images=dict(type='bool', default=False), |
| 335 |
export_with_extraconfig=dict(type='bool', default=False), |
| 336 |
download_timeout=dict(type='int', default=30), |
| 337 |
) |
| 338 |
|
| 339 |
module = AnsibleModule(argument_spec=argument_spec, |
| 340 |
supports_check_mode=True, |
| 341 |
required_one_of=[ |
| 342 |
['name', 'uuid', 'moid'], |
| 343 |
], |
| 344 |
) |
| 345 |
pyv = VMwareExportVmOvf(module) |
| 346 |
vm = pyv.get_vm() |
| 347 |
if vm: |
| 348 |
vm_facts = pyv.gather_facts(vm) |
| 349 |
vm_power_state = vm_facts['hw_power_status'].lower() |
| 350 |
if vm_power_state != 'poweredoff': |
| 351 |
module.fail_json(msg='VM state should be poweredoff to export') |
| 352 |
results = pyv.export_to_ovf_files(vm_obj=vm) |
| 353 |
module.exit_json(**results) |
| 354 |
else: |
| 355 |
module.fail_json(msg='The specified virtual machine not found') |
| 356 |
|
| 357 |
|
| 358 |
if __name__ == '__main__': |
| 359 |
main() |