Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # This module is also sponsored by E.T.A.I. (www.etai.fr)
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r'''
13 ---
14 module: vmware_guest
15 short_description: Manages virtual machines in vCenter
16 description: >
17 This module can be used to create new virtual machines from templates or other virtual machines,
18 manage power state of virtual machine such as power on, power off, suspend, shutdown, reboot, restart etc.,
19 modify various virtual machine components like network, disk, customization etc.,
20 rename a virtual machine and remove a virtual machine with associated components.
21 author:
22 - Loic Blot (@nerzhul) <[email protected]>
23 - Philippe Dellaert (@pdellaert) <[email protected]>
24 - Abhijeet Kasurde (@Akasurde) <[email protected]>
25 notes:
26 - Please make sure that the user used for M(community.vmware.vmware_guest) has the correct level of privileges.
27 - For example, following is the list of minimum privileges required by users to create virtual machines.
28 - " DataStore > Allocate Space"
29 - " Virtual Machine > Configuration > Add New Disk"
30 - " Virtual Machine > Configuration > Add or Remove Device"
31 - " Virtual Machine > Inventory > Create New"
32 - " Network > Assign Network"
33 - " Resource > Assign Virtual Machine to Resource Pool"
34 - "Module may require additional privileges as well, which may be required for gathering facts - e.g. ESXi configurations."
35 - Use SCSI disks instead of IDE when you want to expand online disks by specifying a SCSI controller.
36 - Uses SysPrep for Windows VM (depends on 'guest_id' parameter match 'win') with PyVmomi.
37 - In order to change the VM's parameters (e.g. number of CPUs), the VM must be powered off unless the hot-add
38 support is enabled and the O(state=present) must be used to apply the changes.
39 - "For additional information please visit Ansible VMware community wiki - U(https://github.com/ansible/community/wiki/VMware)."
40 options:
41 state:
42 description:
43 - Specify the state the virtual machine should be in.
44 - If V(present) and virtual machine exists, ensure the virtual machine configurations conforms to task arguments.
45 - If V(absent) and virtual machine exists, then the specified virtual machine is removed with it's associated components.
46 - If set to one of V(poweredon), V(powered-on), V(poweredoff), V(powered-off),
47 V(present), V(restarted), V(suspended) and virtual machine does not exists, virtual machine is deployed with the given parameters.
48 - If set to V(poweredon) or V(powered-on) and virtual machine exists with powerstate other than powered on,
49 then the specified virtual machine is powered on.
50 - If set to V(poweredoff) or V(powered-off) and virtual machine exists with powerstate other than powered off,
51 then the specified virtual machine is powered off.
52 - If set to V(restarted) and virtual machine exists, then the virtual machine is restarted.
53 - If set to V(suspended) and virtual machine exists, then the virtual machine is set to suspended mode.
54 - If set to V(shutdownguest) or V(shutdown-guest) and virtual machine exists, then the virtual machine is shutdown.
55 - If set to V(rebootguest) or V(reboot-guest) and virtual machine exists, then the virtual machine is rebooted.
56 default: present
57 type: str
58 choices: [ absent, poweredon, powered-on, poweredoff, powered-off, present, rebootguest, reboot-guest, restarted, suspended, shutdownguest, shutdown-guest]
59 name:
60 description:
61 - Name of the virtual machine to work with.
62 - Virtual machine names in vCenter are not necessarily unique, which may be problematic, see O(name_match).
63 - If multiple virtual machines with same name exists, then O(folder) is required parameter to
64 identify uniqueness of the virtual machine.
65 - This parameter is required, if O(state=poweredon), O(state=powered-on), O(state=poweredoff), O(state=powered-off),
66 O(state=present), O(state=restarted), O(state=suspended) and virtual machine does not exists.
67 type: str
68 name_match:
69 description:
70 - If multiple virtual machines matching the name, use the first or last found.
71 default: 'first'
72 choices: [ 'first', 'last' ]
73 type: str
74 uuid:
75 description:
76 - UUID of the virtual machine to manage if known, this is VMware's unique identifier.
77 - This is required if O(name) is not supplied.
78 - If virtual machine does not exists, then this parameter is ignored.
79 - Please note that a supplied UUID will be ignored on virtual machine creation, as VMware creates the UUID internally.
80 type: str
81 use_instance_uuid:
82 description:
83 - Whether to use the VMware instance UUID rather than the BIOS UUID.
84 default: false
85 type: bool
86 template:
87 description:
88 - Template or existing virtual machine used to create new virtual machine.
89 - If this value is not set, virtual machine is created without using a template.
90 - If the virtual machine already exists, this parameter will be ignored.
91 - From version 2.8 onwards, absolute path to virtual machine or template can be used.
92 aliases: [ 'template_src' ]
93 type: str
94 is_template:
95 description:
96 - Flag the instance as a template.
97 - This will mark the given virtual machine as template.
98 - Note, this may need to be done in a dedicated task invocation that is not making
99 any other changes. For example, user cannot change the state from powered-on to
100 powered-off AND save as template in the same task.
101 - See M(community.vmware.vmware_guest) source for more details.
102 default: false
103 type: bool
104 folder:
105 description:
106 - Destination folder, absolute path to find an existing guest or create the new guest.
107 - "The folder should include the datacenter. ESXi's datacenter is ha-datacenter."
108 - 'If multiple machines are found with same name, this parameter is used to identify'
109 - 'uniqueness of the virtual machine.'
110 - 'Examples:'
111 - ' folder: /ha-datacenter/vm'
112 - ' folder: ha-datacenter/vm'
113 - ' folder: /datacenter1/vm'
114 - ' folder: datacenter1/vm'
115 - ' folder: /datacenter1/vm/folder1'
116 - ' folder: datacenter1/vm/folder1'
117 - ' folder: /folder1/datacenter1/vm'
118 - ' folder: folder1/datacenter1/vm'
119 - ' folder: /folder1/datacenter1/vm/folder2'
120 type: str
121 hardware:
122 type: dict
123 default: {}
124 description:
125 - "Manage virtual machine's hardware attributes."
126 suboptions:
127 hotadd_cpu:
128 type: bool
129 description: Allow virtual CPUs to be added while the virtual machine is running.
130 hotremove_cpu:
131 type: bool
132 description: Allow virtual CPUs to be removed while the virtual machine is running.
133 hotadd_memory:
134 type: bool
135 description: Allow memory to be added while the virtual machine is running.
136 memory_mb:
137 type: int
138 description: Amount of memory in MB.
139 num_cpus:
140 type: int
141 description:
142 - Number of CPUs.
143 - Must be a multiple of O(hardware.num_cpu_cores_per_socket).
144 - For example, to create a VM with 2 sockets of 4 cores, specify O(hardware.num_cpus) as 8 and O(hardware.num_cpu_cores_per_socket) as 4.
145 num_cpu_cores_per_socket:
146 type: int
147 description: Number of Cores Per Socket.
148 cpu_shares_level:
149 type: str
150 choices: [ 'low', 'normal', 'high', 'custom' ]
151 description:
152 - The allocation level of CPU resources for the virtual machine.
153 version_added: '3.2.0'
154 cpu_shares:
155 type: int
156 description:
157 - The number of shares of CPU allocated to this virtual machine
158 - cpu_shares_level will automatically be set to 'custom'
159 version_added: '3.2.0'
160 vpmc_enabled:
161 version_added: '3.2.0'
162 type: bool
163 description: Enable virtual CPU Performance Counters.
164 scsi:
165 type: str
166 description:
167 - Valid values are V(buslogic), V(lsilogic), V(lsilogicsas) and V(paravirtual).
168 - V(paravirtual) is default.
169 choices: [ 'buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual' ]
170 secure_boot:
171 type: bool
172 description: Whether to enable or disable (U)EFI secure boot.
173 memory_reservation_lock:
174 type: bool
175 description:
176 - If set V(true), memory resource reservation for the virtual machine.
177 max_connections:
178 type: int
179 description:
180 - Maximum number of active remote display connections for the virtual machines.
181 mem_limit:
182 type: int
183 description:
184 - The memory utilization of a virtual machine will not exceed this limit.
185 - Unit is MB.
186 mem_reservation:
187 type: int
188 description: The amount of memory resource that is guaranteed available to the virtual machine.
189 aliases: [ 'memory_reservation' ]
190 mem_shares_level:
191 type: str
192 description:
193 - The allocation level of memory resources for the virtual machine.
194 choices: [ 'low', 'normal', 'high', 'custom' ]
195 version_added: '3.2.0'
196 mem_shares:
197 type: int
198 description:
199 - The number of shares of memory allocated to this virtual machine
200 - mem_shares_level will automatically be set to 'custom'
201 version_added: '3.2.0'
202 cpu_limit:
203 type: int
204 description:
205 - The CPU utilization of a virtual machine will not exceed this limit.
206 - Unit is MHz.
207 cpu_reservation:
208 type: int
209 description: The amount of CPU resource that is guaranteed available to the virtual machine.
210 version:
211 type: str
212 description:
213 - The Virtual machine hardware versions.
214 - Default is 10 (ESXi 5.5 and onwards).
215 - If set to V(latest), the specified virtual machine will be upgraded to the most current hardware version supported on the host.
216 - Please check VMware documentation for correct virtual machine hardware version.
217 - Incorrect hardware version may lead to failure in deployment. If hardware version is already equal to the given.
218 boot_firmware:
219 type: str
220 description: Choose which firmware should be used to boot the virtual machine.
221 choices: [ 'bios', 'efi' ]
222 nested_virt:
223 type: bool
224 description:
225 - Enable nested virtualization.
226 virt_based_security:
227 type: bool
228 description:
229 - Enable Virtualization Based Security feature for Windows on ESXi 6.7 and later, from hardware version 14.
230 - Supported Guest OS are Windows 10 64 bit, Windows Server 2016, Windows Server 2019 and later.
231 - The firmware of virtual machine must be EFI and secure boot must be enabled.
232 - Virtualization Based Security depends on nested virtualization and Intel Virtualization Technology for Directed I/O.
233 - Deploy on unsupported ESXi, hardware version or firmware may lead to failure or deployed VM with unexpected configurations.
234 iommu:
235 type: bool
236 description: Flag to specify if I/O MMU is enabled for this virtual machine.
237 encryption:
238 type: dict
239 default: {}
240 description:
241 - Manage virtual machine encryption settings
242 version_added: '3.9.0'
243 suboptions:
244 encrypted_vmotion:
245 type: str
246 description: Controls encryption for live migrations with vmotion
247 choices: ['disabled', 'opportunistic', 'required']
248 encrypted_ft:
249 type: str
250 description: Controls encryption for fault tolerance replication
251 choices: ['disabled', 'opportunistic', 'required']
252 guest_id:
253 type: str
254 description:
255 - Set the guest ID.
256 - This field is required when creating a virtual machine, not required when creating from the template.
257 - >
258 Valid values are referenced here:
259 U(https://code.vmware.com/apis/358/doc/vim.vm.GuestOsDescriptor.GuestOsIdentifier.html)
260 disk:
261 description:
262 - A list of disks to add.
263 - Shrinking disks is not supported.
264 - Removing existing disks of the virtual machine is not supported.
265 - 'Attributes O(disk[].controller_type), O(disk[].controller_number), O(disk[].unit_number) are used to configure multiple types of disk
266 controllers and disks for creating or reconfiguring virtual machine.'
267 type: list
268 default: []
269 elements: dict
270 suboptions:
271 size:
272 description:
273 - Disk storage size.
274 - Please specify storage unit like [kb, mb, gb, tb].
275 type: str
276 size_kb:
277 description: Disk storage size in kb.
278 type: int
279 size_mb:
280 description: Disk storage size in mb.
281 type: int
282 size_gb:
283 description: Disk storage size in gb.
284 type: int
285 size_tb:
286 description: Disk storage size in tb.
287 type: int
288 type:
289 description:
290 - Type of disk.
291 - If not specified, disk type is inherited from the source VM or template when cloned and thick disk, no eagerzero otherwise.
292 type: str
293 choices: [ 'thin', 'thick', 'eagerzeroedthick' ]
294 datastore:
295 type: str
296 description:
297 - The name of datastore which will be used for the disk.
298 - If O(disk[].autoselect_datastore) is set to True, will select the less used datastore whose name contains this "disk.datastore" string.
299 filename:
300 type: str
301 description:
302 - Existing disk image to be used.
303 - Filename must already exist on the datastore.
304 - Specify filename string in C([datastore_name] path/to/file.vmdk) format.
305 autoselect_datastore:
306 type: bool
307 description:
308 - Select the less used datastore.
309 - O(disk[].datastore) and O(disk[].autoselect_datastore) will not be used if O(datastore) is specified outside this O(disk[]) configuration.
310 disk_mode:
311 type: str
312 choices: ['persistent', 'independent_persistent', 'independent_nonpersistent']
313 description:
314 - Type of disk mode.
315 - If V(persistent) specified, changes are immediately and permanently written to the virtual disk. This is default.
316 - If V(independent_persistent) specified, same as persistent, but not affected by snapshots.
317 - If V(independent_nonpersistent) specified, changes to virtual disk are made to a redo log and discarded at power off,
318 but not affected by snapshots.
319 controller_type:
320 type: str
321 choices: ['buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual', 'sata', 'nvme']
322 description:
323 - Type of disk controller.
324 Set this type on not supported ESXi or VM hardware version will lead to failure in deployment.
325 - When set to V(sata), please make sure O(disk[].unit_number) is correct and not used by SATA CDROMs.
326 - If set to V(sata) type, please make sure O(disk[].controller_number) and O(disk[].unit_number) are set correctly when O(cdrom=sata).
327 controller_number:
328 type: int
329 choices: [0, 1, 2, 3]
330 description:
331 - Disk controller bus number.
332 - The maximum number of same type controller is 4 per VM.
333 unit_number:
334 type: int
335 description:
336 - Disk Unit Number.
337 - Valid value range from 0 to 15 for SCSI controller, except 7.
338 - Valid value range from 0 to 14 for NVME controller.
339 - Valid value range from 0 to 29 for SATA controller.
340 - O(disk[].controller_type), O(disk[].controller_number) and O(disk[].unit_number) are required when creating or reconfiguring VMs
341 with multiple types of disk controllers and disks.
342 - When creating new VM, the first configured disk in the O(disk[]) list will be "Hard Disk 1".
343 nvdimm:
344 description:
345 - Add or remove a virtual NVDIMM device to the virtual machine.
346 - VM virtual hardware version must be 14 or higher on vSphere 6.7 or later.
347 - Verify that guest OS of the virtual machine supports PMem before adding virtual NVDIMM device.
348 - Verify that you have the I(Datastore.Allocate) space privilege on the virtual machine.
349 - Make sure that the host or the cluster on which the virtual machine resides has available PMem resources.
350 - To add or remove virtual NVDIMM device to the existing virtual machine, it must be in power off state.
351 type: dict
352 default: {}
353 suboptions:
354 state:
355 type: str
356 description:
357 - If set to V(absent), then the NVDIMM device with specified O(nvdimm.label) will be removed.
358 choices: ['present', 'absent']
359 size_mb:
360 type: int
361 description: Virtual NVDIMM device size in MB.
362 default: 1024
363 label:
364 type: str
365 description:
366 - The label of the virtual NVDIMM device to be removed or configured, e.g., "NVDIMM 1".
367 - 'This parameter is required when O(nvdimm.state=absent), or O(nvdimm.state=present) to reconfigure NVDIMM device
368 size. When add a new device, please do not set.'
369 cdrom:
370 description:
371 - A list of CD-ROM configurations for the virtual machine.
372 - For V(ide) controller, hot-add or hot-remove CD-ROM is not supported.
373 type: list
374 default: []
375 elements: dict
376 suboptions:
377 type:
378 type: str
379 description:
380 - The type of CD-ROM.
381 - With V(none) the CD-ROM will be disconnected but present.
382 choices: [ 'none', 'client', 'iso' ]
383 default: client
384 iso_path:
385 type: str
386 description:
387 - The datastore path to the ISO file to use, in the form of C([datastore1] path/to/file.iso).
388 - Required if type is set V(iso).
389 controller_type:
390 type: str
391 description:
392 - When set to V(sata), please make sure O(cdrom[].unit_number) is correct and not used by SATA disks.
393 choices: [ 'ide', 'sata' ]
394 default: ide
395 controller_number:
396 type: int
397 description:
398 - For O(cdrom[].controller_type=ide), valid value is 0 or 1.
399 - For O(cdrom[].controller_type=sata), valid value is 0 to 3.
400 unit_number:
401 type: int
402 description:
403 - For O(cdrom[].controller_type=ide), valid value is 0 or 1.
404 - For O(cdrom[].controller_type=sata), valid value is 0 to 29.
405 - O(cdrom[].controller_number) and O(cdrom[].unit_number) are mandatory attributes.
406 state:
407 type: str
408 description:
409 - If set to V(absent), then the specified CD-ROM will be removed.
410 choices: [ 'present', 'absent' ]
411 default: present
412 resource_pool:
413 description:
414 - Use the given resource pool for virtual machine operation.
415 - Resource pool should be child of the selected host parent.
416 - When not specified I(Resources) is taken as default value.
417 type: str
418 wait_for_ip_address:
419 description:
420 - Wait until vCenter detects an IP address for the virtual machine.
421 - This requires vmware-tools (vmtoolsd) to properly work after creation.
422 - "vmware-tools needs to be installed on the given virtual machine in order to work with this parameter."
423 default: false
424 type: bool
425 wait_for_ip_address_timeout:
426 description:
427 - Define a timeout (in seconds) for the wait_for_ip_address parameter.
428 default: '300'
429 type: int
430 wait_for_customization_timeout:
431 description:
432 - Define a timeout (in seconds) for the wait_for_customization parameter.
433 - Be careful when setting this value since the time guest customization took may differ among guest OSes.
434 default: '3600'
435 type: int
436 wait_for_customization:
437 description:
438 - Wait until vCenter detects all guest customizations as successfully completed.
439 - When enabled, the VM will automatically be powered on.
440 - "If vCenter does not detect guest customization start or succeed, failed events after time
441 O(wait_for_customization_timeout) parameter specified, warning message will be printed and task result is fail."
442 default: false
443 type: bool
444 state_change_timeout:
445 description:
446 - If the O(state=shutdownguest), by default the module will return immediately after sending the shutdown signal.
447 - If this argument is set to a positive integer, the module will instead wait for the virtual machine to reach the poweredoff state.
448 - The value sets a timeout in seconds for the module to wait for the state change.
449 default: 0
450 type: int
451 snapshot_src:
452 description:
453 - Name of the existing snapshot to use to create a clone of a virtual machine.
454 - While creating linked clone using O(linked_clone) parameter, this parameter is required.
455 type: str
456 linked_clone:
457 description:
458 - Whether to create a linked clone from the snapshot specified.
459 - If specified, then O(snapshot_src) is required parameter.
460 default: false
461 type: bool
462 force:
463 description:
464 - Ignore warnings and complete the actions.
465 - This parameter is useful while removing virtual machine which is powered on state.
466 - 'This module reflects the VMware vCenter API and UI workflow, as such, in some cases the `force` flag will
467 be mandatory to perform the action to ensure you are certain the action has to be taken, no matter what the consequence.
468 This is specifically the case for removing a powered on the virtual machine when O(state=absent).'
469 default: false
470 type: bool
471 delete_from_inventory:
472 description:
473 - Whether to delete Virtual machine from inventory or delete from disk.
474 default: false
475 type: bool
476 datacenter:
477 description:
478 - Destination datacenter for the deploy operation.
479 default: ha-datacenter
480 type: str
481 cluster:
482 description:
483 - The cluster name where the virtual machine will run.
484 - This is a required parameter, if O(esxi_hostname) is not set.
485 - O(esxi_hostname) and O(cluster) are mutually exclusive parameters.
486 type: str
487 esxi_hostname:
488 description:
489 - The ESXi hostname where the virtual machine will run.
490 - This is a required parameter, if O(cluster) is not set.
491 - O(esxi_hostname) and O(cluster) are mutually exclusive parameters.
492 type: str
493 advanced_settings:
494 description:
495 - Define a list of advanced settings to be added to the VMX config.
496 - An advanced settings object takes the two fields C(key) and C(value).
497 - Incorrect key and values will be ignored.
498 elements: dict
499 type: list
500 default: []
501 annotation:
502 description:
503 - A note or annotation to include in the virtual machine.
504 type: str
505 aliases: [ 'notes' ]
506 customvalues:
507 description:
508 - Define a list of custom values to set on virtual machine.
509 - A custom value object takes the two fields C(key) and C(value).
510 - Incorrect key and values will be ignored.
511 elements: dict
512 type: list
513 default: []
514 networks:
515 description:
516 - A list of networks (in the order of the NICs).
517 - Removing NICs is not allowed, while reconfiguring the virtual machine.
518 - The I(type), I(ip), I(netmask), I(gateway), I(domain), I(dns_servers) options don't set to a guest when creating a blank new virtual machine.
519 They are set by the customization via vmware-tools.
520 If you want to set the value of the options to a guest, you need to clone from a template with installed OS and vmware-tools (also Perl when Linux).
521 type: list
522 default: []
523 elements: dict
524 suboptions:
525 name:
526 type: str
527 description:
528 - Name of the portgroup or distributed virtual portgroup for this interface.
529 - This is required if C(vlan) isn't defined.
530 - When specifying distributed virtual portgroup make sure given O(esxi_hostname) or O(cluster) is associated with it.
531 vlan:
532 type: int
533 description:
534 - VLAN number for this interface.
535 - This is required if C(name) isn't defined.
536 device_type:
537 type: str
538 description:
539 - Virtual network device.
540 - Valid value can be one of C(e1000), C(e1000e), C(pcnet32), C(vmxnet2), C(vmxnet3), C(sriov).
541 - C(vmxnet3) is default.
542 - Optional per entry.
543 - Used for virtual hardware.
544 mac:
545 type: str
546 description:
547 - Customize MAC address.
548 - Optional per entry.
549 - Used for virtual hardware.
550 dvswitch_name:
551 type: str
552 description:
553 - Name of the distributed vSwitch.
554 - Optional per entry.
555 - Used for virtual hardware.
556 type:
557 type: str
558 description:
559 - Type of IP assignment.
560 - Valid values are one of C(dhcp), C(static).
561 - C(dhcp) is default.
562 - Optional per entry.
563 - Used for OS customization.
564 ip:
565 type: str
566 description:
567 - Static IP address. Implies C(type=static).
568 - Optional per entry.
569 - Used for OS customization.
570 netmask:
571 type: str
572 description:
573 - Static netmask required for C(ip).
574 - Optional per entry.
575 - Used for OS customization.
576 gateway:
577 type: str
578 description:
579 - Static gateway.
580 - Optional per entry.
581 - Used for OS customization.
582 typev6:
583 version_added: '4.1.0'
584 type: str
585 description:
586 - Type of IP assignment.
587 - Valid values are one of C(dhcp), C(static).
588 - C(dhcp) is default.
589 - Optional per entry.
590 - Used for OS customization.
591 ipv6:
592 version_added: '4.1.0'
593 type: str
594 description:
595 - Static IP address. Implies C(type=static).
596 - Optional per entry.
597 - Used for OS customization.
598 netmaskv6:
599 version_added: '4.1.0'
600 type: str
601 description:
602 - Static netmask required for C(ip).
603 - Optional per entry.
604 - Used for OS customization.
605 gatewayv6:
606 version_added: '4.1.0'
607 type: str
608 description:
609 - Static gateway.
610 - Optional per entry.
611 - Used for OS customization.
612 dns_servers:
613 type: str
614 description:
615 - DNS servers for this network interface (Windows).
616 - Optional per entry.
617 - Used for OS customization.
618 domain:
619 type: str
620 description:
621 - Domain name for this network interface (Windows).
622 - Optional per entry.
623 - Used for OS customization.
624 connected:
625 type: bool
626 description:
627 - Indicates whether the NIC is currently connected.
628 start_connected:
629 type: bool
630 description:
631 - Specifies whether or not to connect the device when the virtual machine starts.
632 customization:
633 description:
634 - Parameters for OS customization when cloning from the template or the virtual machine, or apply to the existing virtual machine directly.
635 - Not all operating systems are supported for customization with respective vCenter version,
636 please check VMware documentation for respective OS customization.
637 - For supported customization operating system matrix, (see U(http://partnerweb.vmware.com/programs/guestOS/guest-os-customization-matrix.pdf))
638 - Linux based OSes requires Perl package to be installed for OS customizations.
639 suboptions:
640 existing_vm:
641 type: bool
642 description:
643 - If set to V(true), do OS customization on the specified virtual machine directly.
644 - Common for Linux and Windows customization.
645 dns_servers:
646 type: list
647 elements: str
648 description:
649 - List of DNS servers to configure.
650 - Common for Linux and Windows customization.
651 dns_suffix:
652 type: list
653 elements: str
654 description:
655 - List of domain suffixes, also known as DNS search path.
656 - Default C(domain) parameter.
657 - Common for Linux and Windows customization.
658 domain:
659 type: str
660 description:
661 - DNS domain name to use.
662 - Common for Linux and Windows customization.
663 hostname:
664 type: str
665 description:
666 - Computer hostname.
667 - Default is shortened O(name) parameter.
668 - Allowed characters are alphanumeric (uppercase and lowercase) and minus, rest of the characters are dropped as per RFC 952.
669 - Common for Linux and Windows customization.
670 timezone:
671 type: str
672 description:
673 - Timezone.
674 - See List of supported time zones for different vSphere versions in Linux/Unix.
675 - Common for Linux and Windows customization.
676 - L(Windows, https://msdn.microsoft.com/en-us/library/ms912391.aspx).
677 hwclockUTC:
678 type: bool
679 description:
680 - Specifies whether the hardware clock is in UTC or local time.
681 - Specific to Linux customization.
682 script_text:
683 type: str
684 description:
685 - Script to run with shebang.
686 - Needs to be enabled in vmware tools with vmware-toolbox-cmd config set deployPkg enable-custom-scripts true
687 - https://docs.vmware.com/en/VMware-vSphere/7.0/com.vmware.vsphere.vm_admin.doc/GUID-9A5093A5-C54F-4502-941B-3F9C0F573A39.html
688 - Specific to Linux customization.
689 version_added: '3.1.0'
690 autologon:
691 type: bool
692 description:
693 - Auto logon after virtual machine customization.
694 - Specific to Windows customization.
695 autologoncount:
696 type: int
697 description:
698 - Number of autologon after reboot.
699 - Specific to Windows customization.
700 - Ignored if O(customization.autologon) is unset or set to O(customization.autologon=false).
701 - If unset, 1 will be used.
702 domainadmin:
703 type: str
704 description:
705 - User used to join in AD domain.
706 - Required if O(customization.joindomain) specified.
707 - Specific to Windows customization.
708 domainadminpassword:
709 type: str
710 description:
711 - Password used to join in AD domain.
712 - Required if O(customization.joindomain) specified.
713 - Specific to Windows customization.
714 fullname:
715 type: str
716 description:
717 - Server owner name.
718 - Specific to Windows customization.
719 - If unset, "Administrator" will be used as a fall-back.
720 joindomain:
721 type: str
722 description:
723 - AD domain to join.
724 - Not compatible with O(customization.joinworkgroup).
725 - Specific to Windows customization.
726 joinworkgroup:
727 type: str
728 description:
729 - Workgroup to join.
730 - Not compatible with O(customization.joindomain).
731 - Specific to Windows customization.
732 - If unset, "WORKGROUP" will be used as a fall-back.
733 orgname:
734 type: str
735 description:
736 - Organization name.
737 - Specific to Windows customization.
738 - If unset, "ACME" will be used as a fall-back.
739 password:
740 type: str
741 description:
742 - Local administrator password.
743 - If not defined, the password will be set to blank (that is, no password).
744 - Specific to Windows customization.
745 productid:
746 type: str
747 description:
748 - Product ID.
749 - Specific to Windows customization.
750 runonce:
751 type: list
752 elements: str
753 description:
754 - List of commands to run at first user logon.
755 - Specific to Windows customization.
756 domain_ou:
757 type: str
758 description:
759 - The full LDAP path name of the OU to which the computer belongs.
760 - Specific to Windows customization.
761 - Work for vSphere 8.0U2 and above
762 type: dict
763 default: {}
764 vapp_properties:
765 description:
766 - A list of vApp properties.
767 - 'For full list of attributes and types refer to: U(https://code.vmware.com/apis/704/vsphere/vim.vApp.PropertyInfo.html)'
768 type: list
769 default: []
770 elements: dict
771 suboptions:
772 id:
773 type: str
774 description:
775 - Property ID.
776 - Required per entry.
777 value:
778 type: str
779 description:
780 - Property value.
781 type:
782 type: str
783 description:
784 - Value type, string type by default.
785 operation:
786 type: str
787 description:
788 - The C(remove) attribute is required only when removing properties.
789 customization_spec:
790 description:
791 - Unique name identifying the requested customization specification.
792 - If set, then overrides O(customization) parameter values.
793 type: str
794 datastore:
795 description:
796 - Specify datastore or datastore cluster to provision virtual machine.
797 - This parameter takes precedence over O(disk[].datastore) parameter.
798 - This parameter can be used to override datastore or datastore cluster setting
799 of the virtual machine when deployed from the template.
800 - Please see example for more usage.
801 type: str
802 convert:
803 description:
804 - Specify convert disk type while cloning template or virtual machine.
805 choices: [ 'thin', 'thick', 'eagerzeroedthick' ]
806 type: str
807 extends_documentation_fragment:
808 - vmware.vmware.base_options
809
810 '''
811
812 EXAMPLES = r'''
813 - name: Create a virtual machine on given ESXi hostname
814 community.vmware.vmware_guest:
815 hostname: "{{ vcenter_hostname }}"
816 username: "{{ vcenter_username }}"
817 password: "{{ vcenter_password }}"
818 folder: /DC1/vm/
819 name: test_vm_0001
820 state: poweredon
821 guest_id: centos64Guest
822 # This is hostname of particular ESXi server on which user wants VM to be deployed
823 esxi_hostname: "{{ esxi_hostname }}"
824 disk:
825 - size_gb: 10
826 type: thin
827 datastore: datastore1
828 hardware:
829 memory_mb: 512
830 num_cpus: 4
831 scsi: paravirtual
832 networks:
833 - name: VM Network
834 mac: aa:bb:dd:aa:00:14
835 ip: 10.10.10.100
836 netmask: 255.255.255.0
837 device_type: vmxnet3
838 wait_for_ip_address: true
839 wait_for_ip_address_timeout: 600
840 delegate_to: localhost
841 register: deploy_vm
842
843 - name: Create a virtual machine from a template
844 community.vmware.vmware_guest:
845 hostname: "{{ vcenter_hostname }}"
846 username: "{{ vcenter_username }}"
847 password: "{{ vcenter_password }}"
848 folder: /testvms
849 name: testvm_2
850 state: poweredon
851 template: template_el7
852 disk:
853 - size_gb: 10
854 type: thin
855 datastore: g73_datastore
856 # Add another disk from an existing VMDK
857 - filename: "[datastore1] testvms/testvm_2_1/testvm_2_1.vmdk"
858 hardware:
859 memory_mb: 512
860 num_cpus: 6
861 num_cpu_cores_per_socket: 3
862 scsi: paravirtual
863 memory_reservation_lock: true
864 mem_limit: 8096
865 mem_reservation: 4096
866 cpu_shares_level: "high"
867 mem_shares_level: "high"
868 cpu_limit: 8096
869 cpu_reservation: 4096
870 max_connections: 5
871 hotadd_cpu: true
872 hotremove_cpu: true
873 hotadd_memory: false
874 version: 12 # Hardware version of virtual machine
875 boot_firmware: "efi"
876 cdrom:
877 - controller_number: 0
878 unit_number: 0
879 state: present
880 type: iso
881 iso_path: "[datastore1] livecd.iso"
882 networks:
883 - name: VM Network
884 mac: aa:bb:dd:aa:00:14
885 wait_for_ip_address: true
886 delegate_to: localhost
887 register: deploy
888
889 - name: Clone a virtual machine from Windows template and customize
890 community.vmware.vmware_guest:
891 hostname: "{{ vcenter_hostname }}"
892 username: "{{ vcenter_username }}"
893 password: "{{ vcenter_password }}"
894 datacenter: datacenter1
895 cluster: cluster
896 name: testvm-2
897 template: template_windows
898 networks:
899 - name: VM Network
900 ip: 192.168.1.100
901 netmask: 255.255.255.0
902 gateway: 192.168.1.1
903 mac: aa:bb:dd:aa:00:14
904 domain: my_domain
905 dns_servers:
906 - 192.168.1.1
907 - 192.168.1.2
908 - vlan: 1234
909 type: dhcp
910 customization:
911 autologon: true
912 dns_servers:
913 - 192.168.1.1
914 - 192.168.1.2
915 domain: my_domain
916 password: new_vm_password
917 runonce:
918 - powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows\Temp\ConfigureRemotingForAnsible.ps1 -ForceNewSSLCert -EnableCredSSP
919 delegate_to: localhost
920
921 - name: Clone a virtual machine from Linux template and customize
922 community.vmware.vmware_guest:
923 hostname: "{{ vcenter_hostname }}"
924 username: "{{ vcenter_username }}"
925 password: "{{ vcenter_password }}"
926 datacenter: "{{ datacenter }}"
927 state: present
928 folder: /DC1/vm
929 template: "{{ template }}"
930 name: "{{ vm_name }}"
931 cluster: DC1_C1
932 networks:
933 - name: VM Network
934 ip: 192.168.10.11
935 netmask: 255.255.255.0
936 wait_for_ip_address: true
937 customization:
938 domain: "{{ guest_domain }}"
939 dns_servers:
940 - 8.9.9.9
941 - 7.8.8.9
942 dns_suffix:
943 - example.com
944 - example2.com
945 script_text: |
946 #!/bin/bash
947 touch /tmp/touch-from-playbook
948 delegate_to: localhost
949
950 - name: Rename a virtual machine (requires the virtual machine's uuid)
951 community.vmware.vmware_guest:
952 hostname: "{{ vcenter_hostname }}"
953 username: "{{ vcenter_username }}"
954 password: "{{ vcenter_password }}"
955 uuid: "{{ vm_uuid }}"
956 name: new_name
957 state: present
958 delegate_to: localhost
959
960 - name: Remove a virtual machine by uuid
961 community.vmware.vmware_guest:
962 hostname: "{{ vcenter_hostname }}"
963 username: "{{ vcenter_username }}"
964 password: "{{ vcenter_password }}"
965 uuid: "{{ vm_uuid }}"
966 state: absent
967 delegate_to: localhost
968
969 - name: Remove a virtual machine from inventory
970 community.vmware.vmware_guest:
971 hostname: "{{ vcenter_hostname }}"
972 username: "{{ vcenter_username }}"
973 password: "{{ vcenter_password }}"
974 name: vm_name
975 delete_from_inventory: true
976 state: absent
977 delegate_to: localhost
978
979 - name: Manipulate vApp properties
980 community.vmware.vmware_guest:
981 hostname: "{{ vcenter_hostname }}"
982 username: "{{ vcenter_username }}"
983 password: "{{ vcenter_password }}"
984 name: vm_name
985 state: present
986 vapp_properties:
987 - id: remoteIP
988 category: Backup
989 label: Backup server IP
990 type: string
991 value: 10.10.10.1
992 - id: old_property
993 operation: remove
994 delegate_to: localhost
995
996 - name: Set powerstate of a virtual machine to poweroff by using UUID
997 community.vmware.vmware_guest:
998 hostname: "{{ vcenter_hostname }}"
999 username: "{{ vcenter_username }}"
1000 password: "{{ vcenter_password }}"
1001 uuid: "{{ vm_uuid }}"
1002 state: poweredoff
1003 delegate_to: localhost
1004
1005 - name: Deploy a virtual machine in a datastore different from the datastore of the template
1006 community.vmware.vmware_guest:
1007 hostname: "{{ vcenter_hostname }}"
1008 username: "{{ vcenter_username }}"
1009 password: "{{ vcenter_password }}"
1010 name: "{{ vm_name }}"
1011 state: present
1012 template: "{{ template_name }}"
1013 # Here datastore can be different which holds template
1014 datastore: "{{ virtual_machine_datastore }}"
1015 hardware:
1016 memory_mb: 512
1017 num_cpus: 2
1018 scsi: paravirtual
1019 delegate_to: localhost
1020
1021 - name: Create a diskless VM
1022 community.vmware.vmware_guest:
1023 hostname: "{{ vcenter_hostname }}"
1024 username: "{{ vcenter_username }}"
1025 password: "{{ vcenter_password }}"
1026 datacenter: "{{ dc1 }}"
1027 state: poweredoff
1028 cluster: "{{ ccr1 }}"
1029 name: diskless_vm
1030 folder: /Asia-Datacenter1/vm
1031 guest_id: centos64Guest
1032 datastore: "{{ ds1 }}"
1033 hardware:
1034 memory_mb: 1024
1035 num_cpus: 2
1036 num_cpu_cores_per_socket: 1
1037
1038 - name: Create a VM with multiple disks of different disk controller types
1039 community.vmware.vmware_guest:
1040 hostname: "{{ vcenter_hostname }}"
1041 username: "{{ vcenter_username }}"
1042 password: "{{ vcenter_password }}"
1043 folder: /DC1/vm/
1044 name: test_vm_multi_disks
1045 state: poweredoff
1046 guest_id: centos64Guest
1047 datastore: datastore1
1048 disk:
1049 - size_gb: 10
1050 controller_type: 'nvme'
1051 controller_number: 0
1052 unit_number: 0
1053 - size_gb: 10
1054 controller_type: 'paravirtual'
1055 controller_number: 0
1056 unit_number: 1
1057 - size_gb: 10
1058 controller_type: 'sata'
1059 controller_number: 0
1060 unit_number: 2
1061 hardware:
1062 memory_mb: 512
1063 num_cpus: 4
1064 version: 14
1065 networks:
1066 - name: VM Network
1067 device_type: vmxnet3
1068 delegate_to: localhost
1069 register: deploy_vm
1070
1071 - name: Create a VM with NVDIMM device
1072 community.vmware.vmware_guest:
1073 hostname: "{{ vcenter_hostname }}"
1074 username: "{{ vcenter_username }}"
1075 password: "{{ vcenter_password }}"
1076 folder: /DC1/vm/
1077 name: test_vm_nvdimm
1078 state: poweredoff
1079 guest_id: centos7_64Guest
1080 datastore: datastore1
1081 hardware:
1082 memory_mb: 512
1083 num_cpus: 4
1084 version: 14
1085 networks:
1086 - name: VM Network
1087 device_type: vmxnet3
1088 nvdimm:
1089 state: present
1090 size_mb: 2048
1091 delegate_to: localhost
1092 register: deploy_vm
1093 '''
1094
1095 RETURN = r'''
1096 instance:
1097 description: metadata about the new virtual machine
1098 returned: always
1099 type: dict
1100 sample: None
1101 '''
1102
1103 import re
1104 import time
1105 import string
1106
1107 try:
1108 from pyVmomi import vim, vmodl
1109 except ImportError:
1110 pass
1111
1112 from ansible.module_utils.basic import AnsibleModule
1113 from ansible.module_utils.common.network import is_mac
1114 from ansible.module_utils.common.text.converters import to_text, to_native
1115 from ansible_collections.community.vmware.plugins.module_utils.vmware import (
1116 find_obj,
1117 gather_vm_facts,
1118 get_all_objs,
1119 compile_folder_path_for_object,
1120 serialize_spec,
1121 set_vm_power_state,
1122 PyVmomi,
1123 find_dvs_by_name,
1124 find_dvspg_by_name,
1125 wait_for_vm_ip,
1126 quote_obj_name,
1127 )
1128 from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec
1129 from ansible_collections.community.vmware.plugins.module_utils.vm_device_helper import PyVmomiDeviceHelper
1130 from ansible_collections.community.vmware.plugins.module_utils.vmware_spbm import SPBM
1131
1132
1133 class PyVmomiCache(PyVmomi):
1134 """ This class caches references to objects which are requested multiples times but not modified """
1135
1136 def __init__(self, content, dc_name=None):
1137 self.content = content
1138 self.dc_name = dc_name
1139 self.networks = {}
1140 self.clusters = {}
1141 self.esx_hosts = {}
1142 self.parent_datacenters = {}
1143
1144 def find_obj(self, content, types, name, confine_to_datacenter=True):
1145 """ Wrapper around find_obj to set datacenter context """
1146 result = find_obj(content, types, name)
1147 if result and confine_to_datacenter:
1148 if to_text(self.get_parent_datacenter(result).name) != to_text(self.dc_name):
1149 result = None
1150 objects = self.get_all_objs(content, types, confine_to_datacenter=True)
1151 for obj in objects:
1152 if name is None or to_text(obj.name) == to_text(name):
1153 return obj
1154 return result
1155
1156 def get_all_objs(self, content, types, confine_to_datacenter=True):
1157 """ Wrapper around get_all_objs to set datacenter context """
1158 objects = get_all_objs(content, types)
1159 if confine_to_datacenter:
1160 if hasattr(objects, 'items'):
1161 # resource pools come back as a dictionary
1162 # make a copy
1163 for k, v in tuple(objects.items()):
1164 parent_dc = self.get_parent_datacenter(k)
1165 if parent_dc.name != self.dc_name:
1166 del objects[k]
1167 else:
1168 # everything else should be a list
1169 objects = [x for x in objects if self.get_parent_datacenter(x).name == self.dc_name]
1170
1171 return objects
1172
1173 def get_network(self, network_name):
1174 network_name = quote_obj_name(network_name)
1175
1176 if network_name not in self.networks:
1177 networks = self.find_network_by_name(network_name)
1178 if len(networks) == 1:
1179 self.networks[network_name] = networks[0]
1180 else:
1181 self.networks[network_name] = self.find_obj(self.content, [vim.Network], network_name)
1182
1183 return self.networks[network_name]
1184
1185 def get_cluster(self, cluster):
1186 if cluster not in self.clusters:
1187 self.clusters[cluster] = self.find_obj(self.content, [vim.ClusterComputeResource], cluster)
1188
1189 return self.clusters[cluster]
1190
1191 def get_esx_host(self, host):
1192 if host not in self.esx_hosts:
1193 self.esx_hosts[host] = self.find_obj(self.content, [vim.HostSystem], host)
1194
1195 return self.esx_hosts[host]
1196
1197 def get_parent_datacenter(self, obj):
1198 """ Walk the parent tree to find the objects datacenter """
1199 if isinstance(obj, vim.Datacenter):
1200 return obj
1201 if obj in self.parent_datacenters:
1202 return self.parent_datacenters[obj]
1203 datacenter = None
1204 while True:
1205 if not hasattr(obj, 'parent'):
1206 break
1207 obj = obj.parent
1208 if isinstance(obj, vim.Datacenter):
1209 datacenter = obj
1210 break
1211 self.parent_datacenters[obj] = datacenter
1212 return datacenter
1213
1214
1215 class PyVmomiHelper(PyVmomi):
1216 def __init__(self, module):
1217 super(PyVmomiHelper, self).__init__(module)
1218 self.device_helper = PyVmomiDeviceHelper(self.module)
1219 self.configspec = None
1220 self.relospec = None
1221 self.change_detected = False # a change was detected and needs to be applied through reconfiguration
1222 self.change_applied = False # a change was applied meaning at least one task succeeded
1223 self.tracked_changes = {} # dict of changes made or would-be-made in check mode, updated when change_applied is set
1224 self.customspec = None
1225 self.cache = PyVmomiCache(self.content, dc_name=self.params['datacenter'])
1226
1227 def gather_facts(self, vm):
1228 return gather_vm_facts(self.content, vm)
1229
1230 def remove_vm(self, vm, delete_from_inventory=False):
1231 # https://www.vmware.com/support/developer/converter-sdk/conv60_apireference/vim.ManagedEntity.html#destroy
1232 if vm.summary.runtime.powerState.lower() == 'poweredon':
1233 self.module.fail_json(msg="Virtual machine %s found in 'powered on' state, "
1234 "please use 'force' parameter to remove or poweroff VM "
1235 "and try removing VM again." % vm.name)
1236 # Delete VM from Inventory
1237 if delete_from_inventory:
1238 try:
1239 vm.UnregisterVM()
1240 except (vim.fault.TaskInProgress,
1241 vmodl.RuntimeFault) as e:
1242 return {'changed': self.change_applied, 'failed': True, 'msg': e.msg, 'op': 'UnregisterVM'}
1243 self.change_applied = True
1244 return {'changed': self.change_applied, 'failed': False}
1245 # Delete VM from Disk
1246 task = vm.Destroy()
1247 error_msg = self.wait_for_task(task)
1248 if task.info.state == 'error':
1249 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'destroy'}
1250 else:
1251 return {'changed': self.change_applied, 'failed': False}
1252
1253 def configure_guestid(self, vm_obj, vm_creation=False):
1254 # guest_id is not required when using templates
1255 if self.params['template']:
1256 return
1257
1258 # guest_id is only mandatory on VM creation
1259 if vm_creation and self.params['guest_id'] is None:
1260 self.module.fail_json(msg="guest_id attribute is mandatory for VM creation")
1261
1262 if self.params['guest_id'] and \
1263 (vm_obj is None or self.params['guest_id'].lower() != vm_obj.summary.config.guestId.lower()):
1264 self.change_detected = True
1265 self.configspec.guestId = self.params['guest_id']
1266
1267 def configure_resource_alloc_info(self, vm_obj):
1268 """
1269 Function to configure resource allocation information about virtual machine
1270 :param vm_obj: VM object in case of reconfigure, None in case of deploy
1271 :return: None
1272 """
1273 rai_change_detected = False
1274 memory_allocation = vim.ResourceAllocationInfo()
1275 cpu_allocation = vim.ResourceAllocationInfo()
1276
1277 memory_shares_info = vim.SharesInfo()
1278 cpu_shares_info = vim.SharesInfo()
1279
1280 mem_shares_level = self.params['hardware']['mem_shares_level']
1281 if mem_shares_level is not None:
1282 memory_shares_info.level = mem_shares_level
1283 memory_allocation.shares = memory_shares_info
1284
1285 if vm_obj is None or \
1286 memory_allocation.shares.level != vm_obj.config.memoryAllocation.shares.level:
1287 rai_change_detected = True
1288
1289 cpu_shares_level = self.params['hardware']['cpu_shares_level']
1290 if cpu_shares_level is not None:
1291 cpu_shares_info.level = cpu_shares_level
1292 cpu_allocation.shares = cpu_shares_info
1293 if vm_obj is None or \
1294 cpu_allocation.shares.level != vm_obj.config.cpuAllocation.shares.level:
1295 rai_change_detected = True
1296
1297 mem_shares = self.params['hardware']['mem_shares']
1298 if mem_shares is not None:
1299 memory_shares_info.level = 'custom'
1300 memory_shares_info.shares = mem_shares
1301 memory_allocation.shares = memory_shares_info
1302 if vm_obj is None or \
1303 memory_allocation.shares != vm_obj.config.memoryAllocation.shares:
1304 rai_change_detected = True
1305
1306 cpu_shares = self.params['hardware']['cpu_shares']
1307 if cpu_shares is not None:
1308 cpu_shares_info.level = 'custom'
1309 cpu_shares_info.shares = cpu_shares
1310 cpu_allocation.shares = cpu_shares_info
1311 if vm_obj is None or \
1312 cpu_allocation.shares != vm_obj.config.cpuAllocation.shares:
1313 rai_change_detected = True
1314
1315 mem_limit = self.params['hardware']['mem_limit']
1316 if mem_limit is not None:
1317 memory_allocation.limit = mem_limit
1318 if vm_obj is None or \
1319 memory_allocation.limit != vm_obj.config.memoryAllocation.limit:
1320 rai_change_detected = True
1321
1322 mem_reservation = self.params['hardware']['mem_reservation']
1323 if mem_reservation is not None:
1324 memory_allocation.reservation = mem_reservation
1325 if vm_obj is None or \
1326 memory_allocation.reservation != vm_obj.config.memoryAllocation.reservation:
1327 rai_change_detected = True
1328
1329 cpu_limit = self.params['hardware']['cpu_limit']
1330 if cpu_limit is not None:
1331 cpu_allocation.limit = cpu_limit
1332 if vm_obj is None or \
1333 cpu_allocation.limit != vm_obj.config.cpuAllocation.limit:
1334 rai_change_detected = True
1335
1336 cpu_reservation = self.params['hardware']['cpu_reservation']
1337 if cpu_reservation is not None:
1338 cpu_allocation.reservation = cpu_reservation
1339 if vm_obj is None or \
1340 cpu_allocation.reservation != vm_obj.config.cpuAllocation.reservation:
1341 rai_change_detected = True
1342
1343 if rai_change_detected:
1344 self.configspec.memoryAllocation = memory_allocation
1345 self.configspec.cpuAllocation = cpu_allocation
1346 self.change_detected = True
1347
1348 def configure_cpu_and_memory(self, vm_obj, vm_creation=False):
1349 # set cpu/memory/etc
1350 num_cpus = self.params['hardware']['num_cpus']
1351 if num_cpus is not None:
1352 # check VM power state and cpu hot-add/hot-remove state before re-config VM
1353 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1354 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and not self.module.check_mode:
1355 if not vm_obj.config.cpuHotRemoveEnabled and num_cpus < vm_obj.config.hardware.numCPU:
1356 self.module.fail_json(msg="Configured cpu number is less than the cpu number of the VM, "
1357 "cpuHotRemove is not enabled")
1358 if not vm_obj.config.cpuHotAddEnabled and num_cpus > vm_obj.config.hardware.numCPU:
1359 self.module.fail_json(msg="Configured cpu number is more than the cpu number of the VM, "
1360 "cpuHotAdd is not enabled")
1361
1362 num_cpu_cores_per_socket = self.params['hardware']['num_cpu_cores_per_socket']
1363 if num_cpu_cores_per_socket is not None:
1364 if num_cpus % num_cpu_cores_per_socket != 0:
1365 self.module.fail_json(msg="hardware.num_cpus attribute should be a multiple "
1366 "of hardware.num_cpu_cores_per_socket")
1367 if vm_obj is None or num_cpu_cores_per_socket != vm_obj.config.hardware.numCoresPerSocket:
1368 self.change_detected = True
1369 self.configspec.numCoresPerSocket = num_cpu_cores_per_socket
1370 if vm_obj is None or num_cpus != vm_obj.config.hardware.numCPU:
1371 self.change_detected = True
1372 self.configspec.numCPUs = num_cpus
1373 # num_cpu is mandatory for VM creation
1374 elif vm_creation and not self.params['template']:
1375 self.module.fail_json(msg="hardware.num_cpus attribute is mandatory for VM creation")
1376
1377 memory_mb = self.params['hardware']['memory_mb']
1378 if memory_mb is not None:
1379 # check VM power state and memory hotadd state before re-config VM
1380 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn:
1381 if vm_obj.config.memoryHotAddEnabled and memory_mb < vm_obj.config.hardware.memoryMB:
1382 self.module.fail_json(msg="Configured memory is less than memory size of the VM, "
1383 "operation is not supported")
1384 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1385 elif not vm_obj.config.memoryHotAddEnabled and memory_mb != vm_obj.config.hardware.memoryMB and not self.module.check_mode:
1386 self.module.fail_json(msg="memoryHotAdd is not enabled")
1387 if vm_obj is None or memory_mb != vm_obj.config.hardware.memoryMB:
1388 self.change_detected = True
1389 self.configspec.memoryMB = memory_mb
1390 # memory_mb is mandatory for VM creation
1391 elif vm_creation and not self.params['template']:
1392 self.module.fail_json(msg="hardware.memory_mb attribute is mandatory for VM creation")
1393
1394 hotadd_memory = self.params['hardware']['hotadd_memory']
1395 if hotadd_memory is not None:
1396 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1397 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
1398 vm_obj.config.memoryHotAddEnabled != hotadd_memory and not self.module.check_mode:
1399 self.module.fail_json(msg="Configure hotadd memory operation is not supported when VM is power on")
1400 if vm_obj is None or hotadd_memory != vm_obj.config.memoryHotAddEnabled:
1401 self.change_detected = True
1402 self.configspec.memoryHotAddEnabled = hotadd_memory
1403
1404 hotadd_cpu = self.params['hardware']['hotadd_cpu']
1405 if hotadd_cpu is not None:
1406 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1407 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
1408 vm_obj.config.cpuHotAddEnabled != hotadd_cpu and not self.module.check_mode:
1409 self.module.fail_json(msg="Configure hotadd cpu operation is not supported when VM is power on")
1410 if vm_obj is None or hotadd_cpu != vm_obj.config.cpuHotAddEnabled:
1411 self.change_detected = True
1412 self.configspec.cpuHotAddEnabled = hotadd_cpu
1413
1414 hotremove_cpu = self.params['hardware']['hotremove_cpu']
1415 if hotremove_cpu is not None:
1416 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1417 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
1418 vm_obj.config.cpuHotRemoveEnabled != hotremove_cpu and not self.module.check_mode:
1419 self.module.fail_json(msg="Configure hotremove cpu operation is not supported when VM is power on")
1420 if vm_obj is None or hotremove_cpu != vm_obj.config.cpuHotRemoveEnabled:
1421 self.change_detected = True
1422 self.configspec.cpuHotRemoveEnabled = hotremove_cpu
1423
1424 memory_reservation_lock = self.params['hardware']['memory_reservation_lock']
1425 if memory_reservation_lock is not None:
1426 if vm_obj is None or memory_reservation_lock != vm_obj.config.memoryReservationLockedToMax:
1427 self.change_detected = True
1428 self.configspec.memoryReservationLockedToMax = memory_reservation_lock
1429
1430 vpmc_enabled = self.params['hardware']['vpmc_enabled']
1431 if vpmc_enabled is not None:
1432 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1433 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
1434 vm_obj.config.vPMCEnabled != vpmc_enabled and not self.module.check_mode:
1435 self.module.fail_json(msg="Configure vPMC cpu operation is not supported when VM is power on")
1436 if vm_obj is None or vpmc_enabled != vm_obj.config.vPMCEnabled:
1437 self.change_detected = True
1438 self.configspec.vPMCEnabled = vpmc_enabled
1439
1440 boot_firmware = self.params['hardware']['boot_firmware']
1441 if boot_firmware is not None:
1442 # boot firmware re-config can cause boot issue
1443 if vm_obj is not None:
1444 return
1445 self.configspec.firmware = boot_firmware
1446 self.change_detected = True
1447
1448 def sanitize_cdrom_params(self):
1449 cdrom_specs = []
1450 expected_cdrom_spec = self.params.get('cdrom')
1451 if expected_cdrom_spec:
1452 for cdrom_spec in expected_cdrom_spec:
1453 cdrom_spec['controller_type'] = cdrom_spec.get('controller_type')
1454 cdrom_spec['state'] = cdrom_spec.get('state')
1455
1456 if cdrom_spec['state'] == 'present':
1457 # set CDROM type is 'client' by default
1458 cdrom_spec['type'] = cdrom_spec.get('type')
1459 if cdrom_spec['type'] == 'iso' and not cdrom_spec.get('iso_path'):
1460 self.module.fail_json(msg="cdrom.iso_path is mandatory when cdrom.type is set to iso.")
1461
1462 if 'controller_number' not in cdrom_spec or 'unit_number' not in cdrom_spec:
1463 self.module.fail_json(msg="'cdrom.controller_number' and 'cdrom.unit_number' are required"
1464 " parameters when configure CDROM list.")
1465
1466 cdrom_ctl_num = int(cdrom_spec.get('controller_number'))
1467 cdrom_ctl_unit_num = int(cdrom_spec.get('unit_number'))
1468
1469 if cdrom_spec['controller_type'] == 'ide' and (cdrom_ctl_num not in [0, 1] or cdrom_ctl_unit_num not in [0, 1]):
1470 self.module.fail_json(msg="Invalid cdrom.controller_number: %s or cdrom.unit_number: %s, valid"
1471 " values are 0 or 1 for IDE controller."
1472 % (cdrom_spec.get('controller_number'), cdrom_spec.get('unit_number')))
1473
1474 if cdrom_spec['controller_type'] == 'sata' and (cdrom_ctl_num not in range(0, 4) or cdrom_ctl_unit_num not in range(0, 30)):
1475 self.module.fail_json(msg="Invalid cdrom.controller_number: %s or cdrom.unit_number: %s,"
1476 " valid controller_number value is 0-3, valid unit_number is 0-29"
1477 " for SATA controller." % (cdrom_spec.get('controller_number'),
1478 cdrom_spec.get('unit_number')))
1479 cdrom_spec['controller_number'] = cdrom_ctl_num
1480 cdrom_spec['unit_number'] = cdrom_ctl_unit_num
1481
1482 ctl_exist = False
1483 for exist_spec in cdrom_specs:
1484 if exist_spec.get('ctl_num') == cdrom_spec['controller_number'] and \
1485 exist_spec.get('ctl_type') == cdrom_spec['controller_type']:
1486 for cdrom_same_ctl in exist_spec['cdroms']:
1487 if cdrom_same_ctl['unit_number'] == cdrom_spec['unit_number']:
1488 self.module.fail_json(msg="Duplicate cdrom.controller_type: %s, cdrom.controller_number: %s,"
1489 "cdrom.unit_number: %s parameters specified."
1490 % (cdrom_spec['controller_type'], cdrom_spec['controller_number'], cdrom_spec['unit_number']))
1491 ctl_exist = True
1492 exist_spec['cdroms'].append(cdrom_spec)
1493 break
1494 if not ctl_exist:
1495 cdrom_specs.append({'ctl_num': cdrom_spec['controller_number'],
1496 'ctl_type': cdrom_spec['controller_type'], 'cdroms': [cdrom_spec]})
1497
1498 return cdrom_specs
1499
1500 def configure_cdrom(self, vm_obj):
1501 # Configure the VM CD-ROM
1502 if self.params.get('cdrom'):
1503 if vm_obj and vm_obj.config.template:
1504 # Changing CD-ROM settings on a template is not supported
1505 return
1506
1507 self.configure_cdrom_list(vm_obj)
1508
1509 def configure_cdrom_list(self, vm_obj):
1510 configured_cdroms = self.sanitize_cdrom_params()
1511 # get existing CDROM devices
1512 cdrom_devices = self.get_vm_cdrom_devices(vm=vm_obj)
1513 # get existing IDE and SATA controllers
1514 ide_devices = self.get_vm_ide_devices(vm=vm_obj)
1515 sata_devices = self.get_vm_sata_devices(vm=vm_obj)
1516
1517 for expected_cdrom_spec in configured_cdroms:
1518 ctl_device = None
1519 if expected_cdrom_spec['ctl_type'] == 'ide' and ide_devices:
1520 for device in ide_devices:
1521 if device.busNumber == expected_cdrom_spec['ctl_num']:
1522 ctl_device = device
1523 break
1524 if expected_cdrom_spec['ctl_type'] == 'sata' and sata_devices:
1525 for device in sata_devices:
1526 if device.busNumber == expected_cdrom_spec['ctl_num']:
1527 ctl_device = device
1528 break
1529 # if not find create new ide or sata controller
1530 if not ctl_device:
1531 if expected_cdrom_spec['ctl_type'] == 'ide':
1532 ide_ctl = self.device_helper.create_ide_controller(bus_number=expected_cdrom_spec['ctl_num'])
1533 ctl_device = ide_ctl.device
1534 self.change_detected = True
1535 self.configspec.deviceChange.append(ide_ctl)
1536 if expected_cdrom_spec['ctl_type'] == 'sata':
1537 sata_ctl = self.device_helper.create_sata_controller(bus_number=expected_cdrom_spec['ctl_num'])
1538 ctl_device = sata_ctl.device
1539 self.change_detected = True
1540 self.configspec.deviceChange.append(sata_ctl)
1541
1542 for cdrom in expected_cdrom_spec['cdroms']:
1543 cdrom_device = None
1544 iso_path = cdrom.get('iso_path')
1545 unit_number = cdrom.get('unit_number')
1546 for target_cdrom in cdrom_devices:
1547 if target_cdrom.controllerKey == ctl_device.key and target_cdrom.unitNumber == unit_number:
1548 cdrom_device = target_cdrom
1549 break
1550 # create new CD-ROM
1551 if not cdrom_device and cdrom.get('state') != 'absent':
1552 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1553 if vm_obj and vm_obj.runtime.powerState == vim.VirtualMachinePowerState.poweredOn and \
1554 isinstance(ctl_device, vim.vm.device.VirtualIDEController) and not self.module.check_mode:
1555 self.module.fail_json(msg='CD-ROM attach to IDE controller not support hot-add.')
1556 if len(ctl_device.device) == 2 and isinstance(ctl_device, vim.vm.device.VirtualIDEController):
1557 self.module.fail_json(msg='Maximum number of CD-ROMs attached to IDE controller is 2.')
1558 if len(ctl_device.device) == 30 and isinstance(ctl_device, vim.vm.device.VirtualAHCIController):
1559 self.module.fail_json(msg='Maximum number of CD-ROMs attached to SATA controller is 30.')
1560
1561 cdrom_spec = self.device_helper.create_cdrom(ctl_device=ctl_device, cdrom_type=cdrom['type'],
1562 iso_path=iso_path, unit_number=unit_number)
1563 self.change_detected = True
1564 self.configspec.deviceChange.append(cdrom_spec)
1565 # re-configure CD-ROM
1566 elif cdrom_device and cdrom.get('state') != 'absent' and \
1567 not self.device_helper.is_equal_cdrom(vm_obj=vm_obj, cdrom_device=cdrom_device,
1568 cdrom_type=cdrom['type'], iso_path=iso_path):
1569 self.device_helper.update_cdrom_config(vm_obj, cdrom, cdrom_device, iso_path=iso_path)
1570 cdrom_spec = vim.vm.device.VirtualDeviceSpec()
1571 cdrom_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
1572 cdrom_spec.device = cdrom_device
1573 self.change_detected = True
1574 self.configspec.deviceChange.append(cdrom_spec)
1575 # delete CD-ROM
1576 elif cdrom_device and cdrom.get('state') == 'absent':
1577 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1578 if vm_obj and vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff and \
1579 isinstance(ctl_device, vim.vm.device.VirtualIDEController) and not self.module.check_mode:
1580 self.module.fail_json(msg='CD-ROM attach to IDE controller not support hot-remove.')
1581 cdrom_spec = self.device_helper.remove_cdrom(cdrom_device)
1582 self.change_detected = True
1583 self.configspec.deviceChange.append(cdrom_spec)
1584
1585 def configure_hardware_params(self, vm_obj):
1586 """
1587 Function to configure hardware related configuration of virtual machine
1588 Args:
1589 vm_obj: virtual machine object
1590 """
1591 max_connections = self.params['hardware']['max_connections']
1592 if max_connections is not None:
1593 if vm_obj is None or max_connections != vm_obj.config.maxMksConnections:
1594 self.change_detected = True
1595 self.configspec.maxMksConnections = max_connections
1596
1597 nested_virt = self.params['hardware']['nested_virt']
1598 if nested_virt is not None:
1599 if vm_obj is None or nested_virt != bool(vm_obj.config.nestedHVEnabled):
1600 self.change_detected = True
1601 self.configspec.nestedHVEnabled = nested_virt
1602
1603 temp_version = self.params['hardware']['version']
1604 if temp_version is not None:
1605 new_version = None
1606 if temp_version.lower() == 'latest':
1607 # Check is to make sure vm_obj is not of type template
1608 if vm_obj and not vm_obj.config.template:
1609 config_option_descriptors = vm_obj.environmentBrowser.QueryConfigOptionDescriptor()
1610 available_hw_versions = [int(option_desc.key.split("-")[1]) for option_desc in config_option_descriptors if option_desc.upgradeSupported]
1611 temp_version = max(available_hw_versions)
1612 else:
1613 try:
1614 temp_version = int(temp_version)
1615 except ValueError:
1616 self.module.fail_json(msg="Failed to set hardware.version '%s' value as valid"
1617 " values are either 'latest' or a number."
1618 " Please check VMware documentation for valid VM hardware versions." % temp_version)
1619
1620 if isinstance(temp_version, int):
1621 # Hardware version is denoted as "vmx-10"
1622 new_version = "vmx-%02d" % temp_version
1623
1624 if vm_obj is None:
1625 self.change_detected = True
1626 self.configspec.version = new_version
1627 # Check is to make sure vm_obj is not of type template
1628 elif not vm_obj.config.template:
1629 # VM exists and we need to update the hardware version
1630 current_version = vm_obj.config.version
1631 # Hardware version is denoted as "vmx-10"
1632 version_digit = int(current_version.split("-", 1)[-1])
1633 if temp_version < version_digit:
1634 self.module.fail_json(msg="Current hardware version '%d' which is greater than the specified"
1635 " version '%d'. Downgrading hardware version is"
1636 " not supported. Please specify version greater"
1637 " than the current version." % (version_digit,
1638 temp_version))
1639 elif temp_version > version_digit:
1640 self.change_detected = True
1641 self.tracked_changes['hardware.version'] = temp_version
1642 self.configspec.version = new_version
1643 # Only perform the upgrade if not in check mode.
1644 if not self.module.check_mode:
1645 task = vm_obj.UpgradeVM_Task(new_version)
1646 error_msg = self.wait_for_task(task)
1647 if task.info.state == 'error':
1648 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'upgrade'}
1649 self.change_applied = True
1650
1651 secure_boot = self.params['hardware']['secure_boot']
1652 if secure_boot is not None:
1653 if vm_obj is None or secure_boot != vm_obj.config.bootOptions.efiSecureBootEnabled:
1654 self.change_detected = True
1655 self.configspec.bootOptions = vim.vm.BootOptions()
1656 self.configspec.bootOptions.efiSecureBootEnabled = secure_boot
1657
1658 iommu = self.params['hardware']['iommu']
1659 if iommu is not None:
1660 if vm_obj is None or iommu != vm_obj.config.flags.vvtdEnabled:
1661 self.change_detected = True
1662 if self.configspec.flags is None:
1663 self.configspec.flags = vim.vm.FlagInfo()
1664 self.configspec.flags.vvtdEnabled = iommu
1665
1666 virt_based_security = self.params['hardware']['virt_based_security']
1667 if virt_based_security is not None:
1668 if vm_obj is None or virt_based_security != vm_obj.config.flags.vbsEnabled:
1669 self.change_detected = True
1670 if self.configspec.flags is None:
1671 self.configspec.flags = vim.vm.FlagInfo()
1672 self.configspec.flags.vbsEnabled = virt_based_security
1673
1674 def configure_encryption_params(self, vm_obj):
1675
1676 encrypted_vmotion = self.params['encryption']['encrypted_vmotion']
1677 if encrypted_vmotion is not None:
1678 if vm_obj is None or encrypted_vmotion != vm_obj.config.migrateEncryption:
1679 self.change_detected = True
1680 self.configspec.migrateEncryption = encrypted_vmotion
1681
1682 encrypted_ft = self.params['encryption']['encrypted_ft']
1683 if encrypted_ft is not None:
1684 if encrypted_ft == "disabled":
1685 encrypted_ft_cfg = "ftEncryptionDisabled"
1686 elif encrypted_ft == "opportunistic":
1687 encrypted_ft_cfg = "ftEncryptionOpportunistic"
1688 elif encrypted_ft == "required":
1689 encrypted_ft_cfg = "ftEncryptionRequired"
1690 if vm_obj is None or encrypted_ft_cfg != vm_obj.config.ftEncryptionMode:
1691 self.change_detected = True
1692 self.configspec.ftEncryptionMode = encrypted_ft_cfg
1693
1694 def get_device_by_type(self, vm=None, type=None):
1695 device_list = []
1696 if vm is None or type is None:
1697 return device_list
1698 for device in vm.config.hardware.device:
1699 if isinstance(device, type):
1700 device_list.append(device)
1701
1702 return device_list
1703
1704 def get_vm_cdrom_devices(self, vm=None):
1705 return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualCdrom)
1706
1707 def get_vm_ide_devices(self, vm=None):
1708 return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualIDEController)
1709
1710 def get_vm_sata_devices(self, vm=None):
1711 return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualAHCIController)
1712
1713 def get_vm_nvdimm_ctl_device(self, vm=None):
1714 return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualNVDIMMController)
1715
1716 def get_vm_nvdimm_devices(self, vm=None):
1717 return self.get_device_by_type(vm=vm, type=vim.vm.device.VirtualNVDIMM)
1718
1719 def configure_nvdimm(self, vm_obj):
1720 """
1721 Manage virtual NVDIMM device to the virtual machine
1722 Args:
1723 vm_obj: virtual machine object
1724 """
1725 if self.params['nvdimm']['state']:
1726 # Label is required when remove device
1727 if self.params['nvdimm']['state'] == 'absent' and not self.params['nvdimm']['label']:
1728 self.module.fail_json(msg="Please specify the label of virtual NVDIMM device using 'label' parameter"
1729 " when state is set to 'absent'.")
1730 # Reconfigure device requires VM in power off state
1731 if vm_obj and not vm_obj.config.template:
1732 # Allow VM to be powered on during this check when in check mode, when no changes will actually be made
1733 if vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff and not self.module.check_mode:
1734 self.module.fail_json(msg="VM is not in power off state, can not do virtual NVDIMM configuration.")
1735
1736 nvdimm_ctl_exists = False
1737 if vm_obj and not vm_obj.config.template:
1738 # Get existing NVDIMM controller
1739 nvdimm_ctl = self.get_vm_nvdimm_ctl_device(vm=vm_obj)
1740 if len(nvdimm_ctl) != 0:
1741 nvdimm_ctl_exists = True
1742 nvdimm_ctl_key = nvdimm_ctl[0].key
1743 if self.params['nvdimm']['label'] is not None:
1744 nvdimm_devices = self.get_vm_nvdimm_devices(vm=vm_obj)
1745 if len(nvdimm_devices) != 0:
1746 existing_nvdimm_dev = self.device_helper.find_nvdimm_by_label(
1747 nvdimm_label=self.params['nvdimm']['label'],
1748 nvdimm_devices=nvdimm_devices
1749 )
1750 if existing_nvdimm_dev is not None:
1751 if self.params['nvdimm']['state'] == 'absent':
1752 nvdimm_remove_spec = self.device_helper.remove_nvdimm(
1753 nvdimm_device=existing_nvdimm_dev
1754 )
1755 self.change_detected = True
1756 self.configspec.deviceChange.append(nvdimm_remove_spec)
1757 else:
1758 if existing_nvdimm_dev.capacityInMB < self.params['nvdimm']['size_mb']:
1759 nvdimm_config_spec = self.device_helper.update_nvdimm_config(
1760 nvdimm_device=existing_nvdimm_dev,
1761 nvdimm_size=self.params['nvdimm']['size_mb']
1762 )
1763 self.change_detected = True
1764 self.configspec.deviceChange.append(nvdimm_config_spec)
1765 elif existing_nvdimm_dev.capacityInMB > self.params['nvdimm']['size_mb']:
1766 self.module.fail_json(msg="Can not change NVDIMM device size to %s MB, which is"
1767 " smaller than the current size %s MB."
1768 % (self.params['nvdimm']['size_mb'],
1769 existing_nvdimm_dev.capacityInMB))
1770 # New VM or existing VM without label specified, add new NVDIMM device
1771 if vm_obj is None or (vm_obj and not vm_obj.config.template and self.params['nvdimm']['label'] is None):
1772 if self.params['nvdimm']['state'] == 'present':
1773 vc_pmem_profile_id = None
1774 # Get default PMem storage policy when host is vCenter
1775 if self.is_vcenter():
1776 storage_profile_name = "Host-local PMem Default Storage Policy"
1777 spbm = SPBM(self.module)
1778 pmem_profile = spbm.find_storage_profile_by_name(profile_name=storage_profile_name)
1779 if pmem_profile is None:
1780 self.module.fail_json(msg="Can not find PMem storage policy with name '%s'." % storage_profile_name)
1781 vc_pmem_profile_id = pmem_profile.profileId.uniqueId
1782
1783 if not nvdimm_ctl_exists:
1784 nvdimm_ctl_spec = self.device_helper.create_nvdimm_controller()
1785 self.configspec.deviceChange.append(nvdimm_ctl_spec)
1786 nvdimm_ctl_key = nvdimm_ctl_spec.device.key
1787
1788 nvdimm_dev_spec = self.device_helper.create_nvdimm_device(
1789 nvdimm_ctl_dev_key=nvdimm_ctl_key,
1790 pmem_profile_id=vc_pmem_profile_id,
1791 nvdimm_dev_size_mb=self.params['nvdimm']['size_mb']
1792 )
1793 self.change_detected = True
1794 self.configspec.deviceChange.append(nvdimm_dev_spec)
1795
1796 def get_vm_network_interfaces(self, vm=None):
1797 device_list = []
1798 if vm is None:
1799 return device_list
1800
1801 for device in vm.config.hardware.device:
1802 for device_type in self.device_helper.nic_device_type.values():
1803 if isinstance(device, device_type):
1804 device_list.append(device)
1805
1806 return device_list
1807
1808 def sanitize_network_params(self):
1809 """
1810 Sanitize user provided network provided params
1811
1812 Returns: A sanitized list of network params, else fails
1813
1814 """
1815 network_devices = list()
1816 # Clean up user data here
1817 for network in self.params['networks']:
1818 if 'name' not in network and 'vlan' not in network:
1819 self.module.fail_json(msg="Please specify at least a network name or"
1820 " a VLAN name under VM network list.")
1821
1822 if 'name' in network and self.cache.get_network(network['name']) is None:
1823 self.module.fail_json(msg="Network '%(name)s' does not exist." % network)
1824 elif 'vlan' in network:
1825 dvps = self.cache.get_all_objs(self.content, [vim.dvs.DistributedVirtualPortgroup])
1826 for dvp in dvps:
1827 if hasattr(dvp.config.defaultPortConfig, 'vlan') and \
1828 isinstance(dvp.config.defaultPortConfig.vlan.vlanId, int) and \
1829 str(dvp.config.defaultPortConfig.vlan.vlanId) == str(network['vlan']):
1830 network['name'] = dvp.config.name
1831 break
1832 if 'dvswitch_name' in network and \
1833 dvp.config.distributedVirtualSwitch.name == network['dvswitch_name'] and \
1834 dvp.config.name == network['vlan']:
1835 network['name'] = dvp.config.name
1836 break
1837
1838 if dvp.config.name == network['vlan']:
1839 network['name'] = dvp.config.name
1840 break
1841 else:
1842 self.module.fail_json(msg="VLAN '%(vlan)s' does not exist." % network)
1843
1844 if 'type' in network:
1845 if network['type'] not in ['dhcp', 'static']:
1846 self.module.fail_json(msg="Network type '%(type)s' is not a valid parameter."
1847 " Valid parameters are ['dhcp', 'static']." % network)
1848 if network['type'] != 'static' and ('ip' in network or 'netmask' in network):
1849 self.module.fail_json(msg='Static IP information provided for network "%(name)s",'
1850 ' but "type" is set to "%(type)s".' % network)
1851 else:
1852 # Type is optional parameter, if user provided IP or Subnet assume
1853 # network type as 'static'
1854 if 'ip' in network or 'netmask' in network:
1855 network['type'] = 'static'
1856 else:
1857 # User wants network type as 'dhcp'
1858 network['type'] = 'dhcp'
1859
1860 if network.get('type') == 'static':
1861 if 'ip' in network and 'netmask' not in network:
1862 self.module.fail_json(msg="'netmask' is required if 'ip' is"
1863 " specified under VM network list.")
1864 if 'ip' not in network and 'netmask' in network:
1865 self.module.fail_json(msg="'ip' is required if 'netmask' is"
1866 " specified under VM network list.")
1867
1868 if 'typev6' in network:
1869 if network['typev6'] not in ['dhcp', 'static']:
1870 self.module.fail_json(msg="Network type '%(typev6)s' for IPv6 is not a valid parameter."
1871 " Valid parameters are ['dhcp', 'static']." % network)
1872 if network['typev6'] != 'static' and ('ipv6' in network or 'netmaskv6' in network):
1873 self.module.fail_json(msg='Static IPv6 information provided for network "%(name)s",'
1874 ' but "typev6" is set to "%(typev6)s".' % network)
1875 else:
1876 # Type is optional parameter, if user provided IP or Subnet assume
1877 # network type as 'static'
1878 if 'ipv6' in network or 'netmaskv6' in network:
1879 network['typev6'] = 'static'
1880 else:
1881 # User wants network type as 'dhcp'
1882 network['typev6'] = 'dhcp'
1883
1884 if network.get('typev6') == 'static':
1885 if 'ipv6' in network and 'netmaskv6' not in network:
1886 self.module.fail_json(msg="'netmaskv6' is required if 'ipv6' is"
1887 " specified under VM network list.")
1888 if 'ipv6' not in network and 'netmaskv6' in network:
1889 self.module.fail_json(msg="'ipv6' is required if 'netmaskv6' is"
1890 " specified under VM network list.")
1891
1892 if 'device_type' in network and network['device_type'] not in self.device_helper.nic_device_type.keys():
1893 self.module.fail_json(msg="Device type specified '%s' is not valid. Please specify correct device type"
1894 " from ['%s']." % (network['device_type'],
1895 "', '".join(self.device_helper.nic_device_type.keys())))
1896
1897 if 'mac' in network and not is_mac(network['mac']):
1898 self.module.fail_json(msg="Device MAC address '%s' is invalid."
1899 " Please provide correct MAC address." % network['mac'])
1900
1901 network_devices.append(network)
1902
1903 return network_devices
1904
1905 def configure_network(self, vm_obj):
1906 # Ignore empty networks, this permits to keep networks when deploying a template/cloning a VM
1907 if not self.params['networks']:
1908 return
1909
1910 network_devices = self.sanitize_network_params()
1911
1912 # List current device for Clone or Idempotency
1913 current_net_devices = self.get_vm_network_interfaces(vm=vm_obj)
1914 if len(network_devices) < len(current_net_devices):
1915 self.module.fail_json(msg="Given network device list is lesser than current VM device list (%d < %d). "
1916 "Removing interfaces is not allowed"
1917 % (len(network_devices), len(current_net_devices)))
1918
1919 for key in range(0, len(network_devices)):
1920 nic_change_detected = False
1921 network_name = network_devices[key]['name']
1922 if key < len(current_net_devices) and (vm_obj or self.params['template']):
1923 # We are editing existing network devices, this is either when
1924 # are cloning from VM or Template
1925 nic = vim.vm.device.VirtualDeviceSpec()
1926 nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
1927
1928 nic.device = current_net_devices[key]
1929 if "wake_on_lan" in network_devices[key] and \
1930 nic.device.wakeOnLanEnabled != network_devices[key].get("wake_on_lan"):
1931 nic.device.wakeOnLanEnabled = network_devices[key].get("wake_on_lan")
1932 nic_change_detected = True
1933 if "start_connected" in network_devices[key] and \
1934 nic.device.connectable.startConnected != network_devices[key].get("start_connected"):
1935 nic.device.connectable.startConnected = network_devices[key].get("start_connected")
1936 nic_change_detected = True
1937 if "connected" in network_devices[key] and \
1938 nic.device.connectable.connected != network_devices[key].get("connected"):
1939 nic.device.connectable.connected = network_devices[key].get("connected")
1940 nic_change_detected = True
1941 if "allow_guest_control" in network_devices[key] and \
1942 nic.device.connectable.allowGuestControl != network_devices[key].get("allow_guest_control"):
1943 nic.device.connectable.allowGuestControl = network_devices[key].get("allow_guest_control")
1944 nic_change_detected = True
1945
1946 if nic.device.deviceInfo.summary != network_name:
1947 if 'DVSwitch' not in nic.device.deviceInfo.summary:
1948 nic.device.deviceInfo.summary = network_name
1949 nic_change_detected = True
1950 else:
1951 pgs = self.find_network_by_name(network_name)
1952 if len(pgs) == 1:
1953 pg = pgs[0]
1954 else:
1955 pg = find_obj(self.content, [vim.DistributedVirtualPortgroup], network_name)
1956 if pg is None or nic.device.backing.port.portgroupKey != pg.key:
1957 nic.device.deviceInfo.summary = network_name
1958 nic_change_detected = True
1959
1960 if 'device_type' in network_devices[key]:
1961 device = self.device_helper.nic_device_type.get(network_devices[key]['device_type'])
1962 if not isinstance(nic.device, device):
1963 self.module.fail_json(msg="Changing the device type is not possible when interface is already"
1964 " present. The failing device type is %s"
1965 % network_devices[key]['device_type'])
1966 # Changing mac address has no effect when editing interface
1967 if 'mac' in network_devices[key] and nic.device.macAddress != current_net_devices[key].macAddress:
1968 self.module.fail_json(msg="Changing MAC address has not effect when interface is already present. "
1969 "The failing new MAC address is %s" % nic.device.macAddress)
1970
1971 else:
1972 # Default device type is vmxnet3, VMware best practice
1973 device_type = network_devices[key].get('device_type', 'vmxnet3')
1974 nic = self.device_helper.create_nic(device_type,
1975 'Network Adapter %s' % (key + 1),
1976 network_devices[key])
1977 nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
1978 nic_change_detected = True
1979
1980 net_obj = self.cache.get_network(network_name)
1981 if hasattr(net_obj, 'portKeys'):
1982 # VDS switch
1983 pg_obj = None
1984 if 'dvswitch_name' in network_devices[key]:
1985 dvs_name = network_devices[key]['dvswitch_name']
1986 dvs_obj = find_dvs_by_name(self.content, dvs_name)
1987 if dvs_obj is None:
1988 self.module.fail_json(msg="Unable to find distributed virtual switch %s" % dvs_name)
1989 pg_obj = find_dvspg_by_name(dvs_obj, network_name)
1990 if pg_obj is None:
1991 self.module.fail_json(msg="Unable to find distributed port group %s" % network_name)
1992 else:
1993 networks = self.find_network_by_name(network_name)
1994 if len(networks) == 1:
1995 pg_obj = networks[0]
1996 else:
1997 pg_obj = self.cache.find_obj(self.content, [vim.dvs.DistributedVirtualPortgroup], network_name)
1998
1999 # TODO: (akasurde) There is no way to find association between resource pool and distributed virtual portgroup
2000 # For now, check if we are able to find distributed virtual switch
2001 if not pg_obj.config.distributedVirtualSwitch:
2002 self.module.fail_json(
2003 msg="Failed to find distributed virtual switch which is associated with"
2004 " distributed virtual portgroup '%s'. Make sure hostsystem is associated with"
2005 " the given distributed virtual portgroup. Also, check if user has correct"
2006 " permission to access distributed virtual switch in the given portgroup."
2007 % pg_obj.name
2008 )
2009 if nic.device.backing and (
2010 not hasattr(nic.device.backing, "port")
2011 or (
2012 nic.device.backing.port.portgroupKey != pg_obj.key
2013 or nic.device.backing.port.switchUuid
2014 != pg_obj.config.distributedVirtualSwitch.uuid
2015 )
2016 ):
2017 nic_change_detected = True
2018
2019 dvs_port_connection = vim.dvs.PortConnection()
2020 dvs_port_connection.portgroupKey = pg_obj.key
2021 # If user specifies distributed port group without associating to the hostsystem on which
2022 # virtual machine is going to be deployed then we get error. We can infer that there is no
2023 # association between given distributed port group and host system.
2024 host_system = self.params.get('esxi_hostname')
2025 if host_system and host_system not in [host.config.host.name for host in pg_obj.config.distributedVirtualSwitch.config.host]:
2026 self.module.fail_json(msg="It seems that host system '%s' is not associated with distributed"
2027 " virtual portgroup '%s'. Please make sure host system is associated"
2028 " with given distributed virtual portgroup" % (host_system, pg_obj.name))
2029 dvs_port_connection.switchUuid = pg_obj.config.distributedVirtualSwitch.uuid
2030 nic.device.backing = vim.vm.device.VirtualEthernetCard.DistributedVirtualPortBackingInfo()
2031 nic.device.backing.port = dvs_port_connection
2032
2033 elif isinstance(net_obj, vim.OpaqueNetwork):
2034 # NSX-T Logical Switch
2035 nic.device.backing = vim.vm.device.VirtualEthernetCard.OpaqueNetworkBackingInfo()
2036 network_id = net_obj.summary.opaqueNetworkId
2037 nic.device.backing.opaqueNetworkType = 'nsx.LogicalSwitch'
2038 nic.device.backing.opaqueNetworkId = network_id
2039 nic.device.deviceInfo.summary = 'nsx.LogicalSwitch: %s' % network_id
2040 nic_change_detected = True
2041 else:
2042 # vSwitch
2043 if not isinstance(nic.device.backing, vim.vm.device.VirtualEthernetCard.NetworkBackingInfo):
2044 nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
2045 nic_change_detected = True
2046
2047 if nic.device.backing.network != net_obj:
2048 nic.device.backing.network = net_obj
2049 nic_change_detected = True
2050
2051 if nic.device.backing.deviceName != network_name:
2052 nic.device.backing.deviceName = network_name
2053 nic_change_detected = True
2054
2055 if nic_change_detected:
2056 # Change to fix the issue found while configuring opaque network
2057 # VMs cloned from a template with opaque network will get disconnected
2058 # Replacing deprecated config parameter with relocation Spec
2059 if isinstance(net_obj, vim.OpaqueNetwork):
2060 self.relospec.deviceChange.append(nic)
2061 else:
2062 self.configspec.deviceChange.append(nic)
2063 self.change_detected = True
2064
2065 def set_vapp_properties(self, property_spec):
2066 # Sets the values in property_info
2067 property_info = vim.vApp.PropertyInfo()
2068 property_info.classId = property_spec.get('classId')
2069 property_info.instanceId = property_spec.get('instanceId')
2070 property_info.id = property_spec.get('id')
2071 property_info.category = property_spec.get('category')
2072 property_info.label = property_spec.get('label')
2073 property_info.type = property_spec.get('type', 'string')
2074 property_info.userConfigurable = property_spec.get('userConfigurable', True)
2075 property_info.defaultValue = property_spec.get('defaultValue')
2076 property_info.value = property_spec.get('value', '')
2077 property_info.description = property_spec.get('description')
2078 return property_info
2079
2080 def configure_vapp_properties(self, vm_obj):
2081 if not self.params['vapp_properties']:
2082 return
2083
2084 for x in self.params['vapp_properties']:
2085 if not x.get('id'):
2086 self.module.fail_json(msg="id is required to set vApp property")
2087
2088 new_vmconfig_spec = vim.vApp.VmConfigSpec()
2089
2090 if vm_obj:
2091 # VM exists
2092 orig_spec = vm_obj.config.vAppConfig
2093 orig_properties = orig_spec.property if orig_spec is not None else []
2094
2095 vapp_properties_current = dict((x.id, x) for x in orig_properties)
2096 vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties'])
2097
2098 # each property must have a unique key
2099 # init key counter with max value + 1
2100 all_keys = [x.key for x in orig_properties]
2101 new_property_index = max(all_keys) + 1 if all_keys else 0
2102
2103 for property_id, property_spec in vapp_properties_to_change.items():
2104 is_property_changed = False
2105 new_vapp_property_spec = vim.vApp.PropertySpec()
2106
2107 if property_id in vapp_properties_current:
2108 if property_spec.get('operation') == 'remove':
2109 new_vapp_property_spec.operation = 'remove'
2110 new_vapp_property_spec.removeKey = vapp_properties_current[property_id].key
2111 is_property_changed = True
2112 else:
2113 # this is 'edit' branch
2114 new_vapp_property_spec.operation = 'edit'
2115 new_vapp_property_spec.info = vapp_properties_current[property_id]
2116 try:
2117 for property_name, property_value in property_spec.items():
2118
2119 if property_name == 'operation':
2120 # operation is not an info object property
2121 # if set to anything other than 'remove' we don't fail
2122 continue
2123
2124 # Updating attributes only if needed
2125 if getattr(new_vapp_property_spec.info, property_name) != property_value:
2126 setattr(new_vapp_property_spec.info, property_name, property_value)
2127 is_property_changed = True
2128
2129 except Exception as e:
2130 msg = "Failed to set vApp property field='%s' and value='%s'. Error: %s" % (property_name, property_value, to_text(e))
2131 self.module.fail_json(msg=msg)
2132 else:
2133 if property_spec.get('operation') == 'remove':
2134 # attempt to delete non-existent property
2135 continue
2136
2137 # this is add new property branch
2138 new_vapp_property_spec.operation = 'add'
2139
2140 # Configure the values in property_value
2141 property_info = self.set_vapp_properties(property_spec)
2142
2143 new_vapp_property_spec.info = property_info
2144 new_vapp_property_spec.info.key = new_property_index
2145 new_property_index += 1
2146 is_property_changed = True
2147
2148 if is_property_changed:
2149 new_vmconfig_spec.property.append(new_vapp_property_spec)
2150 else:
2151 # New VM
2152 all_keys = [x.key for x in new_vmconfig_spec.property]
2153 new_property_index = max(all_keys) + 1 if all_keys else 0
2154 vapp_properties_to_change = dict((x['id'], x) for x in self.params['vapp_properties'])
2155 is_property_changed = False
2156
2157 for property_id, property_spec in vapp_properties_to_change.items():
2158 new_vapp_property_spec = vim.vApp.PropertySpec()
2159 # this is add new property branch
2160 new_vapp_property_spec.operation = 'add'
2161
2162 # Configure the values in property_value
2163 property_info = self.set_vapp_properties(property_spec)
2164
2165 new_vapp_property_spec.info = property_info
2166 new_vapp_property_spec.info.key = new_property_index
2167 new_property_index += 1
2168 is_property_changed = True
2169
2170 if is_property_changed:
2171 new_vmconfig_spec.property.append(new_vapp_property_spec)
2172
2173 if new_vmconfig_spec.property:
2174 self.configspec.vAppConfig = new_vmconfig_spec
2175 self.change_detected = True
2176
2177 def customize_advanced_settings(self, vm_obj, config_spec):
2178 if not self.params['advanced_settings']:
2179 return
2180
2181 vm_custom_spec = config_spec
2182 vm_custom_spec.extraConfig = []
2183
2184 changed = False
2185 facts = self.gather_facts(vm_obj)
2186 for kv in self.params['advanced_settings']:
2187 if 'key' not in kv or 'value' not in kv:
2188 self.module.exit_json(msg="advanced_settings items required both 'key' and 'value' fields.")
2189
2190 # If kv is not kv fetched from facts, change it
2191 if isinstance(kv['value'], (bool, int)):
2192 specifiedvalue = str(kv['value']).upper()
2193 comparisonvalue = facts['advanced_settings'].get(kv['key'], '').upper()
2194 else:
2195 specifiedvalue = kv['value']
2196 comparisonvalue = facts['advanced_settings'].get(kv['key'], '')
2197
2198 if (kv['key'] not in facts['advanced_settings'] and kv['value'] != '') or comparisonvalue != specifiedvalue:
2199 option = vim.option.OptionValue()
2200 option.key = kv['key']
2201 option.value = specifiedvalue
2202
2203 vm_custom_spec.extraConfig.append(option)
2204 changed = True
2205
2206 if changed:
2207 self.change_detected = True
2208
2209 def customize_customvalues(self, vm_obj):
2210 if not self.params['customvalues']:
2211 return
2212
2213 if not self.is_vcenter():
2214 self.module.warn("Currently connected to ESXi. "
2215 "customvalues are a vCenter feature, this parameter will be ignored.")
2216 return
2217
2218 facts = self.gather_facts(vm_obj)
2219 for kv in self.params['customvalues']:
2220 if 'key' not in kv or 'value' not in kv:
2221 self.module.exit_json(msg="customvalues items required both 'key' and 'value' fields.")
2222
2223 key_id = None
2224 for field in self.content.customFieldsManager.field:
2225 if field.name == kv['key']:
2226 key_id = field.key
2227 break
2228
2229 if not key_id:
2230 self.module.fail_json(msg="Unable to find custom value key %s" % kv['key'])
2231
2232 # If kv is not kv fetched from facts, change it
2233 if kv['key'] not in facts['customvalues'] or facts['customvalues'][kv['key']] != kv['value']:
2234 self.content.customFieldsManager.SetField(entity=vm_obj, key=key_id, value=kv['value'])
2235 self.change_detected = True
2236
2237 def customize_vm(self, vm_obj):
2238
2239 # User specified customization specification
2240 custom_spec_name = self.params.get('customization_spec')
2241 if custom_spec_name:
2242 cc_mgr = self.content.customizationSpecManager
2243 if cc_mgr.DoesCustomizationSpecExist(name=custom_spec_name):
2244 temp_spec = cc_mgr.GetCustomizationSpec(name=custom_spec_name)
2245 self.customspec = temp_spec.spec
2246 return
2247 self.module.fail_json(msg="Unable to find customization specification"
2248 " '%s' in given configuration." % custom_spec_name)
2249
2250 # Network settings
2251 adaptermaps = []
2252 for network in self.params['networks']:
2253
2254 guest_map = vim.vm.customization.AdapterMapping()
2255 guest_map.adapter = vim.vm.customization.IPSettings()
2256
2257 if 'ip' in network and 'netmask' in network:
2258 guest_map.adapter.ip = vim.vm.customization.FixedIp()
2259 guest_map.adapter.ip.ipAddress = str(network['ip'])
2260 guest_map.adapter.subnetMask = str(network['netmask'])
2261 elif 'type' in network and network['type'] == 'dhcp':
2262 guest_map.adapter.ip = vim.vm.customization.DhcpIpGenerator()
2263
2264 if "ipv6" in network and 'netmaskv6' in network:
2265 guest_map.adapter.ipV6Spec = vim.vm.customization.IPSettings.IpV6AddressSpec()
2266 guest_map.adapter.ipV6Spec.ip = [vim.vm.customization.FixedIpV6()]
2267 guest_map.adapter.ipV6Spec.ip[0].ipAddress = str(network['ipv6'])
2268 guest_map.adapter.ipV6Spec.ip[0].subnetMask = int(network['netmaskv6'])
2269 elif 'typev6' in network and network['typev6'] == 'dhcp':
2270 guest_map.adapter.ipV6Spec = vim.vm.customization.IPSettings.IpV6AddressSpec()
2271 guest_map.adapter.ipV6Spec.ip = [vim.vm.customization.DhcpIpV6Generator()]
2272
2273 if 'gateway' in network:
2274 guest_map.adapter.gateway = network['gateway']
2275
2276 if "gatewayv6" in network:
2277 guest_map.adapter.ipV6Spec.gateway = network['gatewayv6']
2278
2279 # On Windows, DNS domain and DNS servers can be set by network interface
2280 # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.IPSettings.html
2281 if 'domain' in network:
2282 guest_map.adapter.dnsDomain = network['domain']
2283 elif self.params['customization']['domain'] is not None:
2284 guest_map.adapter.dnsDomain = self.params['customization']['domain']
2285
2286 if 'dns_servers' in network:
2287 guest_map.adapter.dnsServerList = network['dns_servers']
2288 elif self.params['customization']['dns_servers'] is not None:
2289 guest_map.adapter.dnsServerList = self.params['customization']['dns_servers']
2290
2291 adaptermaps.append(guest_map)
2292
2293 # Global DNS settings
2294 globalip = vim.vm.customization.GlobalIPSettings()
2295 if self.params['customization']['dns_servers'] is not None:
2296 globalip.dnsServerList = self.params['customization']['dns_servers']
2297
2298 # TODO: Maybe list the different domains from the interfaces here by default ?
2299 dns_suffixes = []
2300 dns_suffix = self.params['customization']['dns_suffix']
2301 if dns_suffix:
2302 if isinstance(dns_suffix, list):
2303 dns_suffixes += dns_suffix
2304 else:
2305 dns_suffixes.append(dns_suffix)
2306
2307 globalip.dnsSuffixList = dns_suffixes
2308
2309 if self.params['customization']['domain'] is not None:
2310 dns_suffixes.insert(0, self.params['customization']['domain'])
2311 globalip.dnsSuffixList = dns_suffixes
2312
2313 if self.params['guest_id'] is not None:
2314 guest_id = self.params['guest_id']
2315 else:
2316 guest_id = vm_obj.summary.config.guestId
2317
2318 # For windows guest OS, use SysPrep
2319 # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.Sysprep.html#field_detail
2320 if 'win' in guest_id:
2321 ident = vim.vm.customization.Sysprep()
2322
2323 ident.userData = vim.vm.customization.UserData()
2324
2325 # Setting hostName, orgName and fullName is mandatory, so we set some default when missing
2326 ident.userData.computerName = vim.vm.customization.FixedName()
2327 # computer name will be truncated to 15 characters if using VM name
2328 default_name = ""
2329 if 'name' in self.params and self.params['name']:
2330 default_name = self.params['name'].replace(' ', '')
2331 elif vm_obj:
2332 default_name = vm_obj.name.replace(' ', '')
2333 punctuation = string.punctuation.replace('-', '')
2334 default_name = ''.join([c for c in default_name if c not in punctuation])
2335
2336 if self.params['customization']['hostname'] is not None:
2337 ident.userData.computerName.name = self.params['customization']['hostname'][0:15]
2338 else:
2339 ident.userData.computerName.name = default_name[0:15]
2340
2341 ident.userData.fullName = str(self.params['customization'].get('fullname', 'Administrator'))
2342 ident.userData.orgName = str(self.params['customization'].get('orgname', 'ACME'))
2343
2344 if self.params['customization']['productid'] is not None:
2345 ident.userData.productId = str(self.params['customization']['productid'])
2346
2347 ident.guiUnattended = vim.vm.customization.GuiUnattended()
2348
2349 if self.params['customization']['autologon'] is not None:
2350 ident.guiUnattended.autoLogon = self.params['customization']['autologon']
2351 ident.guiUnattended.autoLogonCount = self.params['customization'].get('autologoncount', 1)
2352
2353 if self.params['customization']['timezone'] is not None:
2354 # Check if timezone value is a int before proceeding.
2355 ident.guiUnattended.timeZone = self.device_helper.integer_value(
2356 self.params['customization']['timezone'],
2357 'customization.timezone')
2358
2359 ident.identification = vim.vm.customization.Identification()
2360
2361 if self.params['customization']['password'] is None or self.params['customization']['password'] == '':
2362 ident.guiUnattended.password = None
2363 else:
2364 ident.guiUnattended.password = vim.vm.customization.Password()
2365 ident.guiUnattended.password.value = str(self.params['customization']['password'])
2366 ident.guiUnattended.password.plainText = True
2367
2368 if self.params['customization']['joindomain'] is not None:
2369 if self.params['customization']['domainadmin'] is None or self.params['customization']['domainadminpassword'] is None:
2370 self.module.fail_json(msg="'domainadmin' and 'domainadminpassword' entries are mandatory in 'customization' section to use "
2371 "joindomain feature")
2372
2373 ident.identification.domainAdmin = self.params['customization']['domainadmin']
2374 ident.identification.joinDomain = self.params['customization']['joindomain']
2375 ident.identification.domainAdminPassword = vim.vm.customization.Password()
2376 ident.identification.domainAdminPassword.value = self.params['customization']['domainadminpassword']
2377 ident.identification.domainAdminPassword.plainText = True
2378
2379 # Add new spec param for vSphere 8.0U2
2380 ident.identification.domainOU = self.params['customization']['domain_ou']
2381
2382 elif self.params['customization']['joinworkgroup'] is not None:
2383 ident.identification.joinWorkgroup = self.params['customization']['joinworkgroup']
2384
2385 if self.params['customization']['runonce'] is not None:
2386 ident.guiRunOnce = vim.vm.customization.GuiRunOnce()
2387 ident.guiRunOnce.commandList = self.params['customization']['runonce']
2388
2389 else:
2390 # FIXME: We have no clue whether this non-Windows OS is actually Linux, hence it might fail!
2391
2392 # For Linux guest OS, use LinuxPrep
2393 # https://pubs.vmware.com/vi3/sdk/ReferenceGuide/vim.vm.customization.LinuxPrep.html
2394 ident = vim.vm.customization.LinuxPrep()
2395
2396 # TODO: Maybe add domain from interface if missing ?
2397 if self.params['customization']['domain'] is not None:
2398 ident.domain = self.params['customization']['domain']
2399
2400 ident.hostName = vim.vm.customization.FixedName()
2401 default_name = ""
2402 if 'name' in self.params and self.params['name']:
2403 default_name = self.params['name']
2404 elif vm_obj:
2405 default_name = vm_obj.name
2406
2407 if self.params['customization']['hostname'] is not None:
2408 hostname = self.params['customization']['hostname'].split('.')[0]
2409 else:
2410 hostname = default_name.split('.')[0]
2411
2412 # Remove all characters except alphanumeric and minus which is allowed by RFC 952
2413 valid_hostname = re.sub(r"[^a-zA-Z0-9\-]", "", hostname)
2414 ident.hostName.name = valid_hostname
2415
2416 # List of supported time zones for different vSphere versions in Linux/Unix systems
2417 # https://kb.vmware.com/s/article/2145518
2418 if self.params['customization']['timezone'] is not None:
2419 ident.timeZone = self.params['customization']['timezone']
2420 if self.params['customization']['hwclockUTC'] is not None:
2421 ident.hwClockUTC = self.params['customization']['hwclockUTC']
2422 if self.params['customization']['script_text'] is not None:
2423 ident.scriptText = self.params['customization']['script_text']
2424
2425 self.customspec = vim.vm.customization.Specification()
2426 self.customspec.nicSettingMap = adaptermaps
2427 self.customspec.globalIPSettings = globalip
2428 self.customspec.identity = ident
2429
2430 def get_vm_scsi_controllers(self, vm_obj):
2431 # If vm_obj doesn't exist there is no SCSI controller to find
2432 scsi_ctls = []
2433 if vm_obj is None:
2434 return None
2435
2436 for device in vm_obj.config.hardware.device:
2437 if self.device_helper.is_scsi_controller(device):
2438 scsi_ctl = vim.vm.device.VirtualDeviceSpec()
2439 scsi_ctl.device = device
2440 scsi_ctls.append(scsi_ctl)
2441
2442 return scsi_ctls
2443
2444 def get_configured_disk_size(self, expected_disk_spec):
2445 # what size is it?
2446 if [x for x in expected_disk_spec.keys() if (x.startswith('size_') or x == 'size') and expected_disk_spec[x]]:
2447 # size, size_tb, size_gb, size_mb, size_kb
2448 if expected_disk_spec['size']:
2449 size_regex = re.compile(r'(\d+(?:\.\d+)?)([tgmkTGMK][bB])')
2450 disk_size_m = size_regex.match(expected_disk_spec['size'])
2451 try:
2452 if disk_size_m:
2453 expected = disk_size_m.group(1)
2454 unit = disk_size_m.group(2)
2455 else:
2456 raise ValueError
2457
2458 if re.match(r'\d+\.\d+', expected):
2459 # We found float value in string, let's typecast it
2460 expected = float(expected)
2461 else:
2462 # We found int value in string, let's typecast it
2463 expected = int(expected)
2464
2465 if not expected or not unit:
2466 raise ValueError
2467
2468 except (TypeError, ValueError, NameError):
2469 # Common failure
2470 self.module.fail_json(msg="Failed to parse disk size please review value"
2471 " provided using documentation.")
2472 else:
2473 param = [x for x in expected_disk_spec.keys() if x.startswith('size_') and expected_disk_spec[x]][0]
2474 unit = param.split('_')[-1]
2475 expected = expected_disk_spec[param]
2476
2477 disk_units = dict(tb=3, gb=2, mb=1, kb=0)
2478 if unit in disk_units:
2479 unit = unit.lower()
2480 return expected * (1024 ** disk_units[unit])
2481 else:
2482 self.module.fail_json(msg="%s is not a supported unit for disk size."
2483 " Supported units are ['%s']." % (unit,
2484 "', '".join(disk_units.keys())))
2485
2486 # No size found but disk, fail
2487 self.module.fail_json(
2488 msg="No size, size_kb, size_mb, size_gb or size_tb defined in disk configuration")
2489
2490 def add_existing_vmdk(self, vm_obj, expected_disk_spec, diskspec, scsi_ctl):
2491 """
2492 Adds vmdk file described by expected_disk_spec['filename'], retrieves the file
2493 information and adds the correct spec to self.configspec.deviceChange.
2494 """
2495 filename = expected_disk_spec['filename']
2496 # If this is a new disk, or the disk file names are different
2497 if (vm_obj and diskspec.device.backing.fileName != filename) or vm_obj is None:
2498 diskspec.device.backing.fileName = filename
2499 diskspec.device.key = -1
2500 self.change_detected = True
2501 self.configspec.deviceChange.append(diskspec)
2502
2503 def sanitize_disk_parameters(self, vm_obj):
2504 """
2505
2506 Sanitize user provided disk parameters to configure multiple types of disk controllers and attached disks
2507
2508 Returns: A sanitized dict of disk params, else fails
2509 e.g., [{'type': 'nvme', 'num': 1, 'disk': []}, {}, {}, {}]}
2510
2511 """
2512 controllers = []
2513 for disk_spec in self.params.get('disk'):
2514 if disk_spec['controller_type'] is None or disk_spec['controller_number'] is None or disk_spec['unit_number'] is None:
2515 self.module.fail_json(msg="'disk.controller_type', 'disk.controller_number' and 'disk.unit_number' are"
2516 " mandatory parameters when configure multiple disk controllers and disks.")
2517
2518 ctl_num = disk_spec['controller_number']
2519 ctl_unit_num = disk_spec['unit_number']
2520
2521 disk_spec['unit_number'] = ctl_unit_num
2522 ctl_type = disk_spec['controller_type']
2523
2524 if len(controllers) != 0:
2525 ctl_exist = False
2526 for ctl in controllers:
2527 if ctl['type'] in self.device_helper.scsi_device_type.keys() and ctl_type in self.device_helper.scsi_device_type.keys():
2528 if ctl['type'] != ctl_type and ctl['num'] == ctl_num:
2529 self.module.fail_json(msg="Specified SCSI controller '%s' and '%s' have the same bus number"
2530 ": '%s'" % (ctl['type'], ctl_type, ctl_num))
2531
2532 if ctl['type'] == ctl_type and ctl['num'] == ctl_num:
2533 for i in range(0, len(ctl['disk'])):
2534 if disk_spec['unit_number'] == ctl['disk'][i]['unit_number']:
2535 self.module.fail_json(msg="Specified the same 'controller_type, controller_number, "
2536 "unit_number in disk configuration '%s:%s'" % (ctl_type, ctl_num))
2537 ctl['disk'].append(disk_spec)
2538 ctl_exist = True
2539 break
2540 if not ctl_exist:
2541 controllers.append({'type': ctl_type, 'num': ctl_num, 'disk': [disk_spec]})
2542 else:
2543 controllers.append({'type': ctl_type, 'num': ctl_num, 'disk': [disk_spec]})
2544
2545 return controllers
2546
2547 def set_disk_parameters(self, disk_spec, expected_disk_spec, reconfigure=False):
2548 disk_modified = False
2549 if expected_disk_spec['disk_mode']:
2550 disk_mode = expected_disk_spec.get('disk_mode')
2551 if reconfigure:
2552 if disk_spec.device.backing.diskMode != disk_mode:
2553 disk_spec.device.backing.diskMode = disk_mode
2554 disk_modified = True
2555 else:
2556 disk_spec.device.backing.diskMode = disk_mode
2557 # default is persistent for new deployed VM
2558 elif not reconfigure:
2559 disk_spec.device.backing.diskMode = "persistent"
2560
2561 if not reconfigure:
2562 disk_type = expected_disk_spec.get('type', 'thin')
2563 if disk_type == 'thin':
2564 disk_spec.device.backing.thinProvisioned = True
2565 elif disk_type == 'eagerzeroedthick':
2566 disk_spec.device.backing.eagerlyScrub = True
2567
2568 kb = self.get_configured_disk_size(expected_disk_spec)
2569 if reconfigure:
2570 if disk_spec.device.capacityInKB > kb:
2571 self.module.fail_json(msg="Given disk size is smaller than found (%d < %d)."
2572 "Reducing disks is not allowed." % (kb, disk_spec.device.capacityInKB))
2573 if disk_spec.device.capacityInKB != kb:
2574 disk_spec.device.capacityInKB = kb
2575 disk_modified = True
2576 else:
2577 disk_spec.device.capacityInKB = kb
2578 disk_modified = True
2579
2580 return disk_modified
2581
2582 def configure_multiple_controllers_disks(self, vm_obj):
2583 ctls = self.sanitize_disk_parameters(vm_obj)
2584 if len(ctls) == 0:
2585 return
2586 for ctl in ctls:
2587 # get existing specified disk controller and attached disks
2588 disk_ctl, disk_list = self.device_helper.get_controller_disks(vm_obj, ctl['type'], ctl['num'])
2589 if disk_ctl is None:
2590 # check if scsi controller key already used
2591 if ctl['type'] in self.device_helper.scsi_device_type.keys() and vm_obj is not None:
2592 scsi_ctls = self.get_vm_scsi_controllers(vm_obj)
2593 if scsi_ctls:
2594 for scsi_ctl in scsi_ctls:
2595 if scsi_ctl.device.busNumber == ctl['num']:
2596 self.module.fail_json(msg="Specified SCSI controller number '%s' is already used"
2597 " by: %s" % (ctl['num'], scsi_ctl))
2598 # create new disk controller if not exist
2599 disk_ctl_spec = self.device_helper.create_disk_controller(ctl['type'], ctl['num'])
2600 self.change_detected = True
2601 self.configspec.deviceChange.append(disk_ctl_spec)
2602 else:
2603 disk_ctl_spec = vim.vm.device.VirtualDeviceSpec()
2604 disk_ctl_spec.device = disk_ctl
2605 for j in range(0, len(ctl['disk'])):
2606 hard_disk = None
2607 hard_disk_spec = None
2608 hard_disk_exist = False
2609 disk_modified_for_spec = False
2610 disk_modified_for_disk = False
2611 disk_unit_number = ctl['disk'][j]['unit_number']
2612 # from attached disk list find the specified one
2613 if len(disk_list) != 0:
2614 for disk in disk_list:
2615 if disk.unitNumber == disk_unit_number:
2616 hard_disk = disk
2617 hard_disk_exist = True
2618 break
2619 # if find the disk do reconfigure
2620 if hard_disk_exist:
2621 hard_disk_spec = vim.vm.device.VirtualDeviceSpec()
2622 hard_disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
2623 hard_disk_spec.device = hard_disk
2624 disk_modified_for_spec = self.set_disk_parameters(hard_disk_spec, ctl['disk'][j], reconfigure=True)
2625 # if no disk or the specified one not exist do create new disk
2626 if len(disk_list) == 0 or not hard_disk_exist:
2627 hard_disk = self.device_helper.create_hard_disk(disk_ctl_spec, disk_unit_number)
2628 hard_disk.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create
2629 disk_modified_for_disk = self.set_disk_parameters(hard_disk, ctl['disk'][j])
2630
2631 # Only update the configspec that will be applied in reconfigure_vm if something actually changed
2632 if disk_modified_for_spec:
2633 self.change_detected = True
2634 self.configspec.deviceChange.append(hard_disk_spec)
2635 if disk_modified_for_disk:
2636 self.change_detected = True
2637 self.configspec.deviceChange.append(hard_disk)
2638
2639 def configure_disks(self, vm_obj):
2640 # Ignore empty disk list, this permits to keep disks when deploying a template/cloning a VM
2641 if not self.params['disk']:
2642 return
2643
2644 # if one of 'controller_type', 'controller_number', 'unit_number' parameters set in one of disks' configuration
2645 # will call configure_multiple_controllers_disks() function
2646 # do not support mixed old scsi disks configuration and new multiple controller types of disks configuration
2647 configure_multiple_ctl = False
2648 for disk_spec in self.params.get('disk'):
2649 if disk_spec['controller_type'] or disk_spec['controller_number'] or disk_spec['unit_number']:
2650 configure_multiple_ctl = True
2651 break
2652 if configure_multiple_ctl:
2653 self.configure_multiple_controllers_disks(vm_obj)
2654 return
2655
2656 # do single controller type disks configuration
2657 scsi_ctls = self.get_vm_scsi_controllers(vm_obj)
2658
2659 # Create scsi controller only if we are deploying a new VM, not a template or reconfiguring
2660 if vm_obj is None or not scsi_ctls:
2661 scsi_ctl = self.device_helper.create_scsi_controller(self.get_scsi_type(), 0)
2662 self.change_detected = True
2663 self.configspec.deviceChange.append(scsi_ctl)
2664 else:
2665 scsi_ctl = scsi_ctls[0]
2666
2667 disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)] \
2668 if vm_obj is not None else None
2669
2670 if disks is not None and self.params.get('disk') and len(self.params.get('disk')) < len(disks):
2671 self.module.fail_json(msg="Provided disks configuration has less disks than "
2672 "the target object (%d vs %d)" % (len(self.params.get('disk')), len(disks)))
2673
2674 disk_index = 0
2675 disk_index_scsi = 0
2676 for expected_disk_spec in self.params.get('disk'):
2677 disk_modified = False
2678 # If we are manipulating and existing objects which has disks and disk_index is in disks
2679 if vm_obj is not None and disks is not None and disk_index < len(disks):
2680 diskspec = vim.vm.device.VirtualDeviceSpec()
2681 # set the operation to edit so that it knows to keep other settings
2682 diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit
2683 diskspec.device = disks[disk_index]
2684 else:
2685 diskspec = self.device_helper.create_hard_disk(scsi_ctl, disk_index_scsi)
2686 diskspec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
2687 disk_modified = True
2688
2689 # increment index for next disk search
2690 disk_index += 1
2691 disk_index_scsi += 1
2692 # index 7 is reserved to SCSI controller
2693 if disk_index_scsi == 7:
2694 disk_index_scsi += 1
2695
2696 if expected_disk_spec['disk_mode']:
2697 disk_mode = expected_disk_spec.get('disk_mode', 'persistent')
2698
2699 if (vm_obj and diskspec.device.backing.diskMode != disk_mode) or (vm_obj is None):
2700 diskspec.device.backing.diskMode = disk_mode
2701 disk_modified = True
2702 else:
2703 diskspec.device.backing.diskMode = "persistent"
2704
2705 # is it thin?
2706 if expected_disk_spec['type']:
2707 disk_type = expected_disk_spec.get('type', '').lower()
2708 if disk_type == 'thin':
2709 diskspec.device.backing.thinProvisioned = True
2710 elif disk_type == 'eagerzeroedthick':
2711 diskspec.device.backing.eagerlyScrub = True
2712
2713 if expected_disk_spec['filename']:
2714 self.add_existing_vmdk(vm_obj, expected_disk_spec, diskspec, scsi_ctl)
2715 continue
2716
2717 # Only create virtual device if not backed by vmdk in original template
2718 if diskspec.device.backing.fileName == '':
2719 diskspec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create
2720
2721 # which datastore?
2722 if expected_disk_spec.get('datastore'):
2723 # TODO: This is already handled by the relocation spec,
2724 # but it needs to eventually be handled for all the
2725 # other disks defined
2726 pass
2727
2728 kb = self.get_configured_disk_size(expected_disk_spec)
2729 # VMware doesn't allow to reduce disk sizes
2730 if kb < diskspec.device.capacityInKB:
2731 self.module.fail_json(
2732 msg="Given disk size is smaller than found (%d < %d). Reducing disks is not allowed." %
2733 (kb, diskspec.device.capacityInKB))
2734
2735 if kb != diskspec.device.capacityInKB or disk_modified:
2736 diskspec.device.capacityInKB = kb
2737 self.configspec.deviceChange.append(diskspec)
2738
2739 self.change_detected = True
2740
2741 def select_host(self):
2742 hostsystem = self.cache.get_esx_host(self.params['esxi_hostname'])
2743 if not hostsystem:
2744 self.module.fail_json(msg='Failed to find ESX host "%(esxi_hostname)s"' % self.params)
2745 if hostsystem.runtime.connectionState != 'connected' or hostsystem.runtime.inMaintenanceMode:
2746 self.module.fail_json(msg='ESXi "%(esxi_hostname)s" is in invalid state or in maintenance mode.' % self.params)
2747 return hostsystem
2748
2749 def autoselect_datastore(self):
2750 datastore = None
2751 datastores = self.cache.get_all_objs(self.content, [vim.Datastore])
2752
2753 if datastores is None or len(datastores) == 0:
2754 self.module.fail_json(msg="Unable to find a datastore list when autoselecting")
2755
2756 datastore_freespace = 0
2757 for ds in datastores:
2758 if not self.is_datastore_valid(datastore_obj=ds):
2759 continue
2760
2761 if ds.summary.freeSpace > datastore_freespace:
2762 datastore = ds
2763 datastore_freespace = ds.summary.freeSpace
2764
2765 return datastore
2766
2767 def select_datastore(self, vm_obj=None):
2768 datastore = None
2769 datastore_name = None
2770
2771 if self.params['disk']:
2772 # TODO: really use the datastore for newly created disks
2773 if self.params['disk'][0]['autoselect_datastore']:
2774 datastores = []
2775
2776 if self.params['cluster']:
2777 cluster = self.find_cluster_by_name(self.params['cluster'], self.content)
2778
2779 for host in cluster.host:
2780 for mi in host.configManager.storageSystem.fileSystemVolumeInfo.mountInfo:
2781 if mi.volume.type == "VMFS" or mi.volume.type == "NFS":
2782 datastores.append(self.cache.find_obj(self.content, [vim.Datastore], mi.volume.name))
2783 elif self.params['esxi_hostname']:
2784 host = self.find_hostsystem_by_name(self.params['esxi_hostname'])
2785
2786 for mi in host.configManager.storageSystem.fileSystemVolumeInfo.mountInfo:
2787 if mi.volume.type == "VMFS" or mi.volume.type == "NFS":
2788 datastores.append(self.cache.find_obj(self.content, [vim.Datastore], mi.volume.name))
2789 else:
2790 datastores = self.cache.get_all_objs(self.content, [vim.Datastore])
2791 datastores = [x for x in datastores if self.cache.get_parent_datacenter(x).name == self.params['datacenter']]
2792
2793 datastore_freespace = 0
2794 for ds in datastores:
2795 if not self.is_datastore_valid(datastore_obj=ds):
2796 continue
2797
2798 if (ds.summary.freeSpace > datastore_freespace) or (ds.summary.freeSpace == datastore_freespace and not datastore):
2799 # If datastore field is provided, filter destination datastores
2800 if self.params['disk'][0]['datastore'] and ds.name.find(self.params['disk'][0]['datastore']) < 0:
2801 continue
2802
2803 datastore = ds
2804 datastore_name = datastore.name
2805 datastore_freespace = ds.summary.freeSpace
2806
2807 elif self.params['disk'][0]['datastore']:
2808 datastore_name = self.params['disk'][0]['datastore']
2809 # Check if user has provided datastore cluster first
2810 datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name)
2811 if datastore_cluster:
2812 # If user specified datastore cluster so get recommended datastore
2813 datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster)
2814 # Check if get_recommended_datastore or user specified datastore exists or not
2815 datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name)
2816 else:
2817 self.module.fail_json(msg="Either datastore or autoselect_datastore should be provided to select datastore")
2818
2819 if not datastore and self.params['template']:
2820 # use the template's existing DS
2821 disks = [x for x in vm_obj.config.hardware.device if isinstance(x, vim.vm.device.VirtualDisk)]
2822 if disks:
2823 datastore = disks[0].backing.datastore
2824 datastore_name = datastore.name
2825 # validation
2826 if datastore:
2827 dc = self.cache.get_parent_datacenter(datastore)
2828 if dc.name != self.params['datacenter']:
2829 datastore = self.autoselect_datastore()
2830 datastore_name = datastore.name
2831
2832 if not datastore:
2833 if len(self.params['disk']) != 0 or self.params['template'] is None:
2834 self.module.fail_json(msg="Unable to find the datastore with given parameters."
2835 " This could mean, %s is a non-existent virtual machine and module tried to"
2836 " deploy it as new virtual machine with no disk. Please specify disks parameter"
2837 " or specify template to clone from." % self.params['name'])
2838 self.module.fail_json(msg="Failed to find a matching datastore")
2839
2840 return datastore, datastore_name
2841
2842 def obj_has_parent(self, obj, parent):
2843 if obj is None and parent is None:
2844 raise AssertionError()
2845 current_parent = obj
2846
2847 while True:
2848 if current_parent.name == parent.name:
2849 return True
2850
2851 # Check if we have reached till root folder
2852 moid = current_parent._moId
2853 if moid in ['group-d1', 'ha-folder-root']:
2854 return False
2855
2856 current_parent = current_parent.parent
2857 if current_parent is None:
2858 return False
2859
2860 def get_scsi_type(self):
2861 disk_controller_type = self.params['hardware']['scsi']
2862 if disk_controller_type is not None:
2863 return disk_controller_type
2864 return "paravirtual"
2865
2866 def find_folder(self, searchpath):
2867 """ Walk inventory objects one position of the searchpath at a time """
2868
2869 # split the searchpath so we can iterate through it
2870 paths = [x.replace('/', '') for x in searchpath.split('/')]
2871 paths_total = len(paths) - 1
2872 position = 0
2873
2874 # recursive walk while looking for next element in searchpath
2875 root = self.content.rootFolder
2876 while root and position <= paths_total:
2877 change = False
2878 if hasattr(root, 'childEntity'):
2879 for child in root.childEntity:
2880 if child.name == paths[position]:
2881 root = child
2882 position += 1
2883 change = True
2884 break
2885 elif isinstance(root, vim.Datacenter):
2886 if hasattr(root, 'vmFolder'):
2887 if root.vmFolder.name == paths[position]:
2888 root = root.vmFolder
2889 position += 1
2890 change = True
2891 else:
2892 root = None
2893
2894 if not change:
2895 root = None
2896
2897 return root
2898
2899 def get_resource_pool(self, cluster=None, host=None, resource_pool=None):
2900 """ Get a resource pool, filter on cluster, esxi_hostname or resource_pool if given """
2901
2902 cluster_name = cluster or self.params.get('cluster', None)
2903 host_name = host or self.params.get('esxi_hostname', None)
2904 resource_pool_name = resource_pool or self.params.get('resource_pool', None)
2905
2906 # get the datacenter object
2907 datacenter = find_obj(self.content, [vim.Datacenter], self.params['datacenter'])
2908 if not datacenter:
2909 self.module.fail_json(msg='Unable to find datacenter "%s"' % self.params['datacenter'])
2910
2911 # if cluster is given, get the cluster object
2912 if cluster_name:
2913 cluster = find_obj(self.content, [vim.ComputeResource], cluster_name, folder=datacenter)
2914 if not cluster:
2915 self.module.fail_json(msg='Unable to find cluster "%s"' % cluster_name)
2916 # if host is given, get the cluster object using the host
2917 elif host_name:
2918 host = find_obj(self.content, [vim.HostSystem], host_name, folder=datacenter)
2919 if not host:
2920 self.module.fail_json(msg='Unable to find host "%s"' % host_name)
2921 cluster = host.parent
2922 else:
2923 cluster = None
2924
2925 # get resource pools limiting search to cluster or datacenter
2926 resource_pool = find_obj(self.content, [vim.ResourcePool], resource_pool_name, folder=cluster or datacenter)
2927 if not resource_pool:
2928 if resource_pool_name:
2929 self.module.fail_json(msg='Unable to find resource_pool "%s"' % resource_pool_name)
2930 else:
2931 self.module.fail_json(msg='Unable to find resource pool, need esxi_hostname, resource_pool, or cluster')
2932 return resource_pool
2933
2934 def deploy_vm(self):
2935 # https://github.com/vmware/pyvmomi-community-samples/blob/master/samples/clone_vm.py
2936 # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.CloneSpec.html
2937 # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.vm.ConfigSpec.html
2938 # https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html
2939
2940 # FIXME:
2941 # - static IPs
2942
2943 self.folder = self.params.get('folder', None)
2944 if self.folder is None:
2945 self.module.fail_json(msg="Folder is required parameter while deploying new virtual machine")
2946
2947 # Prepend / if it was missing from the folder path, also strip trailing slashes
2948 if not self.folder.startswith('/'):
2949 self.folder = '/%(folder)s' % self.params
2950 self.folder = self.folder.rstrip('/')
2951
2952 datacenter = self.cache.find_obj(self.content, [vim.Datacenter], self.params['datacenter'])
2953 if datacenter is None:
2954 self.module.fail_json(msg='No datacenter named %(datacenter)s was found' % self.params)
2955
2956 dcpath = compile_folder_path_for_object(datacenter)
2957
2958 # Nested folder does not have trailing /
2959 if not dcpath.endswith('/'):
2960 dcpath += '/'
2961
2962 # Check for full path first in case it was already supplied
2963 if self.folder.startswith(
2964 dcpath + self.params["datacenter"] + "/vm"
2965 ) or self.folder.startswith(dcpath + "/" + self.params["datacenter"] + "/vm"):
2966 fullpath = self.folder
2967 elif self.folder.startswith("/vm/") or self.folder == "/vm":
2968 fullpath = "%s%s%s" % (dcpath, self.params["datacenter"], self.folder)
2969 elif self.folder.startswith("/"):
2970 fullpath = "%s%s/vm%s" % (dcpath, self.params["datacenter"], self.folder)
2971 else:
2972 fullpath = "%s%s/vm/%s" % (dcpath, self.params["datacenter"], self.folder)
2973
2974 f_obj = self.content.searchIndex.FindByInventoryPath(fullpath)
2975
2976 # abort if no strategy was successful
2977 if f_obj is None:
2978 # Add some debugging values in failure.
2979 details = {
2980 'datacenter': datacenter.name,
2981 'datacenter_path': dcpath,
2982 'folder': self.folder,
2983 'full_search_path': fullpath,
2984 }
2985 self.module.fail_json(msg='No folder %s matched in the search path : %s' % (self.folder, fullpath),
2986 details=details)
2987
2988 destfolder = f_obj
2989
2990 if self.params['template']:
2991 vm_obj = self.get_vm_or_template(template_name=self.params['template'])
2992 if vm_obj is None:
2993 self.module.fail_json(msg="Could not find a template named %(template)s" % self.params)
2994 if self.params['guest_id'] is not None and vm_obj.summary.config.guestId is not None and self.params['guest_id'] != vm_obj.summary.config.guestId:
2995 details = {
2996 'vm_guest_id': self.params['guest_id'],
2997 'template_guest_id': vm_obj.summary.config.guestId,
2998 }
2999 self.module.fail_json(msg="Could not create vm from template with different guest_ids",
3000 details=details)
3001
3002 else:
3003 vm_obj = None
3004
3005 # always get a resource_pool
3006 resource_pool = self.get_resource_pool()
3007
3008 # set the destination datastore for VM & disks
3009 if self.params['datastore']:
3010 # Give precedence to datastore value provided by user
3011 # User may want to deploy VM to specific datastore.
3012 datastore_name = self.params['datastore']
3013 # Check if user has provided datastore cluster first
3014 datastore_cluster = self.cache.find_obj(self.content, [vim.StoragePod], datastore_name)
3015 if datastore_cluster:
3016 # If user specified datastore cluster so get recommended datastore
3017 datastore_name = self.get_recommended_datastore(datastore_cluster_obj=datastore_cluster)
3018 # Check if get_recommended_datastore or user specified datastore exists or not
3019 datastore = self.cache.find_obj(self.content, [vim.Datastore], datastore_name)
3020 else:
3021 (datastore, datastore_name) = self.select_datastore(vm_obj)
3022
3023 self.configspec = vim.vm.ConfigSpec()
3024 self.configspec.deviceChange = []
3025 # create the relocation spec
3026 self.relospec = vim.vm.RelocateSpec()
3027 self.relospec.deviceChange = []
3028 self.configure_guestid(vm_obj=vm_obj, vm_creation=True)
3029 self.configure_cpu_and_memory(vm_obj=vm_obj, vm_creation=True)
3030 self.configure_hardware_params(vm_obj=vm_obj)
3031 self.configure_encryption_params(vm_obj=vm_obj)
3032 self.configure_resource_alloc_info(vm_obj=vm_obj)
3033 self.configure_vapp_properties(vm_obj=vm_obj)
3034 self.configure_disks(vm_obj=vm_obj)
3035 self.configure_network(vm_obj=vm_obj)
3036 self.configure_cdrom(vm_obj=vm_obj)
3037 self.configure_nvdimm(vm_obj=vm_obj)
3038
3039 # Find if we need network customizations (find keys in dictionary that requires customizations)
3040 network_changes = False
3041 for nw in self.params['networks']:
3042 for key in nw:
3043 # We don't need customizations for these keys
3044 if key == 'type' and nw['type'] == 'dhcp':
3045 network_changes = True
3046 break
3047 if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected', 'dvswitch_name'):
3048 network_changes = True
3049 break
3050
3051 if any(v is not None for v in self.params['customization'].values()) or network_changes or self.params.get('customization_spec') is not None:
3052 self.customize_vm(vm_obj=vm_obj)
3053
3054 clonespec = None
3055 clone_method = None
3056 try:
3057 if self.params['template']:
3058 # Only select specific host when ESXi hostname is provided
3059 if self.params['esxi_hostname']:
3060 self.relospec.host = self.select_host()
3061 self.relospec.datastore = datastore
3062
3063 # Convert disk present in template if is set
3064 if self.params['convert']:
3065 for device in vm_obj.config.hardware.device:
3066 if isinstance(device, vim.vm.device.VirtualDisk):
3067 disk_locator = vim.vm.RelocateSpec.DiskLocator()
3068 disk_locator.diskBackingInfo = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
3069 if self.params['convert'] == 'thin':
3070 disk_locator.diskBackingInfo.thinProvisioned = True
3071 if self.params['convert'] == 'eagerzeroedthick':
3072 disk_locator.diskBackingInfo.eagerlyScrub = True
3073 if self.params['convert'] == 'thick':
3074 disk_locator.diskBackingInfo.diskMode = "persistent"
3075 disk_locator.diskId = device.key
3076 disk_locator.datastore = datastore
3077 self.relospec.disk.append(disk_locator)
3078
3079 # https://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.vm.RelocateSpec.html
3080 # > pool: For a clone operation from a template to a virtual machine, this argument is required.
3081 self.relospec.pool = resource_pool
3082 linked_clone = self.params.get('linked_clone')
3083 snapshot_src = self.params.get('snapshot_src', None)
3084 if linked_clone:
3085 if snapshot_src is not None:
3086 self.relospec.diskMoveType = vim.vm.RelocateSpec.DiskMoveOptions.createNewChildDiskBacking
3087 else:
3088 self.module.fail_json(msg="Parameter 'linked_src' and 'snapshot_src' are"
3089 " required together for linked clone operation.")
3090
3091 clonespec = vim.vm.CloneSpec(template=self.params['is_template'], location=self.relospec)
3092 if self.customspec:
3093 clonespec.customization = self.customspec
3094
3095 if snapshot_src is not None:
3096 if vm_obj.snapshot is None:
3097 self.module.fail_json(msg="No snapshots present for virtual machine or template [%(template)s]" % self.params)
3098 snapshot = self.get_snapshots_by_name_recursively(snapshots=vm_obj.snapshot.rootSnapshotList,
3099 snapname=snapshot_src)
3100 if len(snapshot) != 1:
3101 self.module.fail_json(msg='virtual machine "%(template)s" does not contain'
3102 ' snapshot named "%(snapshot_src)s"' % self.params)
3103
3104 clonespec.snapshot = snapshot[0].snapshot
3105
3106 clonespec.config = self.configspec
3107 clone_method = 'Clone'
3108 try:
3109 task = vm_obj.Clone(folder=destfolder, name=self.params['name'], spec=clonespec)
3110 except vim.fault.NoPermission as e:
3111 self.module.fail_json(msg="Failed to clone virtual machine %s to folder %s "
3112 "due to permission issue: %s" % (self.params['name'],
3113 destfolder,
3114 to_native(e.msg)))
3115 self.change_detected = True
3116 else:
3117 # ConfigSpec require name for VM creation
3118 self.configspec.name = self.params['name']
3119 self.configspec.files = vim.vm.FileInfo(logDirectory=None,
3120 snapshotDirectory=None,
3121 suspendDirectory=None,
3122 vmPathName="[" + datastore_name + "]")
3123 esx_host = None
3124 # Only select specific host when ESXi hostname is provided
3125 if self.params['esxi_hostname']:
3126 esx_host = self.select_host()
3127
3128 clone_method = 'CreateVM_Task'
3129 try:
3130 task = destfolder.CreateVM_Task(config=self.configspec, pool=resource_pool, host=esx_host)
3131 except vmodl.fault.InvalidRequest as e:
3132 self.module.fail_json(msg="Failed to create virtual machine due to invalid configuration "
3133 "parameter %s" % to_native(e.msg))
3134 except vim.fault.RestrictedVersion as e:
3135 self.module.fail_json(msg="Failed to create virtual machine due to "
3136 "product versioning restrictions: %s" % to_native(e.msg))
3137 self.change_detected = True
3138 error_msg = self.wait_for_task(task)
3139 except TypeError as e:
3140 self.module.fail_json(msg="TypeError was returned, please ensure to give correct inputs. %s" % to_text(e))
3141
3142 if task.info.state == 'error':
3143 # https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2021361
3144 # https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2173
3145
3146 # provide these to the user for debugging
3147 clonespec_json = serialize_spec(clonespec)
3148 configspec_json = serialize_spec(self.configspec)
3149 kwargs = {
3150 'changed': self.change_applied,
3151 'failed': True,
3152 'msg': error_msg,
3153 'clonespec': clonespec_json,
3154 'configspec': configspec_json,
3155 'clone_method': clone_method
3156 }
3157
3158 return kwargs
3159 else:
3160 # set annotation
3161 vm = task.info.result
3162 if self.params['annotation']:
3163 annotation_spec = vim.vm.ConfigSpec()
3164 annotation_spec.annotation = str(self.params['annotation'])
3165 task = vm.ReconfigVM_Task(annotation_spec)
3166 error_msg = self.wait_for_task(task)
3167 if task.info.state == 'error':
3168 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'annotation'}
3169
3170 if self.params['advanced_settings']:
3171 vm_custom_spec = vim.vm.ConfigSpec()
3172 self.customize_advanced_settings(vm_obj=vm, config_spec=vm_custom_spec)
3173 task = vm.ReconfigVM_Task(vm_custom_spec)
3174 error_msg = self.wait_for_task(task)
3175 if task.info.state == 'error':
3176 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'advanced_settings'}
3177
3178 if self.params['customvalues']:
3179 self.customize_customvalues(vm_obj=vm)
3180
3181 if self.params['wait_for_ip_address'] or self.params['wait_for_customization'] or self.params['state'] in ['poweredon', 'powered-on', 'restarted']:
3182 set_vm_power_state(self.content, vm, 'poweredon', force=False)
3183
3184 if self.params['wait_for_ip_address']:
3185 wait_for_vm_ip(self.content, vm, self.params['wait_for_ip_address_timeout'])
3186
3187 if self.params['wait_for_customization']:
3188 is_customization_ok = self.wait_for_customization(vm=vm, timeout=self.params['wait_for_customization_timeout'])
3189 if not is_customization_ok:
3190 vm_facts = self.gather_facts(vm)
3191 return {'changed': self.change_applied, 'failed': True,
3192 'msg': 'Customization failed. For detailed information see warnings',
3193 'instance': vm_facts, 'op': 'customization'}
3194
3195 vm_facts = self.gather_facts(vm)
3196 return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts}
3197
3198 def get_snapshots_by_name_recursively(self, snapshots, snapname):
3199 snap_obj = []
3200 for snapshot in snapshots:
3201 if snapshot.name == snapname:
3202 snap_obj.append(snapshot)
3203 else:
3204 snap_obj = snap_obj + self.get_snapshots_by_name_recursively(snapshot.childSnapshotList, snapname)
3205 return snap_obj
3206
3207 def reconfigure_vm(self):
3208 self.configspec = vim.vm.ConfigSpec()
3209 self.configspec.deviceChange = []
3210 # create the relocation spec
3211 self.relospec = vim.vm.RelocateSpec()
3212 self.relospec.deviceChange = []
3213 self.configure_guestid(vm_obj=self.current_vm_obj)
3214 self.configure_cpu_and_memory(vm_obj=self.current_vm_obj)
3215 err = self.configure_hardware_params(vm_obj=self.current_vm_obj)
3216 if err is not None:
3217 return err
3218 self.configure_encryption_params(vm_obj=self.current_vm_obj)
3219 self.configure_disks(vm_obj=self.current_vm_obj)
3220 self.configure_network(vm_obj=self.current_vm_obj)
3221 self.configure_cdrom(vm_obj=self.current_vm_obj)
3222 self.configure_nvdimm(vm_obj=self.current_vm_obj)
3223 self.customize_advanced_settings(vm_obj=self.current_vm_obj, config_spec=self.configspec)
3224 self.customize_customvalues(vm_obj=self.current_vm_obj)
3225 self.configure_resource_alloc_info(vm_obj=self.current_vm_obj)
3226 self.configure_vapp_properties(vm_obj=self.current_vm_obj)
3227
3228 if self.params['annotation'] and self.current_vm_obj.config.annotation != self.params['annotation']:
3229 self.configspec.annotation = str(self.params['annotation'])
3230 self.change_detected = True
3231
3232 if self.params['resource_pool']:
3233 self.relospec.pool = self.get_resource_pool()
3234
3235 if self.relospec.pool != self.current_vm_obj.resourcePool:
3236 self.tracked_changes['resourcePool'] = str(self.relospec.pool)
3237 if self.module.check_mode:
3238 self.change_applied = True
3239 else:
3240 task = self.current_vm_obj.RelocateVM_Task(spec=self.relospec)
3241 error_msg = self.wait_for_task(task)
3242 if task.info.state == 'error':
3243 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'relocate'}
3244
3245 # Only send VMware task if we see a modification
3246 if self.change_detected:
3247 self.tracked_changes['configspec'] = str(self.configspec)
3248 if self.module.check_mode:
3249 self.change_applied = True
3250 else:
3251 task = None
3252 try:
3253 task = self.current_vm_obj.ReconfigVM_Task(spec=self.configspec)
3254 except vim.fault.RestrictedVersion as e:
3255 self.module.fail_json(msg="Failed to reconfigure virtual machine due to"
3256 " product versioning restrictions: %s" % to_native(e.msg))
3257 error_msg = self.wait_for_task(task)
3258 if task.info.state == 'error':
3259 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'reconfig'}
3260
3261 # Rename VM
3262 if self.params['uuid'] and self.params['name'] and self.params['name'] != self.current_vm_obj.config.name:
3263 self.tracked_changes['name'] = self.params['name']
3264 if self.module.check_mode:
3265 self.change_applied = True
3266 else:
3267 task = self.current_vm_obj.Rename_Task(self.params['name'])
3268 error_msg = self.wait_for_task(task)
3269 if task.info.state == 'error':
3270 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'rename'}
3271
3272 # Mark VM as Template
3273 if self.params['is_template'] and not self.current_vm_obj.config.template:
3274 try:
3275 if not self.module.check_mode:
3276 self.current_vm_obj.MarkAsTemplate()
3277 self.change_applied = True
3278 self.tracked_changes['MarkAsTemplate'] = True
3279 except vmodl.fault.NotSupported as e:
3280 self.module.fail_json(msg="Failed to mark virtual machine [%s] "
3281 "as template: %s" % (self.params['name'], e.msg))
3282
3283 # Mark Template as VM
3284 elif not self.params['is_template'] and self.current_vm_obj.config.template:
3285 resource_pool = self.get_resource_pool()
3286 kwargs = dict(pool=resource_pool)
3287
3288 if self.params.get('esxi_hostname', None):
3289 host_system_obj = self.select_host()
3290 kwargs.update(host=host_system_obj)
3291
3292 try:
3293 if not self.module.check_mode:
3294 self.current_vm_obj.MarkAsVirtualMachine(**kwargs)
3295 self.change_applied = True
3296 self.tracked_changes['MarkAsVirtualMachine'] = True
3297 except vim.fault.InvalidState as invalid_state:
3298 self.module.fail_json(msg="Virtual machine is not marked"
3299 " as template : %s" % to_native(invalid_state.msg))
3300 except vim.fault.InvalidDatastore as invalid_ds:
3301 self.module.fail_json(msg="Converting template to virtual machine"
3302 " operation cannot be performed on the"
3303 " target datastores: %s" % to_native(invalid_ds.msg))
3304 except vim.fault.CannotAccessVmComponent as cannot_access:
3305 self.module.fail_json(msg="Failed to convert template to virtual machine"
3306 " as operation unable access virtual machine"
3307 " component: %s" % to_native(cannot_access.msg))
3308 except vmodl.fault.InvalidArgument as invalid_argument:
3309 self.module.fail_json(msg="Failed to convert template to virtual machine"
3310 " due to : %s" % to_native(invalid_argument.msg))
3311 except Exception as generic_exc:
3312 self.module.fail_json(msg="Failed to convert template to virtual machine"
3313 " due to generic error : %s" % to_native(generic_exc))
3314
3315 # add customize existing VM after VM re-configure
3316 if self.params['customization']['existing_vm']:
3317 if self.current_vm_obj.config.template:
3318 self.module.fail_json(msg="VM is template, not support guest OS customization.")
3319 if self.current_vm_obj.runtime.powerState != vim.VirtualMachinePowerState.poweredOff and not self.module.check_mode:
3320 self.module.fail_json(msg="VM is not in poweroff state, can not do guest OS customization.")
3321 # TODO not sure if it is possible to query the current customspec to compare against the one being provided to check in check mode.
3322 # Maybe by breaking down the individual fields and querying, but it needs more research.
3323 # For now, assume changed...
3324 self.tracked_changes['customization'] = True
3325 if self.module.check_mode:
3326 self.change_applied = True
3327 else:
3328 cus_result = self.customize_exist_vm()
3329 if cus_result['failed']:
3330 return cus_result
3331
3332 vm_facts = self.gather_facts(self.current_vm_obj)
3333 return {'changed': self.change_applied, 'failed': False, 'instance': vm_facts, 'changes': self.tracked_changes}
3334
3335 def customize_exist_vm(self):
3336 task = None
3337 # Find if we need network customizations (find keys in dictionary that requires customizations)
3338 network_changes = False
3339 for nw in self.params['networks']:
3340 for key in nw:
3341 # We don't need customizations for these keys
3342 if key not in ('device_type', 'mac', 'name', 'vlan', 'type', 'start_connected', 'dvswitch_name'):
3343 network_changes = True
3344 break
3345 if any(v is not None for v in self.params['customization'].values()) or network_changes or self.params.get('customization_spec'):
3346 self.customize_vm(vm_obj=self.current_vm_obj)
3347 try:
3348 task = self.current_vm_obj.CustomizeVM_Task(self.customspec)
3349 except vim.fault.CustomizationFault as e:
3350 self.module.fail_json(msg="Failed to customization virtual machine due to CustomizationFault: %s" % to_native(e.msg))
3351 except vim.fault.RuntimeFault as e:
3352 self.module.fail_json(msg="failed to customization virtual machine due to RuntimeFault: %s" % to_native(e.msg))
3353 except Exception as e:
3354 self.module.fail_json(msg="failed to customization virtual machine due to fault: %s" % to_native(e.msg))
3355 error_msg = self.wait_for_task(task)
3356 if task.info.state == 'error':
3357 return {'changed': self.change_applied, 'failed': True, 'msg': error_msg, 'op': 'customize_exist'}
3358
3359 if self.params['wait_for_customization']:
3360 set_vm_power_state(self.content, self.current_vm_obj, 'poweredon', force=False)
3361 is_customization_ok = self.wait_for_customization(vm=self.current_vm_obj, timeout=self.params['wait_for_customization_timeout'])
3362 if not is_customization_ok:
3363 return {'changed': self.change_applied, 'failed': True,
3364 'msg': 'Customization failed. For detailed information see warnings',
3365 'op': 'wait_for_customize_exist'}
3366
3367 return {'changed': self.change_applied, 'failed': False}
3368
3369 def wait_for_task(self, task, poll_interval=1):
3370 """
3371 Wait for a VMware task to complete. Terminal states are 'error' and 'success'.
3372
3373 Inputs:
3374 - task: the task to wait for
3375 - poll_interval: polling interval to check the task, in seconds
3376
3377 Modifies:
3378 - self.change_applied
3379 """
3380 # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.Task.html
3381 # https://www.vmware.com/support/developer/vc-sdk/visdk25pubs/ReferenceGuide/vim.TaskInfo.html
3382 # https://github.com/virtdevninja/pyvmomi-community-samples/blob/master/samples/tools/tasks.py
3383 error_msg = ''
3384 while task.info.state not in ['error', 'success']:
3385 time.sleep(poll_interval)
3386
3387 if task.info.state == 'error':
3388 error_msg = task.info.error.msg
3389 if hasattr(task.info.error, 'faultMessage'):
3390 for fault in task.info.error.faultMessage:
3391 if hasattr(fault, 'message') and fault.message:
3392 error_msg += fault.message + ';'
3393 error_msg = error_msg.rstrip(';')
3394 self.change_applied = self.change_applied or task.info.state == 'success'
3395 return error_msg
3396
3397 def get_vm_events(self, vm, eventTypeIdList):
3398 byEntity = vim.event.EventFilterSpec.ByEntity(entity=vm, recursion="self")
3399 filterSpec = vim.event.EventFilterSpec(entity=byEntity, eventTypeId=eventTypeIdList)
3400 eventManager = self.content.eventManager
3401 return eventManager.QueryEvent(filterSpec)
3402
3403 def wait_for_customization(self, vm, timeout=3600, sleep=10):
3404 poll = int(timeout // sleep)
3405 thispoll = 0
3406 while thispoll <= poll:
3407 eventStarted = self.get_vm_events(vm, ['CustomizationStartedEvent'])
3408 if len(eventStarted):
3409 thispoll = 0
3410 while thispoll <= poll:
3411 eventsFinishedResult = self.get_vm_events(vm, ['CustomizationSucceeded', 'CustomizationFailed'])
3412 if len(eventsFinishedResult):
3413 if not isinstance(eventsFinishedResult[0], vim.event.CustomizationSucceeded):
3414 self.module.warn("Customization failed with error {%s}:{%s}"
3415 % (eventsFinishedResult[0]._wsdlName, eventsFinishedResult[0].fullFormattedMessage))
3416 return False
3417 else:
3418 return True
3419 else:
3420 time.sleep(sleep)
3421 thispoll += 1
3422 if len(eventsFinishedResult) == 0:
3423 self.module.warn('Waiting for customization result event timed out.')
3424 return False
3425 else:
3426 time.sleep(sleep)
3427 thispoll += 1
3428 if len(eventStarted):
3429 self.module.warn('Waiting for customization result event timed out.')
3430 else:
3431 self.module.warn('Waiting for customization start event timed out.')
3432 return False
3433
3434
3435 def main():
3436 argument_spec = base_argument_spec()
3437 argument_spec.update(
3438 state=dict(type='str', default='present',
3439 choices=['absent', 'poweredoff', 'powered-off',
3440 'poweredon', 'powered-on', 'present',
3441 'rebootguest', 'reboot-guest', 'restarted',
3442 'shutdownguest', 'shutdown-guest', 'suspended']),
3443 template=dict(type='str', aliases=['template_src']),
3444 is_template=dict(type='bool', default=False),
3445 annotation=dict(type='str', aliases=['notes']),
3446 customvalues=dict(type='list', default=[], elements='dict'),
3447 advanced_settings=dict(type='list', default=[], elements='dict'),
3448 name=dict(type='str'),
3449 name_match=dict(type='str', choices=['first', 'last'], default='first'),
3450 uuid=dict(type='str'),
3451 use_instance_uuid=dict(type='bool', default=False),
3452 folder=dict(type='str'),
3453 guest_id=dict(type='str'),
3454 disk=dict(
3455 type='list',
3456 default=[],
3457 elements='dict',
3458 options=dict(
3459 autoselect_datastore=dict(type='bool'),
3460 controller_number=dict(type='int', choices=[0, 1, 2, 3]),
3461 controller_type=dict(type='str', choices=['buslogic', 'lsilogic', 'paravirtual', 'lsilogicsas', 'sata', 'nvme']),
3462 datastore=dict(type='str'),
3463 disk_mode=dict(type='str', choices=['persistent', 'independent_persistent', 'independent_nonpersistent']),
3464 filename=dict(type='str'),
3465 size=dict(type='str'),
3466 size_gb=dict(type='int'),
3467 size_kb=dict(type='int'),
3468 size_mb=dict(type='int'),
3469 size_tb=dict(type='int'),
3470 type=dict(type='str', choices=['thin', 'eagerzeroedthick', 'thick']),
3471 unit_number=dict(type='int'),
3472 )
3473 ),
3474 nvdimm=dict(
3475 type='dict',
3476 default={},
3477 options=dict(
3478 state=dict(type='str', choices=['present', 'absent']),
3479 label=dict(type='str'),
3480 size_mb=dict(type='int', default=1024),
3481 )
3482 ),
3483 cdrom=dict(
3484 type='list',
3485 default=[],
3486 elements='dict',
3487 options=dict(
3488 type=dict(type='str', choices=['none', 'client', 'iso'], default='client'),
3489 iso_path=dict(type='str'),
3490 controller_type=dict(type='str', choices=['ide', 'sata'], default='ide'),
3491 controller_number=dict(type='int'),
3492 unit_number=dict(type='int'),
3493 state=dict(type='str', choices=['present', 'absent'], default='present'),
3494 )
3495 ),
3496 hardware=dict(
3497 type='dict',
3498 default={},
3499 options=dict(
3500 boot_firmware=dict(type='str', choices=['bios', 'efi']),
3501 cpu_limit=dict(type='int'),
3502 cpu_reservation=dict(type='int'),
3503 hotadd_cpu=dict(type='bool'),
3504 hotadd_memory=dict(type='bool'),
3505 hotremove_cpu=dict(type='bool'),
3506 vpmc_enabled=dict(type='bool'),
3507 max_connections=dict(type='int'),
3508 mem_limit=dict(type='int'),
3509 cpu_shares_level=dict(type='str', choices=['low', 'normal', 'high', 'custom']),
3510 mem_shares_level=dict(type='str', choices=['low', 'normal', 'high', 'custom']),
3511 cpu_shares=dict(type='int'),
3512 mem_shares=dict(type='int'),
3513 mem_reservation=dict(type='int', aliases=['memory_reservation']),
3514 memory_mb=dict(type='int'),
3515 memory_reservation_lock=dict(type='bool'),
3516 nested_virt=dict(type='bool'),
3517 num_cpu_cores_per_socket=dict(type='int'),
3518 num_cpus=dict(type='int'),
3519 scsi=dict(type='str', choices=['buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual']),
3520 secure_boot=dict(type='bool'),
3521 version=dict(type='str'),
3522 virt_based_security=dict(type='bool'),
3523 iommu=dict(type='bool')
3524 )),
3525 encryption=dict(
3526 type='dict',
3527 default={},
3528 options=dict(
3529 encrypted_vmotion=dict(type='str', choices=['disabled', 'opportunistic', 'required']),
3530 encrypted_ft=dict(type='str', choices=['disabled', 'opportunistic', 'required'])
3531 )),
3532 force=dict(type='bool', default=False),
3533 datacenter=dict(type='str', default='ha-datacenter'),
3534 esxi_hostname=dict(type='str'),
3535 cluster=dict(type='str'),
3536 wait_for_ip_address=dict(type='bool', default=False),
3537 wait_for_ip_address_timeout=dict(type='int', default=300),
3538 state_change_timeout=dict(type='int', default=0),
3539 snapshot_src=dict(type='str'),
3540 linked_clone=dict(type='bool', default=False),
3541 networks=dict(type='list', default=[], elements='dict'),
3542 resource_pool=dict(type='str'),
3543 customization=dict(
3544 type='dict',
3545 default={},
3546 options=dict(
3547 autologon=dict(type='bool'),
3548 autologoncount=dict(type='int'),
3549 dns_servers=dict(type='list', elements='str'),
3550 dns_suffix=dict(type='list', elements='str'),
3551 domain=dict(type='str'),
3552 domainadmin=dict(type='str'),
3553 domainadminpassword=dict(type='str', no_log=True),
3554 domain_ou=dict(type='str'),
3555 existing_vm=dict(type='bool'),
3556 fullname=dict(type='str'),
3557 hostname=dict(type='str'),
3558 hwclockUTC=dict(type='bool'),
3559 joindomain=dict(type='str'),
3560 joinworkgroup=dict(type='str'),
3561 orgname=dict(type='str'),
3562 password=dict(type='str', no_log=True),
3563 productid=dict(type='str'),
3564 runonce=dict(type='list', elements='str'),
3565 script_text=dict(type='str'),
3566 timezone=dict(type='str')
3567 )),
3568 customization_spec=dict(type='str', default=None),
3569 wait_for_customization=dict(type='bool', default=False),
3570 wait_for_customization_timeout=dict(type='int', default=3600),
3571 vapp_properties=dict(type='list', default=[], elements='dict'),
3572 datastore=dict(type='str'),
3573 convert=dict(type='str', choices=['thin', 'thick', 'eagerzeroedthick']),
3574 delete_from_inventory=dict(type='bool', default=False),
3575 )
3576
3577 module = AnsibleModule(argument_spec=argument_spec,
3578 supports_check_mode=True,
3579 mutually_exclusive=[
3580 ['cluster', 'esxi_hostname'],
3581 ],
3582 required_one_of=[
3583 ['name', 'uuid'],
3584 ],
3585 )
3586 result = {'failed': False, 'changed': False}
3587 pyv = PyVmomiHelper(module)
3588
3589 # Check requirements for virtualization based security
3590 if pyv.params['hardware']['virt_based_security']:
3591 if not pyv.params['hardware']['nested_virt']:
3592 pyv.module.fail_json(msg="Virtualization based security requires nested virtualization. Please enable nested_virt.")
3593
3594 if not pyv.params['hardware']['secure_boot']:
3595 pyv.module.fail_json(msg="Virtualization based security requires (U)EFI secure boot. Please enable secure_boot.")
3596
3597 if not pyv.params['hardware']['iommu']:
3598 pyv.module.fail_json(msg="Virtualization based security requires I/O MMU. Please enable iommu.")
3599
3600 # Check if the VM exists before continuing
3601 vm = pyv.get_vm()
3602
3603 # VM already exists
3604 if vm:
3605 if module.params['state'] == 'absent':
3606 # destroy it
3607 if module.check_mode:
3608 result.update(
3609 vm_name=vm.name,
3610 changed=True,
3611 current_powerstate=vm.summary.runtime.powerState.lower(),
3612 desired_operation='remove_vm',
3613 )
3614 module.exit_json(**result)
3615 if module.params['force']:
3616 # has to be poweredoff first
3617 set_vm_power_state(pyv.content, vm, 'poweredoff', module.params['force'])
3618 result = pyv.remove_vm(vm, module.params['delete_from_inventory'])
3619 elif module.params['state'] == 'present':
3620 # Note that check_mode is handled inside reconfigure_vm
3621 result = pyv.reconfigure_vm()
3622 elif module.params['state'] in ['poweredon', 'powered-on', 'poweredoff',
3623 'powered-off', 'restarted', 'suspended',
3624 'shutdownguest', 'shutdown-guest',
3625 'rebootguest', 'reboot-guest']:
3626 if module.check_mode:
3627 # Identify if the power state would have changed if not in check mode
3628 current_powerstate = vm.summary.runtime.powerState.lower()
3629 powerstate_will_change = False
3630 if ((current_powerstate == 'poweredon' and module.params['state'] not in ['poweredon', 'powered-on'])
3631 or (current_powerstate == 'poweredoff' and module.params['state']
3632 not in ['poweredoff', 'powered-off', 'shutdownguest', 'shutdown-guest'])
3633 or (current_powerstate == 'suspended' and module.params['state'] != 'suspended')):
3634 powerstate_will_change = True
3635
3636 result.update(
3637 vm_name=vm.name,
3638 changed=powerstate_will_change,
3639 current_powerstate=current_powerstate,
3640 desired_operation='set_vm_power_state',
3641 )
3642 module.exit_json(**result)
3643 # set powerstate
3644 tmp_result = set_vm_power_state(pyv.content, vm, module.params['state'], module.params['force'], module.params['state_change_timeout'])
3645 if tmp_result['changed']:
3646 result["changed"] = True
3647 if module.params['state'] in ['poweredon', 'powered-on', 'restarted', 'rebootguest', 'reboot-guest'] and module.params['wait_for_ip_address']:
3648 wait_result = wait_for_vm_ip(pyv.content, vm, module.params['wait_for_ip_address_timeout'])
3649 if not wait_result:
3650 module.fail_json(msg='Waiting for IP address timed out')
3651 tmp_result['instance'] = wait_result
3652 if not tmp_result["failed"]:
3653 result["failed"] = False
3654 result['instance'] = tmp_result['instance']
3655 if tmp_result["failed"]:
3656 result["failed"] = True
3657 result["msg"] = tmp_result["msg"]
3658 else:
3659 # This should not happen
3660 raise AssertionError()
3661 # VM doesn't exist
3662 else:
3663 if module.params['state'] in ['poweredon', 'powered-on', 'poweredoff', 'powered-off',
3664 'present', 'restarted', 'suspended']:
3665 if module.check_mode:
3666 result.update(
3667 changed=True,
3668 desired_operation='deploy_vm',
3669 )
3670 module.exit_json(**result)
3671 result = pyv.deploy_vm()
3672 if result['failed']:
3673 module.fail_json(msg='Failed to create a virtual machine : %s' % result['msg'])
3674
3675 if result['failed']:
3676 module.fail_json(**result)
3677 else:
3678 module.exit_json(**result)
3679
3680
3681 if __name__ == '__main__':
3682 main()