Debian Codegraph @

ansible_collections/community/vmware/plugins/modules/vmware_vmotion.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2015, Bede Carroll <bc+github () bedecarroll.com>
5 # Copyright: (c) 2018, Abhijeet Kasurde <[email protected]>
6 # Copyright: (c) 2018, Ansible Project
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import absolute_import, division, print_function
11 __metaclass__ = type
12
13
14 DOCUMENTATION = r'''
15 ---
16 module: vmware_vmotion
17 short_description: Move a virtual machine using vMotion, and/or its vmdks using storage vMotion.
18 description:
19 - Using VMware vCenter, move a virtual machine using vMotion to a different
20 host, and/or its vmdks to another datastore using storage vMotion.
21 author:
22 - Bede Carroll (@bedecarroll)
23 - Olivier Boukili (@oboukili)
24 options:
25 vm_name:
26 description:
27 - Name of the VM to perform a vMotion on.
28 - This is required parameter, if O(vm_uuid) is not set.
29 aliases: ['vm']
30 type: str
31 vm_uuid:
32 description:
33 - UUID of the virtual machine to perform a vMotion operation on.
34 - This is a required parameter, if O(vm_name) or O(moid) is not set.
35 aliases: ['uuid']
36 type: str
37 moid:
38 description:
39 - Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance.
40 - This is required if O(vm_name) or O(vm_uuid) is not supplied.
41 type: str
42 use_instance_uuid:
43 description:
44 - Whether to use the VMware instance UUID rather than the BIOS UUID.
45 default: false
46 type: bool
47 destination_host:
48 description:
49 - Name of the destination host the virtual machine should be running on.
50 - Version 2.6 onwards, this parameter is not a required parameter, unlike the previous versions.
51 aliases: ['destination']
52 type: str
53 destination_cluster:
54 description:
55 - Name of the destination cluster the virtual machine should be running on.
56 - Only works if drs is enabled for this cluster.
57 type: str
58 destination_datastore_cluster:
59 description:
60 - Name of the destination datastore cluster (storage pod) the virtual machine's vmdk should be moved on.
61 - Only works if drs is enabled for the cluster the vm is running / should run.
62 type: str
63 destination_datastore:
64 description:
65 - Name of the destination datastore the virtual machine's vmdk should be moved on.
66 aliases: ['datastore']
67 type: str
68 destination_datacenter:
69 description:
70 - Name of the destination datacenter the datastore is located on.
71 - Optional, required only when datastores are shared across datacenters.
72 type: str
73 destination_resourcepool:
74 description:
75 - Name of the destination resource pool where the virtual machine should be running.
76 - Resource pool is required if vmotion is done between hosts which are part of different clusters or datacenters.
77 - if not passed, resource_pool object will be retrived from host_obj parent.
78 aliases: ['resource_pool']
79 type: str
80 timeout:
81 description:
82 - The timeout in seconds. When the timeout is reached, the module will fail.
83 type: int
84 default: 3600
85 version_added: '3.4.0'
86 extends_documentation_fragment:
87 - vmware.vmware.base_options
88
89 '''
90
91 EXAMPLES = r'''
92 - name: Perform vMotion of virtual machine
93 community.vmware.vmware_vmotion:
94 hostname: '{{ vcenter_hostname }}'
95 username: '{{ vcenter_username }}'
96 password: '{{ vcenter_password }}'
97 vm_name: 'vm_name_as_per_vcenter'
98 destination_host: 'destination_host_as_per_vcenter'
99 delegate_to: localhost
100
101 - name: Perform vMotion of virtual machine
102 community.vmware.vmware_vmotion:
103 hostname: '{{ vcenter_hostname }}'
104 username: '{{ vcenter_username }}'
105 password: '{{ vcenter_password }}'
106 moid: vm-42
107 destination_host: 'destination_host_as_per_vcenter'
108 delegate_to: localhost
109
110 - name: Perform vMotion of virtual machine to resource_pool
111 community.vmware.vmware_vmotion:
112 hostname: '{{ vcenter_hostname }}'
113 username: '{{ vcenter_username }}'
114 password: '{{ vcenter_password }}'
115 moid: vm-42
116 destination_host: 'destination_host_as_per_vcenter'
117 destination_resourcepool: 'destination_resourcepool_as_per_vcenter'
118 delegate_to: localhost
119
120 - name: Perform storage vMotion of virtual machine
121 community.vmware.vmware_vmotion:
122 hostname: '{{ vcenter_hostname }}'
123 username: '{{ vcenter_username }}'
124 password: '{{ vcenter_password }}'
125 vm_name: 'vm_name_as_per_vcenter'
126 destination_datastore: 'destination_datastore_as_per_vcenter'
127 delegate_to: localhost
128
129 - name: Perform storage vMotion and host vMotion of virtual machine
130 community.vmware.vmware_vmotion:
131 hostname: '{{ vcenter_hostname }}'
132 username: '{{ vcenter_username }}'
133 password: '{{ vcenter_password }}'
134 vm_name: 'vm_name_as_per_vcenter'
135 destination_host: 'destination_host_as_per_vcenter'
136 destination_datastore: 'destination_datastore_as_per_vcenter'
137 delegate_to: localhost
138
139 - name: Perform storage vMotion to a Storage Cluster and vMotion to a Cluster of virtual machine
140 community.vmware.vmware_vmotion:
141 hostname: '{{ vcenter_hostname }}'
142 username: '{{ vcenter_username }}'
143 password: '{{ vcenter_password }}'
144 vm_name: 'vm_name_as_per_vcenter'
145 destination_cluster: 'destination_cluster_as_per_vcenter'
146 destination_datastore_cluster: 'destination_datastore_cluster_as_per_vcenter'
147 delegate_to: localhost
148 '''
149
150 RETURN = r'''
151 running_host:
152 description:
153 - List the host the virtual machine is registered to.
154 - Only returned if there is asked for a vMotion (Cluster or Host).
155 returned: changed or success
156 type: str
157 sample: 'host1.example.com'
158 datastore:
159 description:
160 - List the datastore the virtual machine is on.
161 - Only returned if there is asked for a Storage vMotion (Datastore or Datastore Cluster).
162 returned: changed or success
163 type: str
164 sample: 'datastore1'
165 '''
166
167 try:
168 from pyVmomi import vim, VmomiJSONEncoder
169 except ImportError:
170 pass
171
172 from ansible.module_utils.common.text.converters import to_native
173 from ansible.module_utils.basic import AnsibleModule
174 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
175 PyVmomi, find_hostsystem_by_name,
176 find_vm_by_id, find_datastore_by_name,
177 find_resource_pool_by_cluster,
178 find_datacenter_by_name,
179 find_cluster_by_name, get_all_objs,
180 wait_for_task, TaskError)
181 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
182
183
184 class VmotionManager(PyVmomi):
185 def __init__(self, module):
186 super(VmotionManager, self).__init__(module)
187 self.vm = None
188 self.vm_uuid = self.params.get('vm_uuid', None)
189 self.use_instance_uuid = self.params.get('use_instance_uuid', False)
190 self.vm_name = self.params.get('vm_name', None)
191 self.moid = self.params.get('moid') or None
192 self.destination_datacenter = self.params.get('destination_datacenter', None)
193 self.timeout = self.params.get('timeout')
194 result = dict()
195
196 self.get_vm()
197 if self.vm is None:
198 vm_id = self.vm_uuid or self.vm_name or self.moid
199 self.module.fail_json(msg="Failed to find the virtual machine with %s" % vm_id)
200
201 # Get Datacenter if specified by user
202 dest_datacenter = self.destination_datacenter
203 datacenter_object = None
204 if dest_datacenter is not None:
205 datacenter_object = find_datacenter_by_name(content=self.content, datacenter_name=dest_datacenter)
206 if datacenter_object:
207 dest_datacenter = datacenter_object
208
209 # Get Destination Host System or Cluster if specified by user
210 dest_host_name = self.params.get('destination_host', None)
211 dest_cluster_name = self.params.get('destination_cluster', None)
212
213 if dest_host_name and dest_cluster_name:
214 self.module.fail_json(msg="Please only define one: destination_host or destination_cluster")
215
216 self.host_object = None
217 self.cluster_object = None
218 self.cluster_hosts = None
219
220 if dest_host_name is not None:
221 self.host_object = find_hostsystem_by_name(content=self.content,
222 hostname=dest_host_name)
223 if self.host_object is None:
224 self.module.fail_json(msg="Unable to find destination host %s" % dest_host_name)
225 if dest_cluster_name is not None:
226 self.cluster_object = find_cluster_by_name(content=self.content,
227 cluster_name=dest_cluster_name, datacenter=datacenter_object)
228 if self.cluster_object:
229 self.cluster_hosts = []
230 for host in self.cluster_object.host:
231 self.cluster_hosts.append(host)
232 else:
233 self.module.fail_json(msg="Unable to find destination cluster %s" % dest_cluster_name)
234
235 # Get Destination Datastore or Datastore Cluster if specified by user
236 dest_datastore = self.params.get('destination_datastore', None)
237 dest_datastore_cluster = self.params.get('destination_datastore_cluster', None)
238
239 if dest_datastore and dest_datastore_cluster:
240 self.module.fail_json(msg="Please only define one: destination_datastore or destination_datastore_cluster")
241
242 self.datastore_object = None
243 self.datastore_cluster_object = None
244
245 if dest_datastore is not None:
246 self.datastore_object = find_datastore_by_name(content=self.content,
247 datastore_name=dest_datastore,
248 datacenter_name=dest_datacenter)
249 if dest_datastore_cluster is not None:
250 # unable to use find_datastore_cluster_by_name module
251 data_store_clusters = get_all_objs(self.content, [vim.StoragePod], folder=self.content.rootFolder)
252 for dsc in data_store_clusters:
253 if dsc.name == dest_datastore_cluster:
254 self.datastore_cluster_object = dsc
255
256 # At-least one of datastore, datastore cluster, host system or cluster is required to migrate
257 if self.datastore_object is None and self.datastore_cluster_object is None and self.host_object is None and self.cluster_object is None:
258 self.module.fail_json(msg="Unable to find destination datastore, destination datastore cluster,"
259 " destination host system or destination cluster.")
260
261 # Check if datastore is required, this check is required if destination
262 # and source host system does not share same datastore.
263 host_datastore_required = []
264 for vm_datastore in self.vm.datastore:
265 if self.host_object and vm_datastore not in self.host_object.datastore:
266 host_datastore_required.append(True)
267 if self.cluster_object and vm_datastore not in self.cluster_object.datastore:
268 host_datastore_required.append(True)
269 else:
270 host_datastore_required.append(False)
271
272 if any(host_datastore_required) and (dest_datastore is None and dest_datastore_cluster is None):
273 msg = "Destination host system or cluster does not share" \
274 " datastore ['%s'] with source host system ['%s'] on which" \
275 " virtual machine is located. Please specify destination_datastore or destination_datastore_cluster" \
276 " to rectify this problem." % ("', '".join([ds.name for ds in (self.host_object.datastore
277 or self.cluster_object.datastore)]),
278 "', '".join([ds.name for ds in self.vm.datastore]))
279
280 self.module.fail_json(msg=msg)
281
282 # Check for changes
283 storage_vmotion_needed = True
284 change_required = True
285 vm_ds_name = self.vm.config.files.vmPathName.split(' ', 1)[0].replace('[', '').replace(']', '')
286 if self.host_object and self.datastore_object:
287 # We have both host system and datastore object
288 if not self.datastore_object.summary.accessible:
289 # Datastore is not accessible
290 self.module.fail_json(msg='Destination datastore %s is'
291 ' not accessible.' % dest_datastore)
292
293 if self.datastore_object not in self.host_object.datastore:
294 # Datastore is not associated with host system
295 self.module.fail_json(msg="Destination datastore %s provided"
296 " is not associated with destination"
297 " host system %s. Please specify"
298 " datastore value ['%s'] associated with"
299 " the given host system." % (dest_datastore,
300 dest_host_name,
301 "', '".join([ds.name for ds in self.host_object.datastore])))
302
303 if self.vm.runtime.host.name == dest_host_name and dest_datastore in [ds.name for ds in self.vm.datastore]:
304 change_required = False
305
306 elif self.host_object and self.datastore_cluster_object:
307 if not set(self.datastore_cluster_object.childEntity) <= set(self.host_object.datastore):
308 self.module.fail_json(msg="Destination datastore cluster %s provided"
309 " is not associated with destination"
310 " host system %s. Please specify"
311 " datastore value ['%s'] associated with"
312 " the given host system." % (dest_datastore_cluster,
313 dest_host_name,
314 "', '".join([ds.name for ds in
315 self.host_object.datastore])))
316 if self.vm.runtime.host.name == dest_host_name and vm_ds_name in [ds.name for ds in
317 self.datastore_cluster_object.childEntity]:
318 change_required = False
319
320 elif self.cluster_object and self.datastore_object:
321 if not self.datastore_object.summary.accessible:
322 # Datastore is not accessible
323 self.module.fail_json(msg='Destination datastore %s is'
324 ' not accessible.' % dest_datastore)
325
326 if self.datastore_object not in self.cluster_object.datastore:
327 # Datastore is not associated with host system
328 self.module.fail_json(msg="Destination datastore %s provided"
329 " is not associated with destination"
330 " cluster %s. Please specify"
331 " datastore value ['%s'] associated with"
332 " the given host system." % (dest_datastore,
333 dest_cluster_name,
334 "', '".join([ds.name for ds in
335 self.cluster_object.datastore])))
336
337 if self.vm.runtime.host.name in [host.name for host in self.cluster_hosts] and \
338 dest_datastore in [ds.name for ds in self.vm.datastore]:
339 change_required = False
340
341 elif self.cluster_object and self.datastore_cluster_object:
342 if not set(self.datastore_cluster_object.childEntity) <= set(self.cluster_object.datastore):
343 self.module.fail_json(msg="Destination datastore cluster %s provided"
344 " is not associated with destination"
345 " cluster %s. Please specify"
346 " datastore value ['%s'] associated with"
347 " the given host system." % (dest_datastore_cluster,
348 dest_cluster_name,
349 "', '".join([ds.name for ds in
350 self.cluster_object.datastore])))
351 if self.vm.runtime.host.name in [host.name for host in self.cluster_hosts] and \
352 vm_ds_name in [ds.name for ds in self.datastore_cluster_object.childEntity]:
353 change_required = False
354
355 elif (self.host_object and self.datastore_object is None) or (
356 self.host_object and self.datastore_cluster_object is None):
357 if self.vm.runtime.host.name == dest_host_name:
358 # VM is already located on same host
359 change_required = False
360
361 storage_vmotion_needed = False
362
363 elif (self.cluster_object and self.datastore_object is None) or (
364 self.cluster_object and self.datastore_cluster_object is None):
365 if self.vm.runtime.host.name in [host.name for host in self.cluster_hosts]:
366 # VM is already located on this cluster
367 change_required = False
368
369 storage_vmotion_needed = False
370
371 elif (self.datastore_object and self.host_object is None) or (
372 self.datastore_object and self.cluster_object is None):
373 if self.datastore_object in self.vm.datastore:
374 # VM is already located on same datastore
375 change_required = False
376
377 if not self.datastore_object.summary.accessible:
378 # Datastore is not accessible
379 self.module.fail_json(msg='Destination datastore %s is'
380 ' not accessible.' % dest_datastore)
381
382 elif (self.datastore_cluster_object and self.host_object is None) or (
383 self.datastore_cluster_object and self.cluster_object is None):
384 if vm_ds_name in [ds.name for ds in self.datastore_cluster_object.childEntity]:
385 # VM is already located on a datastore in the datastore cluster
386 change_required = False
387
388 if self.cluster_object or self.datastore_cluster_object:
389 self.set_placement()
390
391 # Get Destination resourcepool
392 dest_resourcepool = self.params.get('destination_resourcepool', None)
393 self.resourcepool_object = None
394 if dest_resourcepool:
395 self.resourcepool_object = find_resource_pool_by_cluster(content=self.content,
396 resource_pool_name=dest_resourcepool)
397 if self.resourcepool_object is None:
398 self.module.fail_json(msg="Unable to find destination resource pool object for %s" % dest_resourcepool)
399 elif not dest_resourcepool and self.host_object:
400 self.resourcepool_object = self.host_object.parent.resourcePool
401
402 if module.check_mode:
403 if self.host_object:
404 result['running_host'] = self.host_object.name
405 if self.datastore_object:
406 result['datastore'] = self.datastore_object.name
407 result['changed'] = change_required
408 module.exit_json(**result)
409
410 if change_required:
411 # Migrate VM and get Task object back
412 task_object = self.migrate_vm()
413 # Wait for task to complete
414 try:
415 wait_for_task(task_object, timeout=self.timeout)
416 except TaskError as task_error:
417 self.module.fail_json(msg=to_native(task_error))
418 # If task was a success the VM has moved, update running_host and complete module
419 if task_object.info.state == vim.TaskInfo.State.success:
420 # The storage layout is not automatically refreshed, so we trigger it to get coherent module return values
421 if storage_vmotion_needed:
422 self.vm.RefreshStorageInfo()
423 if self.host_object:
424 result['running_host'] = self.host_object.name
425 if self.datastore_object:
426 result['datastore'] = self.datastore_object.name
427 result['changed'] = True
428 module.exit_json(**result)
429 else:
430 msg = 'Unable to migrate virtual machine due to an error, please check vCenter'
431 if task_object.info.error is not None:
432 msg += " : %s" % task_object.info.error
433 module.fail_json(msg=msg)
434 else:
435 try:
436 if self.host_object:
437 result['running_host'] = self.host_object.name
438 if self.datastore_object:
439 result['datastore'] = self.datastore_object.name
440 except vim.fault.NoPermission:
441 result['running_host'] = 'NA'
442 result['datastore'] = 'NA'
443 result['changed'] = False
444 module.exit_json(**result)
445
446 def migrate_vm(self):
447 """
448 Migrate virtual machine and return the task.
449 """
450 relocate_spec = vim.vm.RelocateSpec(host=self.host_object,
451 datastore=self.datastore_object,
452 pool=self.resourcepool_object)
453 task_object = self.vm.Relocate(relocate_spec)
454 return task_object
455
456 def set_placement(self):
457 """
458 Get the host from the cluster and/or the datastore from datastore cluster.
459 """
460 if self.cluster_object is None:
461 if self.host_object:
462 self.cluster_object = self.host_object.parent
463 else:
464 self.cluster_object = self.vm.runtime.host.parent
465
466 if not self.cluster_object.configuration.drsConfig.enabled:
467 self.module.fail_json(
468 msg='destination_cluster or destination_storage_cluster is only allowed for clusters with active drs.')
469
470 relocate_spec = vim.vm.RelocateSpec(host=self.host_object,
471 datastore=self.datastore_object)
472 if self.datastore_cluster_object:
473 storagePods = [self.datastore_cluster_object]
474 else:
475 storagePods = None
476 placement_spec = vim.cluster.PlacementSpec(storagePods=storagePods,
477 hosts=self.cluster_hosts,
478 vm=self.vm,
479 relocateSpec=relocate_spec)
480 placement = self.cluster_object.PlaceVm(placement_spec)
481
482 if not placement.recommendations:
483 self.module.fail_json(
484 msg='No placement recommendation from vSphere.')
485
486 if self.host_object is None:
487 self.host_object = placement.recommendations[0].action[0].targetHost
488 if self.datastore_object is None:
489 self.datastore_object = placement.recommendations[0].action[0].relocateSpec.datastore
490
491 def get_vm(self):
492 """
493 Find unique virtual machine either by UUID or Name.
494 Returns: virtual machine object if found, else None.
495
496 """
497 vms = []
498 vm_obj = None
499 if self.vm_uuid:
500 if not self.use_instance_uuid:
501 vm_obj = find_vm_by_id(self.content, vm_id=self.params['vm_uuid'], vm_id_type="uuid")
502 elif self.use_instance_uuid:
503 vm_obj = find_vm_by_id(self.content, vm_id=self.params['vm_uuid'], vm_id_type="instance_uuid")
504 vms = [vm_obj]
505 elif self.vm_name:
506 objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name'])
507 for temp_vm_object in objects:
508 if len(temp_vm_object.propSet) != 1:
509 continue
510 if temp_vm_object.obj.name == self.vm_name:
511 vms.append(temp_vm_object.obj)
512 break
513 elif self.moid:
514 vm_obj = VmomiJSONEncoder.templateOf('VirtualMachine')(self.moid, self.si._stub)
515 if vm_obj:
516 vms.append(vm_obj)
517
518 if len(vms) > 1:
519 self.module.fail_json(msg="Multiple virtual machines with same name %s found."
520 " Please specify vm_uuid instead of vm_name." % self.vm_name)
521
522 if vms:
523 self.vm = vms[0]
524
525
526 def main():
527 argument_spec = base_argument_spec()
528 argument_spec.update(
529 dict(
530 vm_name=dict(aliases=['vm']),
531 vm_uuid=dict(aliases=['uuid']),
532 moid=dict(type='str'),
533 use_instance_uuid=dict(type='bool', default=False),
534 destination_host=dict(aliases=['destination']),
535 destination_resourcepool=dict(aliases=['resource_pool']),
536 destination_datastore=dict(aliases=['datastore']),
537 destination_datacenter=dict(type='str'),
538 destination_cluster=dict(type='str'),
539 destination_datastore_cluster=dict(type='str'),
540 timeout=dict(type='int', default=3600)
541 )
542 )
543
544 module = AnsibleModule(
545 argument_spec=argument_spec,
546 supports_check_mode=True,
547 required_one_of=[
548 ['destination_host', 'destination_datastore', 'destination_cluster', 'destination_datastore_cluster'],
549 ['vm_uuid', 'vm_name', 'moid'],
550 ],
551 mutually_exclusive=[
552 ['vm_uuid', 'vm_name', 'moid'],
553 ],
554 )
555
556 VmotionManager(module)
557
558
559 if __name__ == '__main__':
560 main()