Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox_kvm.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2016, Abdoul Bah (@helldorado) <bahabdoul at gmail.com>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7
8 DOCUMENTATION = r"""
9 module: proxmox_kvm
10 short_description: Management of Qemu(KVM) Virtual Machines in Proxmox VE cluster
11 description:
12 - Allows you to create/delete/stop Qemu(KVM) Virtual Machines in Proxmox VE cluster.
13 author: "Abdoul Bah (@helldorado) <bahabdoul at gmail.com>"
14 attributes:
15 check_mode:
16 support: none
17 diff_mode:
18 support: none
19 options:
20 archive:
21 description:
22 - Specify a path to an archive to restore (instead of creating or cloning a VM).
23 type: str
24 acpi:
25 description:
26 - Specify if ACPI should be enabled/disabled.
27 type: bool
28 agent:
29 description:
30 - Specify if the QEMU Guest Agent should be enabled/disabled.
31 type: str
32 args:
33 description:
34 - Pass arbitrary arguments to kvm.
35 - This option is for experts only!
36 type: str
37 audio:
38 description:
39 - A hash/dictionary of audio devices for the VM. O(audio={"key":"value", "key":"value"}).
40 - Keys allowed are - C(audio[n]) where 0 ≤ n ≤ N.
41 - Values allowed are - C(device="ich9-intel-hda|intel-hda|AC97",driver="none|spice").
42 - C(device) is either V(ich9-intel-hda) or V(intel-hda) or V(AC97).
43 - Option C(driver) is V(none) or V(spice).
44 type: dict
45 autostart:
46 description:
47 - Specify if the VM should be automatically restarted after crash (currently ignored in PVE API).
48 type: bool
49 balloon:
50 description:
51 - Specify the amount of RAM for the VM in MB.
52 - Using zero disables the balloon driver.
53 type: int
54 bios:
55 description:
56 - Specify the BIOS implementation.
57 type: str
58 choices: ['seabios', 'ovmf']
59 boot:
60 description:
61 - Specify the boot order -> boot on floppy V(a), hard disk V(c), CD-ROM V(d), or network V(n).
62 - For newer versions of Proxmox VE, use a boot order like V(order=scsi0;net0;hostpci0).
63 - You can combine to set order.
64 - Network boot requires setting V(rng0) since PVE 8.3.5.
65 type: str
66 bootdisk:
67 description:
68 - Enable booting from specified disk. Format V((ide|sata|scsi|virtio\)\\d+).
69 type: str
70 cicustom:
71 description:
72 - 'Cloud-init: Specify custom files to replace the automatically generated ones at start.'
73 type: str
74 cipassword:
75 description:
76 - 'Cloud-init: password of default user to create.'
77 type: str
78 citype:
79 description:
80 - 'Cloud-init: Specifies the cloud-init configuration format.'
81 - The default depends on the configured operating system type (V(ostype)).
82 - We use the V(nocloud) format for Linux, and V(configdrive2) for Windows.
83 type: str
84 choices: ['nocloud', 'configdrive2']
85 ciupgrade:
86 description:
87 - 'Cloud-init: do an automatic package upgrade after the first boot.'
88 type: bool
89 ciuser:
90 description:
91 - 'Cloud-init: username of default user to create.'
92 type: str
93 clone:
94 description:
95 - Name of VM to be cloned. If O(vmid) is set, O(clone) can take an arbitrary value but is required for initiating the
96 clone.
97 type: str
98 cores:
99 description:
100 - Specify number of cores per socket.
101 type: int
102 cpu:
103 description:
104 - Specify emulated CPU type.
105 type: str
106 cpulimit:
107 description:
108 - Specify if CPU usage will be limited. Value V(0) indicates no CPU limit.
109 - If the computer has 2 CPUs, it has total of '2' CPU time.
110 type: int
111 cpuunits:
112 description:
113 - Specify CPU weight for a VM.
114 - You can disable fair-scheduler configuration by setting this to V(0).
115 type: int
116 delete:
117 description:
118 - Specify a list of settings you want to delete.
119 type: str
120 description:
121 description:
122 - Specify the description for the VM. Only used on the configuration web interface.
123 - This is saved as comment inside the configuration file.
124 type: str
125 destroy_unreferenced_disks:
126 description:
127 - Remove unreferenced disks that belong to the virtual machine.
128 - Volumes referenced in the config will always be removed.
129 - Used with O(state=absent).
130 type: bool
131 default: false
132 digest:
133 description:
134 - Specify if to prevent changes if current configuration file has different SHA1 digest.
135 - This can be used to prevent concurrent modifications.
136 type: str
137 efidisk0:
138 description:
139 - Specify a hash/dictionary of EFI disk options.
140 - Requires O(bios=ovmf) to be set to be able to use it.
141 type: dict
142 suboptions:
143 storage:
144 description:
145 - V(storage) is the storage identifier where to create the disk.
146 type: str
147 format:
148 description:
149 - V(format) is the drive's backing file's data format.
150 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-pvesm.html), tables
151 3 to 14, to find out format supported by the provided storage backend.
152 type: str
153 efitype:
154 description:
155 - V(efitype) indicates the size of the EFI disk.
156 - V(2m) will allow for a 2MB EFI disk, which will be enough to persist boot order and new boot entries.
157 - V(4m) will allow for a 4MB EFI disk, which will additionally allow to store EFI keys in order to enable Secure
158 Boot.
159 type: str
160 choices:
161 - 2m
162 - 4m
163 pre_enrolled_keys:
164 description:
165 - V(pre_enrolled_keys) indicates whether EFI keys for Secure Boot should be enrolled V(1) in the VM firmware upon
166 creation or not (0).
167 - If set to V(1), Secure Boot will also be enabled by default when the VM is created.
168 type: bool
169 force:
170 description:
171 - If V(true), allows forceful power operations (stop, reset).
172 - When used with O(state=stopped), attempts a graceful shutdown
173 and if the VM is still running after O(timeout), it will be forcefully powered off.
174 - When used with O(state=restarted), performs reset (power off and on) and not a graceful reboot.
175 type: bool
176 format:
177 description:
178 - Target drive's backing file's data format.
179 - Used only with clone.
180 - Use O(format=unspecified) and O(full=false) for a linked clone.
181 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-pvesm.html), tables
182 3 to 14, to find out format supported by the provided storage backend.
183 - Not specifying this option is equivalent to setting it to V(unspecified).
184 type: str
185 choices: ["cloop", "cow", "qcow", "qcow2", "qed", "raw", "vmdk", "unspecified"]
186 freeze:
187 description:
188 - Specify if PVE should freeze CPU at startup (use 'c' monitor command to start execution).
189 type: bool
190 full:
191 description:
192 - Create a full copy of all disk. This is always done when you clone a normal VM.
193 - For VM templates, we try to create a linked clone by default.
194 - Used only with clone.
195 type: bool
196 default: true
197 hookscript:
198 description:
199 - Script that will be executed during various steps in the containers lifetime.
200 type: str
201 hostpci:
202 description:
203 - Specify a hash/dictionary of map host pci devices into guest. O(hostpci='{"key":"value", "key":"value"}').
204 - Keys allowed are - C(hostpci[n]) where 0 ≤ n ≤ N.
205 - Values allowed are - V("host="HOSTPCIID[;HOSTPCIID2...]",pcie="1|0",rombar="1|0",x-vga="1|0"").
206 - The C(host) parameter is Host PCI device pass through. HOSTPCIID syntax is V(bus:dev.func) (hexadecimal numbers).
207 - V(pcie=boolean) V(default=0) Choose the PCI-express bus (needs the q35 machine model).
208 - V(rombar=boolean) V(default=1) Specify whether or not the device's ROM will be visible in the guest's memory map.
209 - V(x-vga=boolean) V(default=0) Enable vfio-vga device support.
210 - /!\ This option allows direct access to host hardware. So it is no longer possible to migrate such machines - use
211 with special care.
212 type: dict
213 hotplug:
214 description:
215 - Selectively enable hotplug features.
216 - This is a comma separated list of hotplug features V(network), V(disk), V(cpu), V(memory), and V(usb).
217 - Value 0 disables hotplug completely and value 1 is an alias for the default V(network,disk,usb).
218 type: str
219 hugepages:
220 description:
221 - Enable/disable hugepages memory.
222 type: str
223 choices: ['any', '2', '1024']
224 ide:
225 description:
226 - A hash/dictionary of volume used as IDE hard disk or CD-ROM.
227 - Keys must be C(ide[n]) where 0 ≤ n ≤ 3.
228 - Values are strings containing comma-separated options in formats accepted by Proxmox VE.
229 - 'Examples: V("<storage>:10,format=qcow2") for a disk, V("<storage>:cloudinit,format=qcow2") for cloud-init,
230 V("<storage>:iso/debian.iso,media=cdrom") for an ISO-backed CD-ROM, or V("none,media=cdrom") for an empty CD-ROM.'
231 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_options:#:~:text=ide,-[n]%3A).
232 type: dict
233 ipconfig:
234 description:
235 - 'Cloud-init: IP configuration for network interfaces.'
236 - Maps to C(net[n]) interfaces (e.g. C(ipconfig0) for C(net0)).
237 - Keys must be C(ipconfig[n]) where 0 ≤ n ≤ 31.
238 - Values are comma-separated options in the format V(ip=<addr>[,gw=<gateway>][,ip6=<addr>][,gw6=<gateway>]).
239 - 'Options:'
240 - ' - V(ip): IPv4 address in CIDR notation (e.g. V(192.168.1.10/24)) or V(dhcp) for DHCP.'
241 - ' - V(gw): IPv4 gateway (requires V(ip)); omit when using V(ip=dhcp).'
242 - ' - V(ip6): IPv6 address in CIDR notation, V(dhcp), or V(auto) for SLAAC.'
243 - ' - V(gw6): IPv6 gateway (requires V(ip6)); omit when using V(ip6=dhcp) or V(ip6=auto).'
244 - 'Examples: V(ip=dhcp) for DHCP; V(ip=192.168.1.10/24,gw=192.168.1.1) for static IPv4.'
245 - If cloud-init is enabled and no address is specified, IPv4 defaults to DHCP.
246 type: dict
247 keyboard:
248 description:
249 - Sets the keyboard layout for VNC server.
250 type: str
251 kvm:
252 description:
253 - Enable/disable KVM hardware virtualization.
254 type: bool
255 localtime:
256 description:
257 - Sets the real time clock to local time.
258 - This is enabled by default if ostype indicates a Microsoft OS.
259 type: bool
260 lock:
261 description:
262 - Lock/unlock the VM.
263 type: str
264 choices: ['migrate', 'backup', 'snapshot', 'rollback']
265 machine:
266 description:
267 - Specifies the Qemu machine type.
268 - Type => V((pc|pc(-i440fx\)?-\\d+\\.\\d+(\\.pxe\)?|q35|pc-q35-\\d+\\.\\d+(\\.pxe\)?\)).
269 - Allows to set, [[type=]<machine type>] [,enable-s3=<1|0>] [,enable-s4=<1|0>] [,viommu=<intel|virtio>].
270 type: str
271 memory:
272 description:
273 - Memory size in MB for instance.
274 type: int
275 migrate:
276 description:
277 - Migrate the VM to O(node) if it is on another node.
278 type: bool
279 default: false
280 migrate_downtime:
281 description:
282 - Sets maximum tolerated downtime (in seconds) for migrations.
283 type: int
284 migrate_speed:
285 description:
286 - Sets maximum speed (in MB/s) for migrations.
287 - A value of 0 is no limit.
288 type: int
289 name:
290 description:
291 - Specifies the VM name. Name could be non-unique across the cluster.
292 - Required only for O(state=present).
293 - With O(state=present) if O(vmid) not provided and VM with name exists in the cluster then no changes will be made.
294 type: str
295 nameservers:
296 description:
297 - 'Cloud-init: DNS server IP address(es).'
298 - If unset, PVE host settings are used.
299 type: list
300 elements: str
301 net:
302 description:
303 - A hash/dictionary of network interfaces for the VM.
304 - Keys must be C(net[n]) where 0 ≤ n ≤ N.
305 - Values are strings containing comma-separated options in the format V([model=]<enum>[,option=value]...)
306 - 'Examples: V("virtio,bridge=vmbr0") for a basic interface, or V("virtio,bridge=vmbr0,firewall=1,rate=200,tag=10")
307 for a rate-limited VLAN interface with firewall enabled.'
308 - V(macaddr=XX:XX:XX:XX:XX:XX) must be a unique MAC address.
309 If not specified, a unique MAC address is automatically generated.
310 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_options:#:~:text=net,-[n]%3A).
311 type: dict
312 newid:
313 description:
314 - VMID for the clone. Used only with clone.
315 - If newid is not set, the next available VM ID will be fetched from ProxmoxAPI.
316 type: int
317 numa:
318 description:
319 - A hash/dictionaries of NUMA topology. O(numa='{"key":"value", "key":"value"}').
320 - Keys allowed are - V(numa[n]) where 0 ≤ n ≤ N.
321 - Values allowed are - V("cpu="<id[-id];...>",hostnodes="<id[-id];...>",memory="number",policy="(bind|interleave|preferred)"").
322 - V(cpus) CPUs accessing this NUMA node.
323 - V(hostnodes) Host NUMA nodes to use.
324 - V(memory) Amount of memory this NUMA node provides.
325 - V(policy) NUMA allocation policy.
326 type: dict
327 numa_enabled:
328 description:
329 - Enables NUMA.
330 type: bool
331 onboot:
332 description:
333 - Specifies whether a VM will be started during system bootup.
334 type: bool
335 ostype:
336 description:
337 - Specifies guest operating system. This is used to enable special optimization/features for specific operating systems.
338 - The l26 is Linux 2.6/3.X Kernel.
339 type: str
340 choices: ['other', 'wxp', 'w2k', 'w2k3', 'w2k8', 'wvista', 'win7', 'win8', 'win10', 'win11', 'l24', 'l26', 'solaris']
341 parallel:
342 description:
343 - A hash/dictionary of map host parallel devices. O(parallel='{"key":"value", "key":"value"}').
344 - Keys allowed are - (parallel[n]) where 0 ≤ n ≤ 2.
345 - Values allowed are - C("/dev/parport\d+|/dev/usb/lp\d+").
346 type: dict
347 protection:
348 description:
349 - Enable/disable the protection flag of the VM. This will enable/disable the remove VM and remove disk operations.
350 type: bool
351 purge:
352 description:
353 - Remove VMID from configurations, like backup & replication jobs and HA.
354 - Used with state C(absent).
355 type: bool
356 default: false
357 reboot:
358 description:
359 - Allow reboot. If set to V(true), the VM exit on reboot.
360 type: bool
361 revert:
362 description:
363 - Revert a pending change.
364 type: str
365 rng0:
366 description: Randomness source for RNG device, for example V(/dev/urandom).
367 type: str
368 version_added: 1.0.0
369 sata:
370 description:
371 - A hash/dictionary of volume used as SATA hard disk or CD-ROM.
372 - Keys must be C(sata[n]) where 0 ≤ n ≤ 5.
373 - Values are strings containing comma-separated options in formats accepted by Proxmox VE.
374 - 'Examples: V("<storage>:10,format=qcow2") for a disk, V("<storage>:cloudinit,format=qcow2") for cloud-init,
375 V("<storage>:iso/debian.iso,media=cdrom") for an ISO-backed CD-ROM, or V("none,media=cdrom") for an empty CD-ROM.'
376 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_options:#:~:text=sata,-[n]%3A).
377 type: dict
378 scsi:
379 description:
380 - A hash/dictionary of volume used as SCSI hard disk or CD-ROM.
381 - Keys must be C(scsi[n]) where 0 ≤ n ≤ 30.
382 - Values are strings containing comma-separated options in formats accepted by Proxmox VE.
383 - 'Examples: V("<storage>:10,format=qcow2") for a disk, V("<storage>:cloudinit,format=qcow2") for cloud-init,
384 V("<storage>:iso/debian.iso,media=cdrom") for an ISO-backed CD-ROM, or V("none,media=cdrom") for an empty CD-ROM.'
385 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_options:#:~:text=scsi,-[n]%3A).
386 type: dict
387 scsihw:
388 description:
389 - Specifies the SCSI controller model.
390 type: str
391 choices: ['lsi', 'lsi53c810', 'virtio-scsi-pci', 'virtio-scsi-single', 'megasas', 'pvscsi']
392 searchdomains:
393 description:
394 - 'Cloud-init: Sets DNS search domain(s).'
395 - If unset, PVE host settings are used.
396 type: list
397 elements: str
398 serial:
399 description:
400 - A hash/dictionary of serial device to create inside the VM. V('{"key":"value", "key":"value"}').
401 - Keys allowed are - serial[n](str; required) where 0 ≤ n ≤ 3.
402 - Values allowed are - V((/dev/.+|socket\)).
403 - /!\ If you pass through a host serial device, it is no longer possible to migrate such machines - use with special
404 care.
405 type: dict
406 shares:
407 description:
408 - Rets amount of memory shares for auto-ballooning. (0 - 50000).
409 - The larger the number is, the more memory this VM gets.
410 - The number is relative to weights of all other running VMs.
411 - Using 0 disables auto-ballooning, this means no limit.
412 type: int
413 skiplock:
414 description:
415 - Ignore locks.
416 - Only root is allowed to use this option.
417 type: bool
418 smbios:
419 description:
420 - Specifies SMBIOS type 1 fields.
421 - Comma separated, Base64 encoded (optional) SMBIOS properties:.
422 - V([base64=<1|0>] [,family=<Base64 encoded string>]).
423 - V([,manufacturer=<Base64 encoded string>]).
424 - V([,product=<Base64 encoded string>]).
425 - V([,serial=<Base64 encoded string>]).
426 - V([,sku=<Base64 encoded string>]).
427 - V([,uuid=<UUID>]).
428 - V([,version=<Base64 encoded string>]).
429 type: str
430 snapname:
431 description:
432 - The name of the snapshot. Used only with clone.
433 type: str
434 sockets:
435 description:
436 - Sets the number of CPU sockets. (1 - N).
437 type: int
438 spice_enhancements:
439 description:
440 - Configure additional SPICE enhancements.
441 - Value is a comma-separated list of options in the format V(foldersharing=<0|1>[,videostreaming=<off|all|filter>]).
442 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_spice_enhancements).
443 type: str
444 sshkeys:
445 description:
446 - 'Cloud-init: SSH public key(s) to assign to the default user.'
447 - Supports multiple SSH keys by providing a multi-line value.
448 - Each key should be on a separate line in the format C(ssh-key-type key-data [comment]).
449 - Use YAML literal block scalar (C(|)) to provide multiple keys, one per line.
450 type: str
451 startdate:
452 description:
453 - Sets the initial date of the real time clock.
454 - Valid format for date are V('now') or V('2016-09-25T16:01:21') or V('2016-09-25').
455 type: str
456 startup:
457 description:
458 - Startup and shutdown behavior. V([[order=]\\d+] [,up=\\d+] [,down=\\d+]).
459 - Order is a non-negative number defining the general startup order.
460 - Shutdown in done with reverse ordering.
461 type: str
462 state:
463 description:
464 - Indicates desired state of the instance.
465 - If V(current), the current state of the VM will be fetched. You can access it with C(results.status).
466 - V(stopped) ensures that the VM is powered off using a graceful shutdown.
467 type: str
468 choices: ['present', 'started', 'absent', 'stopped', 'restarted', 'current', 'template', 'paused', 'hibernated']
469 default: present
470 storage:
471 description:
472 - Target storage for full clone.
473 - If restoring from archive, target storage for all disks. If omitted, storage location embedded inside archive will be used.
474 type: str
475 tablet:
476 description:
477 - Enables/disables the USB tablet device.
478 type: bool
479 tags:
480 description:
481 - List of tags to apply to the VM instance.
482 - Tags must start with V([a-z0-9_]) followed by zero or more of the following characters V([a-z0-9_-+.]).
483 - Tags are only available in Proxmox 6+.
484 type: list
485 elements: str
486 target:
487 description:
488 - Target node. Only allowed if the original VM is on shared storage.
489 - Used only with clone.
490 type: str
491 tdf:
492 description:
493 - Enables/disables time drift fix.
494 type: bool
495 template:
496 description:
497 - Enables/disables the template.
498 type: bool
499 timeout:
500 description:
501 - Timeout in seconds for operations.
502 - If the timeout is reached with O(state=stopped) and O(force=True), the VM will be forcefully powered off.
503 - If the timeout is reached with O(state=stopped) and O(force=False), the task will fail.
504 type: int
505 default: 30
506 tpmstate0:
507 description:
508 - A hash/dictionary of options for the Trusted Platform Module disk.
509 - A TPM state disk is required for Windows 11 installations.
510 suboptions:
511 storage:
512 description:
513 - O(tpmstate0.storage) is the storage identifier where to create the disk.
514 type: str
515 required: true
516 version:
517 description:
518 - The TPM version to use.
519 type: str
520 choices: ['1.2', '2.0']
521 default: '2.0'
522 type: dict
523 usb:
524 description:
525 - A hash/dictionary of USB devices for the VM. O(usb='{"key":"value", "key":"value"}').
526 - Keys allowed are - C(usb[n]) where 0 ≤ n ≤ N.
527 - Values allowed are - C(host="value|spice",mapping="value",usb3="1|0").
528 - Host is either C(spice) or the USB id/port.
529 - Option C(mapping) is the mapped USB device name.
530 - Option C(usb3) enables USB 3 support.
531 type: dict
532 update:
533 description:
534 - If V(true), the VM will be updated with new value.
535 - Because of the operations of the API and security reasons, I have disabled the update of the following parameters
536 O(net), O(virtio), O(virtiofs), O(ide), O(sata), O(scsi). Per example updating O(net) update the MAC address and O(virtio) create
537 always new disk... This security feature can be disabled by setting the O(update_unsafe) to V(true).
538 - Update of O(pool) is disabled. It needs an additional API endpoint not covered by this module.
539 type: bool
540 default: false
541 update_unsafe:
542 description:
543 - If V(true), do not enforce limitations on parameters O(net), O(virtio), O(virtiofs), O(ide), O(sata), O(scsi),
544 O(efidisk0), and O(tpmstate0). Use this option with caution because an improper configuration might result in a permanent loss of data
545 (for example disk recreated).
546 type: bool
547 default: false
548 vcpus:
549 description:
550 - Sets number of hotplugged vcpus.
551 type: int
552 vga:
553 description:
554 - Select VGA type. If you want to use high resolution modes (>= 1280x1024x16) then you should use option V(std) or V(vmware).
555 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_options:#:~:text=vga%3A).
556 type: str
557 virtio:
558 description:
559 - A hash/dictionary of volume used as VIRTIO hard disk or CD-ROM.
560 - Keys must be C(virtio[n]) where 0 ≤ n ≤ 15.
561 - Values are strings containing comma-separated options in the format V(<storage>:<size>[,option=value]...)
562 - 'Examples: V("<storage>:10,format=qcow2") for a disk, or V("<storage>:iso/debian.iso,media=cdrom") for a CD-ROM.'
563 - Refer to the Proxmox VE documentation at U(https://pve.proxmox.com/pve-docs/chapter-qm.html#qm_options:#:~:text=virtio,-[n]%3A).
564 type: dict
565 virtiofs:
566 description:
567 - A hash/dictionary of Virtio-fs devices for sharing directories between host and guest.
568 - Keys must be C(virtiofs[n]) where 0 ≤ n ≤ 9.
569 - Values are strings containing comma-separated options. Requires a directory mapping to be created
570 first.
571 - 'Options:'
572 - ' - V(dirid): Identifier of the directory mapping.'
573 - ' - V(cache): Caching policy V(always), V(auto), V(metadata), or V(never).'
574 - ' - V(direct-io): Whether to allow direct I/O. V(0) or V(1).'
575 - ' - V(expose-acl): Whether to expose POSIX ACLs. V(0) or V(1). Implies xattr when enabled.'
576 - ' - V(expose-xattr): Enable support for extended attributes. V(0) or V(1).'
577 - 'Example: V("dirid=my-share,cache=always,direct-io=1,expose-acl=1,expose-xattr=1")'
578 - Available in Proxmox VE 8.4 and later.
579 - For more information, see U(https://pve.proxmox.com/pve-docs/qm.conf.5.html#:~:text=virtiofs,-[n]%3A).
580 type: dict
581
582 watchdog:
583 description:
584 - Creates a virtual hardware watchdog device.
585 type: str
586 with_local_disks:
587 description:
588 - Enables migration of local disks to the next node.
589 type: bool
590 default: false
591
592 seealso:
593 - module: community.proxmox.proxmox_disk
594 description: Manage VM disks and disk options.
595 - module: community.proxmox.proxmox_vm_info
596 - name: Proxmox VE QEMU/KVM Virtual Machines documentation
597 description: Proxmox VE QEMU/KVM Virtual Machines documentation.
598 link: "https://pve.proxmox.com/pve-docs/chapter-qm.html"
599
600 extends_documentation_fragment:
601 - community.proxmox.proxmox.actiongroup_proxmox
602 - community.proxmox.proxmox.documentation
603 - community.proxmox.proxmox.selection
604 - community.proxmox.attributes
605 """
606
607 EXAMPLES = r"""
608 - name: Create new VM with minimal options
609 community.proxmox.proxmox_kvm:
610 name: spynal
611 node: sabrewulf
612
613 - name: Create a VM from archive (backup)
614 community.proxmox.proxmox_kvm:
615 archive: backup-storage:backup/vm/140/2023-03-08T06:41:23Z
616 name: spynal
617
618 - name: Create new VM with minimal options and given vmid
619 community.proxmox.proxmox_kvm:
620 name: spynal
621 node: sabrewulf
622 vmid: 100
623
624 - name: Create new VM with two network interface options
625 community.proxmox.proxmox_kvm:
626 name: spynal
627 node: sabrewulf
628 net:
629 net0: 'virtio,bridge=vmbr1,rate=200'
630 net1: 'e1000,bridge=vmbr2'
631
632 - name: Create new VM with one network interface, three virto hard disk, 4 cores, and 2 vcpus
633 community.proxmox.proxmox_kvm:
634 name: spynal
635 node: sabrewulf
636 net:
637 net0: 'virtio,bridge=vmbr1,rate=200'
638 virtio:
639 virtio0: 'VMs_LVM:10'
640 virtio1: 'VMs:2,format=qcow2'
641 virtio2: 'VMs:5,format=raw'
642 cores: 4
643 vcpus: 2
644
645 - name: Create VM with 1 10GiB SATA disk and an EFI disk, with Secure Boot disabled by default
646 community.proxmox.proxmox_kvm:
647 name: spynal
648 node: sabrewulf
649 sata:
650 sata0: 'VMs_LVM:10,format=raw'
651 bios: ovmf
652 efidisk0:
653 storage: VMs_LVM_thin
654 format: raw
655 efitype: 4m
656 pre_enrolled_keys: false
657
658 - name: Create VM with 1 10GiB SATA disk and an EFI disk, with Secure Boot enabled by default
659 community.proxmox.proxmox_kvm:
660 name: spynal
661 node: sabrewulf
662 sata:
663 sata0: 'VMs_LVM:10,format=raw'
664 bios: ovmf
665 efidisk0:
666 storage: VMs_LVM
667 format: raw
668 efitype: 4m
669 pre_enrolled_keys: 1
670
671 - name: >
672 Clone VM with only source VM name.
673 The VM source is spynal.
674 The target VM name is zavala
675 community.proxmox.proxmox_kvm:
676 clone: spynal
677 name: zavala
678 node: sabrewulf
679 storage: VMs
680 format: qcow2
681 timeout: 500
682
683 - name: >
684 Create linked clone VM with only source VM name.
685 The VM source is spynal.
686 The target VM name is zavala
687 community.proxmox.proxmox_kvm:
688 clone: spynal
689 name: zavala
690 node: sabrewulf
691 storage: VMs
692 full: false
693 format: unspecified
694 timeout: 500
695
696 - name: Clone VM with source vmid and target newid and raw format
697 community.proxmox.proxmox_kvm:
698 clone: arbitrary_name
699 vmid: 108
700 newid: 152
701 name: zavala
702 node: sabrewulf
703 storage: LVM_STO
704 format: raw
705 timeout: 300
706
707 - name: Create new VM and lock it for snapshot
708 community.proxmox.proxmox_kvm:
709 name: spynal
710 node: sabrewulf
711 lock: snapshot
712
713 - name: Create new VM and set protection to disable the remove VM and remove disk operations
714 community.proxmox.proxmox_kvm:
715 name: spynal
716 node: sabrewulf
717 protection: true
718
719 - name: Create new VM using cloud-init with a username and password
720 community.proxmox.proxmox_kvm:
721 node: sabrewulf
722 name: spynal
723 ide:
724 ide2: 'local:cloudinit,format=qcow2'
725 ciuser: mylinuxuser
726 cipassword: supersecret
727 searchdomains: 'mydomain.internal'
728 nameservers: 1.1.1.1
729 net:
730 net0: 'virtio,bridge=vmbr1,tag=77'
731 ipconfig:
732 ipconfig0: 'ip=192.168.1.1/24,gw=192.168.1.1'
733
734 - name: Create new VM using Cloud-Init with an ssh key
735 community.proxmox.proxmox_kvm:
736 node: sabrewulf
737 name: spynal
738 ide:
739 ide2: 'local:cloudinit,format=qcow2'
740 sshkeys: |
741 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPUF/cMCRObddaMmvUDio//yge6gRGXNv3uqMq7ve0x3 [email protected]
742 ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIP+v9HERWdWKh1lxceobl98LBX3+alfVK0zJnAxLbMRq [email protected]
743 searchdomains: 'mydomain.internal'
744 nameservers:
745 - '1.1.1.1'
746 - '8.8.8.8'
747 net:
748 net0: 'virtio,bridge=vmbr1,tag=77'
749 ipconfig:
750 ipconfig0: 'ip=192.168.1.1/24'
751
752 - name: Start VM
753 community.proxmox.proxmox_kvm:
754 name: spynal
755 node: sabrewulf
756 state: started
757
758 - name: Stop VM
759 community.proxmox.proxmox_kvm:
760 name: spynal
761 node: sabrewulf
762 state: stopped
763
764 - name: Stop VM with force
765 community.proxmox.proxmox_kvm:
766 name: spynal
767 node: sabrewulf
768 state: stopped
769 force: true
770
771 - name: Restart VM
772 community.proxmox.proxmox_kvm:
773 name: spynal
774 node: sabrewulf
775 state: restarted
776
777 - name: Convert VM to template
778 community.proxmox.proxmox_kvm:
779 name: spynal
780 node: sabrewulf
781 state: template
782
783 - name: Convert VM to template (stop VM if running)
784 community.proxmox.proxmox_kvm:
785 name: spynal
786 node: sabrewulf
787 state: template
788 force: true
789
790 - name: Remove VM
791 community.proxmox.proxmox_kvm:
792 name: spynal
793 node: sabrewulf
794 state: absent
795
796 - name: >-
797 Remove VM, deleting all volumes that use the VM's ID, regardless
798 of whether they are mentioned in the config or not
799 community.proxmox.proxmox_kvm:
800 name: spynal
801 node: sabrewulf
802 state: absent
803 destroy_unreferenced_disks: true
804
805 - name: Get VM current state
806 community.proxmox.proxmox_kvm:
807 name: spynal
808 node: sabrewulf
809 state: current
810
811 - name: Update VM configuration
812 community.proxmox.proxmox_kvm:
813 name: spynal
814 node: sabrewulf
815 cores: 8
816 memory: 16384
817 update: true
818
819 - name: Update VM configuration (incl. unsafe options)
820 community.proxmox.proxmox_kvm:
821 name: spynal
822 node: sabrewulf
823 cores: 8
824 memory: 16384
825 net:
826 net0: virtio,bridge=vmbr1
827 update: true
828 update_unsafe: true
829
830 - name: Delete QEMU parameters
831 community.proxmox.proxmox_kvm:
832 name: spynal
833 node: sabrewulf
834 delete: 'args,template,cpulimit'
835
836 - name: Revert a pending change
837 community.proxmox.proxmox_kvm:
838 name: spynal
839 node: sabrewulf
840 revert: 'template,cpulimit'
841
842 - name: Migrate VM on second node
843 community.proxmox.proxmox_kvm:
844 name: spynal
845 node: sabrewulf-2
846 migrate: true
847
848 - name: Add hookscript to existing VM
849 community.proxmox.proxmox_kvm:
850 vmid: 999
851 node: sabrewulf
852 hookscript: local:snippets/hookscript.pl
853 update: true
854 """
855
856 RETURN = r"""
857 vmid:
858 description: The VM vmid.
859 returned: success
860 type: int
861 sample: 115
862 status:
863 description: The current virtual machine status.
864 returned: success, not clone, not absent, not update
865 type: str
866 sample: running
867 msg:
868 description: A short message.
869 returned: always
870 type: str
871 sample: "VM kropta with vmid = 110 is running"
872 """
873
874 import re
875 import time
876 from urllib.parse import quote
877
878 from ansible.module_utils.parsing.convert_bool import boolean
879
880 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
881 ProxmoxAnsible,
882 ansible_to_proxmox_bool,
883 create_proxmox_module,
884 )
885 from ansible_collections.community.proxmox.plugins.module_utils.version import LooseVersion
886
887
888 def parse_mac(netstr):
889 return re.search("=(.*?),", netstr).group(1)
890
891
892 def parse_dev(devstr):
893 return re.search("(.*?)(,|$)", devstr).group(1)
894
895
896 def module_args():
897 return dict(
898 archive=dict(type="str"),
899 acpi=dict(type="bool"),
900 agent=dict(type="str"),
901 args=dict(type="str"),
902 audio=dict(type="dict"),
903 autostart=dict(type="bool"),
904 balloon=dict(type="int"),
905 bios=dict(choices=["seabios", "ovmf"]),
906 boot=dict(type="str"),
907 bootdisk=dict(type="str"),
908 cicustom=dict(type="str"),
909 cipassword=dict(type="str", no_log=True),
910 citype=dict(type="str", choices=["nocloud", "configdrive2"]),
911 ciupgrade=dict(type="bool"),
912 ciuser=dict(type="str"),
913 clone=dict(type="str"),
914 cores=dict(type="int"),
915 cpu=dict(type="str"),
916 cpulimit=dict(type="int"),
917 cpuunits=dict(type="int"),
918 delete=dict(type="str"),
919 description=dict(type="str"),
920 destroy_unreferenced_disks=dict(type="bool", default=False),
921 digest=dict(type="str"),
922 efidisk0=dict(
923 type="dict",
924 options=dict(
925 storage=dict(type="str"),
926 format=dict(type="str"),
927 efitype=dict(type="str", choices=["2m", "4m"]),
928 pre_enrolled_keys=dict(type="bool"),
929 ),
930 ),
931 force=dict(type="bool"),
932 format=dict(type="str", choices=["cloop", "cow", "qcow", "qcow2", "qed", "raw", "vmdk", "unspecified"]),
933 freeze=dict(type="bool"),
934 full=dict(type="bool", default=True),
935 hookscript=dict(type="str"),
936 hostpci=dict(type="dict"),
937 hotplug=dict(type="str"),
938 hugepages=dict(choices=["any", "2", "1024"]),
939 ide=dict(type="dict"),
940 ipconfig=dict(type="dict"),
941 keyboard=dict(type="str"),
942 kvm=dict(type="bool"),
943 localtime=dict(type="bool"),
944 lock=dict(choices=["migrate", "backup", "snapshot", "rollback"]),
945 machine=dict(type="str"),
946 memory=dict(type="int"),
947 migrate=dict(type="bool", default=False),
948 migrate_downtime=dict(type="int"),
949 migrate_speed=dict(type="int"),
950 name=dict(type="str"),
951 nameservers=dict(type="list", elements="str"),
952 net=dict(type="dict"),
953 newid=dict(type="int"),
954 node=dict(),
955 numa=dict(type="dict"),
956 numa_enabled=dict(type="bool"),
957 onboot=dict(type="bool"),
958 ostype=dict(
959 choices=[
960 "other",
961 "wxp",
962 "w2k",
963 "w2k3",
964 "w2k8",
965 "wvista",
966 "win7",
967 "win8",
968 "win10",
969 "win11",
970 "l24",
971 "l26",
972 "solaris",
973 ]
974 ),
975 parallel=dict(type="dict"),
976 pool=dict(type="str"),
977 protection=dict(type="bool"),
978 purge=dict(type="bool", default=False),
979 reboot=dict(type="bool"),
980 revert=dict(type="str"),
981 rng0=dict(type="str"),
982 sata=dict(type="dict"),
983 scsi=dict(type="dict"),
984 scsihw=dict(choices=["lsi", "lsi53c810", "virtio-scsi-pci", "virtio-scsi-single", "megasas", "pvscsi"]),
985 serial=dict(type="dict"),
986 searchdomains=dict(type="list", elements="str"),
987 shares=dict(type="int"),
988 skiplock=dict(type="bool"),
989 smbios=dict(type="str"),
990 snapname=dict(type="str"),
991 sockets=dict(type="int"),
992 sshkeys=dict(type="str", no_log=False),
993 spice_enhancements=dict(type="str"),
994 startdate=dict(type="str"),
995 startup=dict(),
996 state=dict(
997 default="present",
998 choices=[
999 "present",
1000 "absent",
1001 "stopped",
1002 "started",
1003 "restarted",
1004 "current",
1005 "template",
1006 "paused",
1007 "hibernated",
1008 ],
1009 ),
1010 storage=dict(type="str"),
1011 tablet=dict(type="bool"),
1012 tags=dict(type="list", elements="str"),
1013 target=dict(type="str"),
1014 tdf=dict(type="bool"),
1015 template=dict(type="bool"),
1016 timeout=dict(type="int", default=30),
1017 tpmstate0=dict(
1018 type="dict",
1019 options=dict(
1020 storage=dict(type="str", required=True), version=dict(type="str", choices=["2.0", "1.2"], default="2.0")
1021 ),
1022 ),
1023 usb=dict(type="dict"),
1024 update=dict(type="bool", default=False),
1025 update_unsafe=dict(type="bool", default=False),
1026 vcpus=dict(type="int"),
1027 vga=dict(type="str"),
1028 virtio=dict(type="dict"),
1029 virtiofs=dict(type="dict"),
1030 vmid=dict(type="int"),
1031 watchdog=dict(),
1032 with_local_disks=dict(type="bool", default=False),
1033 )
1034
1035
1036 def module_options():
1037 return dict(
1038 supports_check_mode=False,
1039 mutually_exclusive=[
1040 ("delete", "revert"),
1041 ("delete", "update"),
1042 ("revert", "update"),
1043 ("clone", "update"),
1044 ("clone", "delete"),
1045 ("clone", "revert"),
1046 ],
1047 required_one_of=[("name", "vmid")],
1048 required_if=[("state", "present", ["node"])],
1049 )
1050
1051
1052 class ProxmoxKvmAnsible(ProxmoxAnsible):
1053 def get_vminfo(self, node, vmid, **kwargs):
1054 mac = {}
1055 devices = {}
1056 try:
1057 vm = self.proxmox_api.nodes(node).qemu(vmid).config.get()
1058 except Exception as e:
1059 self.module.fail_json(msg=f"Getting information for VM with vmid = {vmid} failed with exception: {e}")
1060
1061 # Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
1062 kwargs = {k: v for k, v in kwargs.items() if v is not None}
1063
1064 # Convert all dict in kwargs to elements.
1065 # For hostpci[n], ide[n], net[n], numa[n], parallel[n], sata[n], scsi[n], serial[n], virtio[n], virtiofs[n]
1066 for k in list(kwargs.keys()):
1067 if isinstance(kwargs[k], dict):
1068 kwargs.update(kwargs[k])
1069 del kwargs[k]
1070
1071 # Split information by type
1072 re_net = re.compile(r"net[0-9]")
1073 re_dev = re.compile(r"(virtio|ide|scsi|sata|efidisk)[0-9]")
1074 for k in kwargs:
1075 if re_net.match(k):
1076 mac[k] = parse_mac(vm[k])
1077 elif re_dev.match(k):
1078 devices[k] = parse_dev(vm[k])
1079
1080 return {"mac": mac, "devices": devices, "vmid": int(vmid)}
1081
1082 def settings(self, vmid, node, **kwargs):
1083 proxmox_node = self.proxmox_api.nodes(node)
1084
1085 # Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
1086 kwargs = {k: v for k, v in kwargs.items() if v is not None}
1087
1088 return proxmox_node.qemu(vmid).config.set(**kwargs) is None
1089
1090 def wait_for_task(self, node, taskid):
1091 timeout = self.module.params["timeout"]
1092 if self.module.params["state"] == "stopped":
1093 # Increase task timeout in case of stopped state to be sure it waits longer than VM stop operation itself
1094 timeout += 10
1095
1096 while timeout:
1097 if self.api_task_ok(node, taskid):
1098 # Wait an extra second as the API can be a ahead of the hypervisor
1099 time.sleep(1)
1100 return True
1101 timeout = timeout - 1
1102 if timeout == 0:
1103 break
1104 time.sleep(1)
1105 return False
1106
1107 def create_vm(self, vmid, newid, node, name, memory, cpu, cores, sockets, update, update_unsafe, **kwargs): # noqa: PLR0912, PLR0913, PLR0915
1108 # Available only in PVE 4
1109 only_v4 = ["force", "protection", "skiplock"]
1110 only_v6 = ["ciuser", "cipassword", "sshkeys", "ipconfig", "tags"]
1111 only_v8 = ["ciupgrade"]
1112
1113 # valid clone parameters
1114 valid_clone_params = ["format", "full", "pool", "snapname", "storage", "target"]
1115 clone_params = {}
1116
1117 proxmox_node = self.proxmox_api.nodes(node)
1118
1119 # Sanitize kwargs. Remove not defined args and ensure True and False converted to int.
1120 kwargs = {k: v for k, v in kwargs.items() if v is not None}
1121 kwargs.update({k: int(v) for k, v in kwargs.items() if isinstance(v, bool)})
1122
1123 version = self.version()
1124 pve_major_version = 3 if version < LooseVersion("4.0") else version.version[0]
1125
1126 # The features work only on PVE 4+
1127 if pve_major_version < 4: # noqa: PLR2004
1128 for p in only_v4:
1129 if p in kwargs:
1130 del kwargs[p]
1131
1132 # The features work only on PVE 6
1133 if pve_major_version < 6: # noqa: PLR2004
1134 for p in only_v6:
1135 if p in kwargs:
1136 del kwargs[p]
1137
1138 # The features work only on PVE 8
1139 if pve_major_version < 8: # noqa: PLR2004
1140 for p in only_v8:
1141 if p in kwargs:
1142 del kwargs[p]
1143
1144 # 'sshkeys' param expects an urlencoded string
1145 if "sshkeys" in kwargs:
1146 urlencoded_ssh_keys = quote(kwargs["sshkeys"], safe="")
1147 kwargs["sshkeys"] = str(urlencoded_ssh_keys)
1148
1149 # If update, don't update disk (virtio, efidisk0, tpmstate0, ide, sata, scsi), virtiofs, and network interface, unless update_unsafe=True
1150 # pool parameter not supported by qemu/<vmid>/config endpoint on "update" (PVE 6.2) - only with "create"
1151 if update:
1152 if update_unsafe is False:
1153 if "virtio" in kwargs:
1154 del kwargs["virtio"]
1155 if "sata" in kwargs:
1156 del kwargs["sata"]
1157 if "scsi" in kwargs:
1158 del kwargs["scsi"]
1159 if "ide" in kwargs:
1160 del kwargs["ide"]
1161 if "efidisk0" in kwargs:
1162 del kwargs["efidisk0"]
1163 if "tpmstate0" in kwargs:
1164 del kwargs["tpmstate0"]
1165 if "net" in kwargs:
1166 del kwargs["net"]
1167 if "virtiofs" in kwargs:
1168 del kwargs["virtiofs"]
1169 if "force" in kwargs:
1170 del kwargs["force"]
1171 if "pool" in kwargs:
1172 del kwargs["pool"]
1173
1174 # Check that the bios option is set to ovmf if the efidisk0 option is present
1175 if "efidisk0" in kwargs and kwargs.get("bios") != "ovmf":
1176 self.module.fail_json(msg="efidisk0 cannot be used if bios is not set to ovmf. ")
1177
1178 # Flatten efidisk0 option to a string so that it is a string which is what Proxmoxer and the API expect
1179 if "efidisk0" in kwargs:
1180 efidisk0_str = ""
1181 # Regexp to catch underscores in keys name, to replace them after by hyphens
1182 hyphen_re = re.compile(r"_")
1183 # If present, the storage definition should be the first argument
1184 if "storage" in kwargs["efidisk0"]:
1185 efidisk0_str += kwargs["efidisk0"].get("storage") + ":1,"
1186 kwargs["efidisk0"].pop("storage")
1187 # Join other elements from the dict as key=value using commas as separator, replacing any underscore in key
1188 # by hyphens (needed for pre_enrolled_keys to pre-enrolled-keys)
1189 efidisk0_str += ",".join(
1190 [hyphen_re.sub("-", k) + "=" + str(v) for k, v in kwargs["efidisk0"].items() if k != "storage"]
1191 )
1192 kwargs["efidisk0"] = efidisk0_str
1193
1194 # Flatten tpmstate0 option to a string so that it is a string which is what Proxmoxer and the API expect
1195 if "tpmstate0" in kwargs:
1196 tpm = kwargs["tpmstate0"]
1197 kwargs["tpmstate0"] = f"{tpm.get('storage')}:1,version=v{tpm.get('version')}"
1198
1199 # Convert all dict in kwargs to elements.
1200 # For audio[n], hostpci[n], ide[n], net[n], numa[n], parallel[n], sata[n], scsi[n], serial[n], virtio[n], virtiofs[n], ipconfig[n], usb[n]
1201 for k in list(kwargs.keys()):
1202 if isinstance(kwargs[k], dict):
1203 kwargs.update(kwargs[k])
1204 del kwargs[k]
1205
1206 if "agent" in kwargs:
1207 try:
1208 # The API also allows booleans instead of e.g. `enabled=1` for backward-compatibility.
1209 kwargs["agent"] = int(boolean(kwargs["agent"], strict=True))
1210 except TypeError:
1211 # Not something that Ansible would parse as a boolean.
1212 pass
1213
1214 # Rename numa_enabled to numa, according the API documentation
1215 if "numa_enabled" in kwargs:
1216 kwargs["numa"] = kwargs["numa_enabled"]
1217 del kwargs["numa_enabled"]
1218
1219 # PVE api expects strings for the following params
1220 if "nameservers" in self.module.params:
1221 nameservers = self.module.params.pop("nameservers")
1222 if nameservers:
1223 kwargs["nameserver"] = " ".join(nameservers)
1224 if "searchdomains" in self.module.params:
1225 searchdomains = self.module.params.pop("searchdomains")
1226 if searchdomains:
1227 kwargs["searchdomain"] = " ".join(searchdomains)
1228
1229 # VM tags are expected to be valid and presented as a comma/semi-colon delimited string
1230 if "tags" in kwargs:
1231 re_tag = re.compile(r"^[a-zA-Z0-9_][a-zA-Z0-9_\-\+\.]*$")
1232 for tag in kwargs["tags"]:
1233 if not re_tag.match(tag):
1234 self.module.fail_json(msg=f"{tag} is not a valid tag")
1235 kwargs["tags"] = ",".join(kwargs["tags"])
1236
1237 # -args and skiplock require root@pam user - but can not use api tokens
1238 if self.module.params["api_user"] == "root@pam" and self.module.params["args"] is not None:
1239 kwargs["args"] = self.module.params["args"]
1240 elif self.module.params["api_user"] != "root@pam" and self.module.params["args"] is not None:
1241 self.module.fail_json(msg="args parameter require root@pam user. ")
1242
1243 if self.module.params["api_user"] != "root@pam" and self.module.params["skiplock"] is not None:
1244 self.module.fail_json(msg="skiplock parameter require root@pam user. ")
1245
1246 if update:
1247 result = proxmox_node.qemu(vmid).config.set(
1248 name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs
1249 )
1250 return result is None
1251 elif self.module.params["clone"] is not None:
1252 for param in valid_clone_params:
1253 if self.module.params[param] is not None:
1254 clone_params[param] = self.module.params[param]
1255 clone_params.update({k: int(v) for k, v in clone_params.items() if isinstance(v, bool)})
1256 taskid = proxmox_node.qemu(vmid).clone.post(newid=newid, name=name, **clone_params)
1257 else:
1258 taskid = proxmox_node.qemu.create(
1259 vmid=vmid, name=name, memory=memory, cpu=cpu, cores=cores, sockets=sockets, **kwargs
1260 )
1261
1262 if not self.wait_for_task(node, taskid):
1263 self.module.fail_json(
1264 msg=f"Reached timeout while waiting for creating VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1265 )
1266 return False
1267 return True
1268
1269 def start_vm(self, vm):
1270 vmid = vm["vmid"]
1271 proxmox_node = self.proxmox_api.nodes(vm["node"])
1272 taskid = proxmox_node.qemu(vmid).status.start.post()
1273 if not self.wait_for_task(vm["node"], taskid):
1274 self.module.fail_json(
1275 msg=f"Reached timeout while waiting for starting VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1276 )
1277 return False
1278 return True
1279
1280 def stop_vm(self, vm, force, timeout):
1281 vmid = vm["vmid"]
1282 proxmox_node = self.proxmox_api.nodes(vm["node"])
1283 taskid = proxmox_node.qemu(vmid).status.shutdown.post(forceStop=(1 if force else 0), timeout=timeout)
1284 if not self.wait_for_task(vm["node"], taskid):
1285 self.module.fail_json(
1286 msg=f"Reached timeout while waiting for stopping VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1287 )
1288 return False
1289 return True
1290
1291 def restart_vm(self, vm, force, **status):
1292 vmid = vm["vmid"]
1293 try:
1294 proxmox_node = self.proxmox_api.nodes(vm["node"])
1295 taskid = (
1296 proxmox_node.qemu(vmid).status.reset.post() if force else proxmox_node.qemu(vmid).status.reboot.post()
1297 )
1298 if not self.wait_for_task(vm["node"], taskid):
1299 self.module.fail_json(
1300 msg=f"Reached timeout while waiting for rebooting VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1301 )
1302 return False
1303 return True
1304 except Exception as e:
1305 self.module.fail_json(vmid=vmid, msg=f"restarting of VM {vmid} failed with exception: {e}")
1306 return False
1307
1308 def convert_to_template(self, vm, timeout, force):
1309 vmid = vm["vmid"]
1310 try:
1311 proxmox_node = self.proxmox_api.nodes(vm["node"])
1312 if proxmox_node.qemu(vmid).status.current.get()["status"] == "running" and force:
1313 self.stop_instance(vm, vmid, timeout, force)
1314 # not sure why, but templating a container doesn't return a taskid
1315 proxmox_node.qemu(vmid).template.post()
1316 return True
1317 except Exception as e:
1318 self.module.fail_json(vmid=vmid, msg=f"conversion of VM {vmid} to template failed with exception: {e}")
1319 return False
1320
1321 def migrate_vm(self, vm, target_node, with_local_disks):
1322 vmid = vm["vmid"]
1323 with_local_disks = ansible_to_proxmox_bool(with_local_disks)
1324 migration_args = {
1325 "with-local-disks": with_local_disks,
1326 "vmid": vmid,
1327 "node": vm["node"],
1328 "target": target_node,
1329 "online": 1,
1330 }
1331 proxmox_node = self.proxmox_api.nodes(vm["node"])
1332 taskid = proxmox_node.qemu(vmid).migrate.post(**migration_args)
1333 if not self.wait_for_task(vm["node"], taskid):
1334 self.module.fail_json(
1335 msg=f"Reached timeout while waiting for migrating VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1336 )
1337 return False
1338 return True
1339
1340 def suspend_vm(self, vm, timeout, todisk):
1341 vmid = vm["vmid"]
1342 proxmox_node = self.proxmox_api.nodes(vm["node"])
1343 taskid = proxmox_node.qemu(vmid).status.suspend.post(todisk=(1 if todisk else 0), timeout=timeout)
1344 if not self.wait_for_task(vm["node"], taskid):
1345 self.module.fail_json(
1346 msg=f"Reached timeout while waiting for suspending VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1347 )
1348 return False
1349 return True
1350
1351
1352 def main(): # noqa: PLR0912, PLR0915
1353 module = create_proxmox_module(module_args(), **module_options())
1354 proxmox = ProxmoxKvmAnsible(module)
1355
1356 clone = module.params["clone"]
1357 cpu = module.params["cpu"]
1358 cores = module.params["cores"]
1359 delete = module.params["delete"]
1360 migrate = module.params["migrate"]
1361 memory = module.params["memory"]
1362 name = module.params["name"]
1363 newid = module.params["newid"]
1364 node = module.params["node"]
1365 revert = module.params["revert"]
1366 sockets = module.params["sockets"]
1367 state = module.params["state"]
1368 update = bool(module.params["update"])
1369 update_unsafe = bool(module.params["update_unsafe"])
1370 vmid = module.params["vmid"]
1371
1372 if module.params["format"] == "unspecified":
1373 module.params["format"] = None
1374
1375 # If vmid is not defined then retrieve its value from the vm name,
1376 # the cloned vm name or retrieve the next free VM id from ProxmoxAPI.
1377 if not vmid:
1378 if state == "present" and not update and not clone and not delete and not revert and not migrate:
1379 existing_vmid = proxmox.get_vmid(name, ignore_missing=True)
1380 if existing_vmid:
1381 vmid = existing_vmid
1382 else:
1383 try:
1384 vmid = proxmox.get_nextvmid()
1385 except Exception:
1386 module.fail_json(
1387 msg=f"Can't get the next vmid for VM {name} automatically. Ensure your cluster state is good"
1388 )
1389 else:
1390 clone_target = clone or name
1391 vmid = proxmox.get_vmid(clone_target, ignore_missing=True)
1392
1393 if clone is not None:
1394 # If newid is not defined then retrieve the next free id from ProxmoxAPI
1395 if not newid:
1396 try:
1397 newid = proxmox.get_nextvmid()
1398 except Exception:
1399 module.fail_json(
1400 msg=f"Can't get the next vmid for VM {name} automatically. Ensure your cluster state is good"
1401 )
1402
1403 # Ensure source VM name exists when cloning
1404 if not vmid:
1405 module.fail_json(msg=f"VM with name = {clone} does not exist in cluster")
1406
1407 # Ensure source VM id exists when cloning
1408 proxmox.get_vm(vmid)
1409
1410 # Ensure the chosen VM id doesn't already exist when cloning
1411 if proxmox.get_vm(newid, ignore_missing=True):
1412 module.exit_json(changed=False, vmid=vmid, msg=f"vmid {newid} with VM name {name} already exists")
1413
1414 if delete is not None:
1415 try:
1416 proxmox.settings(vmid, node, delete=delete)
1417 module.exit_json(changed=True, vmid=vmid, msg=f"Settings has deleted on VM {name} with vmid {vmid}")
1418 except Exception as e:
1419 module.fail_json(vmid=vmid, msg=f"Unable to delete settings on VM {name} with vmid {vmid}: " + str(e))
1420
1421 if revert is not None:
1422 try:
1423 proxmox.settings(vmid, node, revert=revert)
1424 module.exit_json(changed=True, vmid=vmid, msg=f"Settings has reverted on VM {name} with vmid {vmid}")
1425 except Exception as e:
1426 module.fail_json(
1427 vmid=vmid,
1428 msg=f"Unable to revert settings on VM {name} with vmid {vmid}: Maybe is not a pending task... "
1429 + str(e),
1430 )
1431
1432 if migrate:
1433 try:
1434 vm = proxmox.get_vm(vmid)
1435 vm_node = vm["node"]
1436 if node != vm_node:
1437 proxmox.migrate_vm(vm, node, module.params["with_local_disks"])
1438 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} has been migrated from {vm_node} to {node}")
1439 else:
1440 module.exit_json(changed=False, vmid=vmid, msg=f"VM {vmid} is already on {node}")
1441 except Exception as e:
1442 module.fail_json(vmid=vmid, msg=f"Unable to migrate VM {vmid} from {vm_node} to {node}: {e}")
1443
1444 if state == "present":
1445 if not (update or clone) and proxmox.get_vm(vmid, ignore_missing=True):
1446 module.exit_json(changed=False, vmid=vmid, msg=f"VM with vmid <{vmid}> already exists")
1447 elif not (update or clone or vmid) and proxmox.get_vmid(name, ignore_missing=True):
1448 module.exit_json(changed=False, vmid=proxmox.get_vmid(name), msg=f"VM with name <{name}> already exists")
1449 elif not node:
1450 module.fail_json(msg="node is mandatory for creating/updating VM")
1451 elif update and not any([vmid, name]):
1452 module.fail_json(msg="vmid or name is mandatory for updating VM")
1453 elif not proxmox.get_node(node):
1454 module.fail_json(msg=f"node '{node}' does not exist in cluster")
1455
1456 vminfo = {}
1457 try:
1458 proxmox.create_vm(
1459 vmid,
1460 newid,
1461 node,
1462 name,
1463 memory,
1464 cpu,
1465 cores,
1466 sockets,
1467 update,
1468 update_unsafe,
1469 archive=module.params["archive"],
1470 acpi=module.params["acpi"],
1471 agent=module.params["agent"],
1472 audio=module.params["audio"],
1473 autostart=module.params["autostart"],
1474 balloon=module.params["balloon"],
1475 bios=module.params["bios"],
1476 boot=module.params["boot"],
1477 bootdisk=module.params["bootdisk"],
1478 cicustom=module.params["cicustom"],
1479 cipassword=module.params["cipassword"],
1480 citype=module.params["citype"],
1481 ciupgrade=module.params["ciupgrade"],
1482 ciuser=module.params["ciuser"],
1483 cpulimit=module.params["cpulimit"],
1484 cpuunits=module.params["cpuunits"],
1485 description=module.params["description"],
1486 digest=module.params["digest"],
1487 efidisk0=module.params["efidisk0"],
1488 force=module.params["force"],
1489 freeze=module.params["freeze"],
1490 hookscript=module.params["hookscript"],
1491 hostpci=module.params["hostpci"],
1492 hotplug=module.params["hotplug"],
1493 hugepages=module.params["hugepages"],
1494 ide=module.params["ide"],
1495 ipconfig=module.params["ipconfig"],
1496 keyboard=module.params["keyboard"],
1497 kvm=module.params["kvm"],
1498 localtime=module.params["localtime"],
1499 lock=module.params["lock"],
1500 machine=module.params["machine"],
1501 migrate_downtime=module.params["migrate_downtime"],
1502 migrate_speed=module.params["migrate_speed"],
1503 net=module.params["net"],
1504 numa=module.params["numa"],
1505 numa_enabled=module.params["numa_enabled"],
1506 onboot=module.params["onboot"],
1507 ostype=module.params["ostype"],
1508 parallel=module.params["parallel"],
1509 pool=module.params["pool"],
1510 protection=module.params["protection"],
1511 reboot=module.params["reboot"],
1512 rng0=module.params["rng0"],
1513 sata=module.params["sata"],
1514 scsi=module.params["scsi"],
1515 scsihw=module.params["scsihw"],
1516 serial=module.params["serial"],
1517 shares=module.params["shares"],
1518 spice_enhancements=module.params["spice_enhancements"],
1519 skiplock=module.params["skiplock"],
1520 smbios1=module.params["smbios"],
1521 snapname=module.params["snapname"],
1522 sshkeys=module.params["sshkeys"],
1523 startdate=module.params["startdate"],
1524 startup=module.params["startup"],
1525 storage=module.params["storage"],
1526 tablet=module.params["tablet"],
1527 tags=module.params["tags"],
1528 target=module.params["target"],
1529 tdf=module.params["tdf"],
1530 template=module.params["template"],
1531 tpmstate0=module.params["tpmstate0"],
1532 usb=module.params["usb"],
1533 vcpus=module.params["vcpus"],
1534 vga=module.params["vga"],
1535 virtio=module.params["virtio"],
1536 virtiofs=module.params["virtiofs"],
1537 watchdog=module.params["watchdog"],
1538 )
1539
1540 if not clone:
1541 vminfo = proxmox.get_vminfo(
1542 node,
1543 vmid,
1544 ide=module.params["ide"],
1545 net=module.params["net"],
1546 sata=module.params["sata"],
1547 scsi=module.params["scsi"],
1548 virtio=module.params["virtio"],
1549 )
1550 except Exception as e:
1551 if update:
1552 module.fail_json(vmid=vmid, msg=f"Unable to update vm {name} with vmid {vmid}: {e}")
1553 elif clone is not None:
1554 module.fail_json(vmid=vmid, msg=f"Unable to clone vm {name} from vmid {vmid}: {e}")
1555 else:
1556 module.fail_json(
1557 vmid=vmid, msg=f"creation of qemu VM {name} with vmid {vmid} failed with exception={e}"
1558 )
1559
1560 if update:
1561 module.exit_json(changed=True, vmid=vmid, msg=f"VM {name} with vmid {vmid} updated")
1562 elif clone is not None:
1563 module.exit_json(
1564 changed=True, vmid=newid, msg=f"VM {name} with newid {newid} cloned from vm with vmid {vmid}"
1565 )
1566 else:
1567 module.exit_json(changed=True, msg=f"VM {name} with vmid {vmid} deployed", **vminfo)
1568
1569 elif state == "started":
1570 if not vmid:
1571 module.fail_json(msg=f"VM with name = {name} does not exist in cluster")
1572
1573 status = {}
1574 try:
1575 vm = proxmox.get_vm(vmid)
1576 current = proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).status.current.get()["status"]
1577 status["status"] = current
1578 if current == "running":
1579 module.exit_json(changed=False, vmid=vmid, msg=f"VM {vmid} is already running", **status)
1580
1581 if proxmox.start_vm(vm):
1582 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} started", **status)
1583 except Exception as e:
1584 module.fail_json(vmid=vmid, msg=f"starting of VM {vmid} failed with exception: {e}", **status)
1585
1586 elif state == "stopped":
1587 if not vmid:
1588 module.fail_json(msg=f"VM with name = {name} does not exist in cluster")
1589
1590 status = {}
1591 try:
1592 vm = proxmox.get_vm(vmid)
1593 current = proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).status.current.get()["status"]
1594 status["status"] = current
1595 if current == "stopped":
1596 module.exit_json(changed=False, vmid=vmid, msg=f"VM {vmid} is already stopped", **status)
1597
1598 proxmox.stop_vm(vm, force=module.params["force"], timeout=module.params["timeout"])
1599 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} is shutting down", **status)
1600 except Exception as e:
1601 module.fail_json(vmid=vmid, msg=f"stopping of VM {vmid} failed with exception: {e}", **status)
1602
1603 elif state == "template":
1604 if not vmid:
1605 module.fail_json(msg=f"VM with name = {name} does not exist in cluster")
1606
1607 status = {}
1608 try:
1609 vm = proxmox.get_vm(vmid)
1610
1611 if vm["template"] == 1:
1612 module.exit_json(changed=False, vmid=vmid, msg=f"VM {vmid} is already a template", **status)
1613
1614 if proxmox.convert_to_template(vm, force=module.params["force"], timeout=module.params["timeout"]):
1615 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} is converting to template", **status)
1616 except Exception as e:
1617 module.fail_json(vmid=vmid, msg=f"conversion of VM {vmid} to template failed with exception: {e}", **status)
1618
1619 elif state == "restarted":
1620 if not vmid:
1621 module.fail_json(msg=f"VM with name = {name} does not exist in cluster")
1622
1623 status = {}
1624 vm = proxmox.get_vm(vmid)
1625 current = proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).status.current.get()["status"]
1626 status["status"] = current
1627 if current == "stopped":
1628 module.exit_json(changed=False, vmid=vmid, msg=f"VM {vmid} is not running", **status)
1629
1630 if proxmox.restart_vm(vm, force=module.params["force"]):
1631 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} is restarted", **status)
1632
1633 elif state == "absent":
1634 status = {}
1635 if not vmid:
1636 module.exit_json(changed=False, msg=f"VM with name = {name} is already absent")
1637
1638 try:
1639 vm = proxmox.get_vm(vmid, ignore_missing=True)
1640 if not vm:
1641 module.exit_json(changed=False, vmid=vmid)
1642
1643 proxmox_node = proxmox.proxmox_api.nodes(vm["node"])
1644 current = proxmox_node.qemu(vmid).status.current.get()["status"]
1645 status["status"] = current
1646 if current == "running":
1647 if module.params["force"]:
1648 proxmox.stop_vm(vm, True, timeout=module.params["timeout"])
1649 else:
1650 module.exit_json(
1651 changed=False,
1652 vmid=vmid,
1653 msg=f"VM {vmid} is running. Stop it before deletion or use force=true.",
1654 )
1655
1656 delete_params = {}
1657 if module.params["purge"]:
1658 delete_params["purge"] = 1
1659 if module.params["destroy_unreferenced_disks"]:
1660 delete_params["destroy-unreferenced-disks"] = 1
1661 taskid = proxmox_node.qemu.delete(vmid, **delete_params)
1662 if not proxmox.wait_for_task(vm["node"], taskid):
1663 module.fail_json(
1664 msg=f"Reached timeout while waiting for removing VM. Last line in task before timeout: {proxmox_node.tasks(taskid).log.get()[:1]}"
1665 )
1666 else:
1667 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} removed")
1668 except Exception as e:
1669 module.fail_json(msg=f"deletion of VM {vmid} failed with exception: {e}")
1670
1671 elif state == "current":
1672 status = {}
1673 if not vmid:
1674 module.fail_json(msg=f"VM with name = {name} does not exist in cluster")
1675 vm = proxmox.get_vm(vmid)
1676 if not name:
1677 name = vm.get("name", "(unnamed)")
1678 current = proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).status.current.get()["status"]
1679 status["status"] = current
1680 if status:
1681 module.exit_json(changed=False, vmid=vmid, msg=f"VM {name} with vmid = {vmid} is {current}", **status)
1682
1683 elif state in ["paused", "hibernated"]:
1684 if not vmid:
1685 module.fail_json(msg=f"VM with name = {name} does not exist in cluster")
1686
1687 status = {}
1688 try:
1689 vm = proxmox.get_vm(vmid)
1690 current = proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).status.current.get()["status"]
1691 status["status"] = current
1692 if current != "running":
1693 module.exit_json(changed=False, vmid=vmid, msg=f"VM {vmid} is not running", **status)
1694
1695 proxmox.suspend_vm(
1696 vm, force=module.params["force"], timeout=module.params["timeout"], todisk=(state == "hibernated")
1697 )
1698 module.exit_json(changed=True, vmid=vmid, msg=f"VM {vmid} is suspending", **status)
1699 except Exception as e:
1700 module.fail_json(vmid=vmid, msg=f"suspending of VM {vmid} failed with exception: {e}", **status)
1701
1702
1703 if __name__ == "__main__":
1704 main()