Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2021, Ansible Project
5 # Copyright: (c) 2021, Anant Chopra <[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 # Make coding more python3-ish
10 from __future__ import (absolute_import, division, print_function)
11 __metaclass__ = type
12
13
14 DOCUMENTATION = r'''
15 ---
16 module: vmware_guest_instant_clone
17 short_description: Instant Clone VM
18
19 description:
20 - This module can be used for Creating a powered-on Instant Clone of a virtual machine.
21 - M(community.vmware.vmware_guest) module is needed for creating a VM with poweredon state which would be used as a parent VM.
22 - M(community.vmware.vmware_guest_powerstate) module is also needed to poweroff the instant cloned module.
23 - The powered off VM would in turn be deleted by again using M(community.vmware.vmware_guest) module.
24 - Thus M(community.vmware.vmware_guest) module is necessary for removing Instant Cloned VM when VMs being created in testing environment.
25 - Also GuestOS Customization has now been added with guestinfo_vars parameter.
26 - The Parent VM must have The Guest customization Engine for instant Clone to customize Guest OS.
27 - Only Linux Os in Parent VM enable support for native vSphere Guest Customization for Instant Clone in vSphere 7.
28 options:
29 name:
30 description:
31 - Name of the Cloned virtual machine.
32 type: str
33 aliases: ['vm_name']
34 required: true
35 parent_vm:
36 description:
37 - Name of the parent virtual machine.
38 - This is a required parameter, if parameter O(uuid) or O(moid) is not supplied.
39 type: str
40 uuid:
41 description:
42 - UUID of the vm instance to clone from, this is VMware's unique identifier.
43 - This is a required parameter, if parameter O(parent_vm) or O(moid) is not supplied.
44 type: str
45 moid:
46 description:
47 - Managed Object ID of the vm instance to manage if known, this is a unique identifier only within a single vCenter instance.
48 - This is required if O(parent_vm) or O(uuid) is not supplied.
49 type: str
50 use_instance_uuid:
51 description:
52 - Whether to use the VMware instance UUID rather than the BIOS UUID.
53 default: false
54 type: bool
55 host:
56 description:
57 - Name of the ESX Host in datacenter in which to place cloned VM.
58 - The host has to be a member of the cluster that contains the resource pool.
59 - Required with O(resource_pool) to find resource pool details. This will be used as additional information when there are resource pools with same name.
60 type: str
61 aliases: ['esxi_hostname']
62 required: true
63 datastore:
64 description:
65 - The name of the datastore or the datastore cluster.
66 - If datastore cluster name is specified, module will find the Storage DRS recommended datastore in that cluster.
67 type: str
68 required: true
69 datacenter:
70 description:
71 - Name of the datacenter, where VM to be deployed.
72 type: str
73 required: true
74 folder:
75 description:
76 - Destination folder, absolute path to deploy the cloned vm.
77 - 'Examples:'
78 - 'folder: ha-datacenter/vm'
79 - 'folder: /datacenter1/vm'
80 type: str
81 resource_pool:
82 description:
83 - Name of the resource pool in datacenter in which to place deployed VM.
84 - C(Resources) is the default name of resource pool.
85 type: str
86 required: false
87 vm_username:
88 description:
89 - The user to login-in to the virtual machine.
90 - Only required when using guest customization feature.
91 required: false
92 type: str
93 vm_password:
94 description:
95 - The password used to login-in to the virtual machine.
96 - Only required when using guest customization feature.
97 required: false
98 type: str
99 guestinfo_vars:
100 description:
101 - Provides GuestOS Customization functionality in instant cloned VM.
102 - A list of key value pairs that will be passed to the destination VM.
103 - These pairs should be used to provide user-defined customization to differentiate the destination VM from the source VM.
104 suboptions:
105 hostname:
106 description:
107 - hostname is used to obtain the DNS(Domain Name System) name and set the Guest system's hostname.
108 type: str
109 ipaddress:
110 description:
111 - ipaddress is used to set the ipaddress in Instant Cloned Guest Operating System.
112 type: str
113 netmask:
114 description:
115 - netmask is used to set the netmask in Instant Cloned Guest Operating System.
116 type: str
117 gateway:
118 description:
119 - netmask is used to set the netmask in Instant Cloned Guest Operating System.
120 type: str
121 dns:
122 description:
123 - dns is used to set the dns in Instant Cloned Guest Operating System..
124 type: str
125 domain:
126 description:
127 - domain is used to set A fully qualified domain name (FQDN) or complete domain name for Instant Cloned Guest operating System.
128 type: str
129 type: list
130 elements: dict
131 wait_vm_tools:
132 description:
133 - Whether waiting until vm tools start after rebooting an instant clone vm.
134 type: bool
135 default: true
136 wait_vm_tools_timeout:
137 description:
138 - Define a timeout (in seconds) for the O(wait_vm_tools) parameter.
139 type: int
140 default: 300
141 extends_documentation_fragment:
142 - vmware.vmware.base_options
143
144 author:
145 - Anant Chopra (@Anant99-sys)
146
147 '''
148
149 EXAMPLES = r'''
150 - name: Instant Clone a VM
151 community.vmware.vmware_guest_instant_clone:
152 hostname: "{{ vcenter_hostname }}"
153 username: "{{ vcenter_username }}"
154 password: "{{ vcenter_password }}"
155 validate_certs: false
156 folder: "{{ f0 }}"
157 datastore: "{{ rw_datastore }}"
158 datacenter: "{{ dc1 }}"
159 host: "{{ esxi1 }}"
160 name: "{{ Clone_vm }}"
161 parent_vm: "{{ testvm_1 }}"
162 resource_pool: "{{ test_resource_001 }}"
163 register: vm_clone
164 delegate_to: localhost
165
166 - name: set state to poweroff the Cloned VM
167 community.vmware.vmware_guest_powerstate:
168 validate_certs: false
169 hostname: "{{ vcenter_hostname }}"
170 username: "{{ vcenter_username }}"
171 password: "{{ vcenter_password }}"
172 name: "cloned_vm_from_vm_cluster"
173 folder: "{{ f0 }}"
174 state: powered-off
175 register: poweroff_instant_clone_from_vm_when_cluster
176 delegate_to: localhost
177
178 - name: Clean VM
179 community.vmware.vmware_guest:
180 validate_certs: false
181 hostname: "{{ vcenter_hostname }}"
182 username: "{{ vcenter_username }}"
183 password: "{{ vcenter_password }}"
184 name: "cloned_vm_from_vm_cluster"
185 datacenter: "{{ dc1 }}"
186 state: absent
187 register: delete_instant_clone_from_vm_when_cluster
188 ignore_errors: true
189 delegate_to: localhost
190
191 - name: Instant Clone a VM with guest_customization
192 community.vmware.vmware_guest_instant_clone:
193 hostname: "{{ vcenter_hostname }}"
194 username: "{{ vcenter_username }}"
195 password: "{{ vcenter_password }}"
196 vm_username: "root"
197 vm_password: "SuperSecret"
198 validate_certs: false
199 folder: "{{ f0 }}"
200 datastore: "{{ rw_datastore }}"
201 datacenter: "{{ dc1 }}"
202 host: "{{ esxi1 }}"
203 guestinfo_vars:
204 - hostname: "{{ guestinfo.ic.hostname }}"
205 ipaddress: "{{ guestinfo.ic.ipaddress }}"
206 netmask: "{{ guestinfo.ic.netmask }}"
207 gateway: "{{ guestinfo.ic.gateway }}"
208 dns: "{{ guestinfo.ic.dns }}"
209 domain: "{{ guestinfo.ic.domain }}"
210 name: "Instant_clone_guest_customize"
211 parent_vm: "test_vm1"
212 resource_pool: DC0_C0_RP1
213 register: Instant_cloned_guest_customize
214 delegate_to: localhost
215
216 - name: Instant Clone a VM when skipping optional params
217 community.vmware.vmware_guest_instant_clone:
218 hostname: "{{ vcenter_hostname }}"
219 username: "{{ vcenter_username }}"
220 password: "{{ vcenter_password }}"
221 validate_certs: false
222 name: "{{ Clone_vm }}"
223 parent_vm: "{{ testvm_1 }}"
224 datacenter: "{{ dc1 }}"
225 datastore: "{{ rw_datastore }}"
226 host: "{{ esxi1 }}"
227 register: VM_clone_optional_arguments
228 delegate_to: localhost
229
230 - name: Instant clone in check mode
231 community.vmware.vmware_guest_instant_clone:
232 hostname: "{{ vcenter_hostname }}"
233 username: "{{ vcenter_username }}"
234 password: "{{ vcenter_password }}"
235 validate_certs: false
236 folder: "{{ f0 }}"
237 datastore: "{{ rw_datastore }}"
238 datacenter: "{{ dc1 }}"
239 host: "{{ esx1 }}"
240 name: "{{ Clone_vm }}"
241 parent_vm: "{{ testvm_2 }}"
242 resource_pool: "{{ test_resource_001 }}"
243 check_mode: true
244 register: check_mode_clone
245 delegate_to: localhost
246 - debug:
247 var: check_mode_clone
248
249 '''
250
251 RETURN = r'''
252 vm_info:
253 description:
254 - metadata about the virtual machine
255 returned: always
256 type: dict
257 sample: {
258 "vm_name": "",
259 "vcenter": "",
260 "host": "",
261 "datastore": "",
262 "vm_folder": "",
263 "instance_uuid": ""
264 }
265 '''
266
267 import time
268 from ansible.module_utils.common.text.converters import to_native
269 from ansible.module_utils.basic import AnsibleModule
270
271 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
272 PyVmomi,
273 TaskError,
274 find_vm_by_name,
275 find_vm_by_id,
276 find_obj,
277 wait_for_task,
278 set_vm_power_state
279 )
280 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
281 from ansible_collections.vmware.vmware.plugins.module_utils.clients.pyvmomi import PyvmomiClient
282
283 try:
284 from pyVmomi import vim
285 except ImportError:
286 pass
287
288
289 class VmwareGuestInstantClone(PyVmomi):
290 def __init__(self, module):
291 """Constructor."""
292 super().__init__(module)
293 self.instant_clone_spec = vim.vm.InstantCloneSpec()
294 self.relocate_spec = vim.vm.RelocateSpec()
295 self.vm_name = self.params.get('name')
296 self.parent_vm = self.params.get('parent_vm')
297 self.datacenter = self.params.get('datacenter')
298 self.datastore = self.params.get('datastore')
299 self.hostname = self.params.get('hostname')
300 self.folder = self.params.get('folder')
301 self.resource_pool = self.params.get('resource_pool')
302 self.host = self.params.get('host')
303 self.username = self.params.get('username')
304 self.password = self.params.get('password')
305 self.validate_certs = self.params.get('validate_certs')
306 self.moid = self.params.get('moid')
307 self.uuid = self.params.get('uuid')
308 self.port = self.params.get('port')
309 self.use_instance_uuid = self.params.get('use_instance_uuid')
310 self.wait_vm_tools = self.params.get('wait_vm_tools')
311 self.wait_vm_tools_timeout = self.params.get('wait_vm_tools_timeout')
312 self.guestinfo_vars = self.params.get('guestinfo_vars')
313
314 def get_new_vm_info(self, vm):
315 # to check if vm has been cloned in the destination vc
316 # query for the vm in destination vc
317 # get the host and datastore info
318 info = {}
319 vm_obj = find_vm_by_name(content=self.destination_content, vm_name=vm)
320 if vm_obj is None:
321 self.module.fail_json(msg="Newly Instant cloned VM is not found in the VCenter")
322
323 vm_facts = self.gather_facts(vm_obj)
324 info['vm_name'] = vm
325 info['vcenter'] = self.hostname
326 info['host'] = vm_facts['hw_esxi_host']
327 info['datastore'] = vm_facts['hw_datastores']
328 info['vm_folder'] = vm_facts['hw_folder']
329 info['instance_uuid'] = vm_facts['instance_uuid']
330 return info
331
332 def Instant_clone(self):
333 # clone the vm on VC
334 if self.vm_obj is None:
335 vm_id = self.parent_vm or self.uuid or self.moid
336 self.module.fail_json(msg="Failed to find the VM/template with %s" % vm_id)
337 try:
338 task = self.vm_obj.InstantClone_Task(spec=self.instant_clone_spec)
339 wait_for_task(task)
340 vm_info = self.get_new_vm_info(self.vm_name)
341 result = {'changed': True, 'failed': False, 'vm_info': vm_info}
342 except TaskError as task_e:
343 self.module.fail_json(msg=to_native(task_e))
344
345 pyvmomi_client = PyvmomiClient(
346 hostname=self.hostname,
347 username=self.username,
348 password=self.password,
349 port=self.port,
350 validate_certs=self.validate_certs)
351
352 self.destination_content = pyvmomi_client.content
353
354 vm_IC = find_vm_by_name(content=self.destination_content, vm_name=self.params['name'])
355 if vm_IC and self.params.get('guestinfo_vars'):
356 guest_custom_mng = self.destination_content.guestCustomizationManager
357 # Make an object for authentication in a guest OS
358 auth_obj = vim.vm.guest.NamePasswordAuthentication()
359
360 guest_user = self.params.get('vm_username')
361 guest_password = self.params.get('vm_password')
362 auth_obj.username = guest_user
363 auth_obj.password = guest_password
364
365 guestinfo_vars = self.params.get('guestinfo_vars')
366 # Make a spec object to customize Guest OS
367 customization_spec = vim.vm.customization.Specification()
368 customization_spec.globalIPSettings = vim.vm.customization.GlobalIPSettings()
369 customization_spec.globalIPSettings.dnsServerList = [guestinfo_vars[0]['dns']]
370 # Make an identity object to do linux prep
371 # The params are reflected the specified following after rebooting OS
372 customization_spec.identity = vim.vm.customization.LinuxPrep()
373 customization_spec.identity.domain = guestinfo_vars[0]['domain']
374 customization_spec.identity.hostName = vim.vm.customization.FixedName()
375 customization_spec.identity.hostName.name = guestinfo_vars[0]['hostname']
376
377 customization_spec.nicSettingMap = []
378 adapter_mapping_obj = vim.vm.customization.AdapterMapping()
379 adapter_mapping_obj.adapter = vim.vm.customization.IPSettings()
380 adapter_mapping_obj.adapter.ip = vim.vm.customization.FixedIp()
381 adapter_mapping_obj.adapter.ip.ipAddress = guestinfo_vars[0]['ipaddress']
382 adapter_mapping_obj.adapter.subnetMask = guestinfo_vars[0]['netmask']
383 adapter_mapping_obj.adapter.gateway = [guestinfo_vars[0]['gateway']]
384
385 customization_spec.nicSettingMap.append(adapter_mapping_obj)
386
387 try:
388 task_guest = guest_custom_mng.CustomizeGuest_Task(vm_IC, auth_obj, customization_spec)
389 wait_for_task(task_guest)
390 vm_info = self.get_new_vm_info(self.vm_name)
391 result = {'changed': True, 'failed': False, 'vm_info': vm_info}
392 except TaskError as task_e:
393 self.module.fail_json(msg=to_native(task_e))
394
395 # Should require rebooting to reflect customization parameters to instant clone vm.
396 instant_vm_obj = find_vm_by_id(content=self.content, vm_id=vm_info['instance_uuid'], vm_id_type='instance_uuid')
397 set_vm_power_state(content=self.content, vm=instant_vm_obj, state='rebootguest', force=False)
398
399 if self.wait_vm_tools:
400 interval = 15
401 # Wait vm tools is started after rebooting.
402 while self.wait_vm_tools_timeout > 0:
403 if instant_vm_obj.guest.toolsRunningStatus != 'guestToolsRunning':
404 break
405 self.wait_vm_tools_timeout -= interval
406 time.sleep(interval)
407
408 while self.wait_vm_tools_timeout > 0:
409 if instant_vm_obj.guest.toolsRunningStatus == 'guestToolsRunning':
410 break
411 self.wait_vm_tools_timeout -= interval
412 time.sleep(interval)
413
414 if self.wait_vm_tools_timeout <= 0:
415 self.module.fail_json(msg="Timeout has been reached for waiting to start the vm tools.")
416
417 return result
418
419 def sanitize_params(self):
420 '''
421 Verify user-provided parameters
422 '''
423 # connect to host/VC
424 pyvmomi_client = PyvmomiClient(
425 hostname=self.hostname,
426 username=self.username,
427 password=self.password,
428 port=self.port,
429 validate_certs=self.validate_certs)
430
431 self.destination_content = pyvmomi_client.content
432
433 use_instance_uuid = self.params.get('use_instance_uuid') or False
434
435 if 'parent_vm' in self.params and self.params['parent_vm']:
436 self.vm_obj = find_vm_by_name(content=self.destination_content, vm_name=self.parent_vm)
437
438 elif 'uuid' in self.params and self.params['uuid']:
439 if not use_instance_uuid:
440 self.vm_obj = find_vm_by_id(content=self.destination_content, vm_id=self.params['uuid'], vm_id_type="uuid")
441 elif use_instance_uuid:
442 self.vm_obj = find_vm_by_id(content=self.destination_content,
443 vm_id=self.params['uuid'],
444 vm_id_type="instance_uuid")
445
446 elif 'moid' in self.params and self.params['moid']:
447 self.vm_obj = vim.VirtualMachine(self.params['moid'], self.si._stub)
448
449 if self.vm_obj is None:
450 vm_id = self.parent_vm or self.uuid or self.moid
451 self.module.fail_json(msg="Failed to find the VM/template with %s" % vm_id)
452
453 vm = find_vm_by_name(content=self.destination_content, vm_name=self.params['name'])
454 if vm:
455 self.module.exit_json(changed=False, msg="A VM with the given name already exists")
456
457 self.datacenter = self.find_datacenter_by_name(self.params['datacenter'])
458
459 # datacentre check
460 if self.datacenter is None:
461 self.module.fail_json(msg="Datacenter not found.")
462
463 datastore_name = self.params['datastore']
464 datastore_cluster = find_obj(self.destination_content, [vim.StoragePod], datastore_name)
465
466 if datastore_cluster:
467 # If user specified datastore cluster so get recommended datastore
468 datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster)
469 # Check if get_recommended_datastore or user specified datastore exists or not
470 # datastore check
471 self.datastore = self.find_datastore_by_name(datastore_name=datastore_name)
472
473 if self.datastore is None:
474 self.module.fail_json(msg="Datastore not found.")
475
476 if self.params['folder']:
477 self.folder = self.find_folder_by_fqpn(folder_name=self.params['folder'], datacenter_name=self.params['datacenter'], folder_type='vm')
478 if self.folder is None:
479 self.module.fail_json(msg="Folder not found.")
480 else:
481 self.folder = self.datacenter.vmFolder
482
483 self.host = self.find_hostsystem_by_name(host_name=self.params['host'])
484 if self.host is None:
485 self.module.fail_json(msg="Host not found.")
486
487 if self.params['resource_pool']:
488 self.resource_pool = self.find_resource_pool_by_name(resource_pool_name=self.params['resource_pool'])
489 if self.resource_pool is None:
490 self.module.fail_json(msg="Resource Pool not found.")
491 else:
492 self.resource_pool = self.host.parent.resourcePool
493
494 if self.params['guestinfo_vars']:
495 self.guestinfo_vars = self.dict_to_optionvalues()
496 else:
497 self.guestinfo_vars = None
498
499 def dict_to_optionvalues(self):
500 optionvalues = []
501 for dictionary in self.params['guestinfo_vars']:
502 for key, value in dictionary.items():
503 opt = vim.option.OptionValue()
504 (opt.key, opt.value) = ("guestinfo.ic." + key, value)
505 optionvalues.append(opt)
506
507 return optionvalues
508
509 def populate_specs(self):
510
511 # populate relocate spec
512 self.relocate_spec.datastore = self.datastore
513 self.relocate_spec.pool = self.resource_pool
514 self.relocate_spec.folder = self.folder
515 # populate Instant clone spec
516 self.instant_clone_spec.name = self.vm_name
517 self.instant_clone_spec.location = self.relocate_spec
518 self.instant_clone_spec.config = self.guestinfo_vars
519
520
521 def main():
522 argument_spec = base_argument_spec()
523 argument_spec.update(
524 name=dict(type='str', required=True, aliases=['vm_name']),
525 uuid=dict(type='str'),
526 moid=dict(type='str'),
527 vm_username=dict(type='str', required=False),
528 vm_password=dict(type='str', no_log=True, required=False),
529 datacenter=dict(type='str', required=True),
530 datastore=dict(type='str', required=True),
531 use_instance_uuid=dict(type='bool', default=False),
532 host=dict(type='str', required=True, aliases=['esxi_hostname']),
533 folder=dict(type='str', required=False),
534 resource_pool=dict(type='str', required=False),
535 parent_vm=dict(type='str'),
536 wait_vm_tools=dict(type='bool', default=True),
537 wait_vm_tools_timeout=dict(type='int', default=300),
538 guestinfo_vars=dict(
539 type='list',
540 elements='dict',
541 options=dict(
542 ipaddress=dict(type='str'),
543 netmask=dict(type='str'),
544 gateway=dict(type='str'),
545 dns=dict(type='str'),
546 domain=dict(type='str'),
547 hostname=dict(type='str'),
548 ),
549 ),
550 )
551 module = AnsibleModule(
552 argument_spec=argument_spec,
553 supports_check_mode=True,
554 required_one_of=[
555 ['uuid', 'parent_vm', 'moid'],
556 ],
557 mutually_exclusive=[
558 ['uuid', 'parent_vm', 'moid'],
559 ],
560 required_together=[
561 ['vm_username', 'vm_password', 'guestinfo_vars']
562 ]
563 )
564 result = {'failed': False, 'changed': False}
565
566 if module.check_mode:
567 result.update(
568 vm_name=module.params['name'],
569 host=module.params['hostname'],
570 datastore=module.params['datastore'],
571 vm_folder=module.params['folder'],
572 changed=True,
573 desired_operation='Create VM with check mode'
574 )
575 module.exit_json(**result)
576
577 clone_manager = VmwareGuestInstantClone(module)
578 clone_manager.sanitize_params()
579 clone_manager.populate_specs()
580 result = clone_manager.Instant_clone()
581
582 if result['failed']:
583 module.fail_json(**result)
584 module.exit_json(**result)
585
586
587 if __name__ == '__main__':
588 main()