| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2022, Castor Sky (@castorsky) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see COPYING 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_disk |
| 10 |
short_description: Management of a disk of a Qemu(KVM) VM in a Proxmox VE cluster |
| 11 |
description: |
| 12 |
- Allows you to perform some supported operations on a disk in Qemu(KVM) Virtual Machines in a Proxmox VE cluster. |
| 13 |
author: "Castor Sky (@castorsky) <[email protected]>" |
| 14 |
attributes: |
| 15 |
check_mode: |
| 16 |
support: none |
| 17 |
diff_mode: |
| 18 |
support: none |
| 19 |
options: |
| 20 |
name: |
| 21 |
description: |
| 22 |
- The unique name of the VM. |
| 23 |
- You can specify either O(name) or O(vmid) or both of them. |
| 24 |
type: str |
| 25 |
vmid: |
| 26 |
description: |
| 27 |
- The unique ID of the VM. |
| 28 |
- You can specify either O(vmid) or O(name) or both of them. |
| 29 |
type: int |
| 30 |
disk: |
| 31 |
description: |
| 32 |
- The disk key (V(unused[n]), V(ide[n]), V(sata[n]), V(scsi[n]), V(virtio[n]), V(efidisk[n]) or V(tpmstate[n])) you want to operate on. |
| 33 |
- Disk buses (IDE, SATA and so on) have fixed ranges of V(n) that accepted by Proxmox API. |
| 34 |
- 'For IDE: 0-3; for SCSI: 0-30; for SATA: 0-5; for VirtIO: 0-15; for Unused: 0-255; for EFI disk: 0; for TPM state: 0.' |
| 35 |
type: str |
| 36 |
required: true |
| 37 |
state: |
| 38 |
description: |
| 39 |
- Indicates desired state of the disk. |
| 40 |
- O(state=present) can be used to create, replace disk or update options in existing disk. It will create missing disk |
| 41 |
or update options in existing one by default. See the O(create) parameter description to control behavior of this |
| 42 |
option. |
| 43 |
- Some updates on options (like O(cache)) are not being applied instantly and require VM restart. |
| 44 |
- Use O(state=detached) to detach existing disk from VM but do not remove it entirely. When O(state=detached) and disk |
| 45 |
is V(unused[n]) it will be left in same state (not removed). |
| 46 |
- O(state=moved) may be used to change backing storage for the disk in bounds of the same VM or to send the disk to |
| 47 |
another VM (using the same backing storage). |
| 48 |
- O(state=resized) intended to change the disk size. As of Proxmox 7.2 you can only increase the disk size because shrinking |
| 49 |
disks is not supported by the PVE API and has to be done manually. |
| 50 |
- To entirely remove the disk from backing storage use O(state=absent). |
| 51 |
type: str |
| 52 |
choices: ['present', 'resized', 'detached', 'moved', 'absent'] |
| 53 |
default: present |
| 54 |
create: |
| 55 |
description: |
| 56 |
- With O(create) flag you can control behavior of O(state=present). |
| 57 |
- When O(create=disabled) it will not create new disk (if not exists) but will update options in existing disk. |
| 58 |
- When O(create=regular) it will either create new disk (if not exists) or update options in existing disk. |
| 59 |
- When O(create=forced) it will always create new disk (if disk exists it will be detached and left unused). |
| 60 |
type: str |
| 61 |
choices: ['disabled', 'regular', 'forced'] |
| 62 |
default: regular |
| 63 |
storage: |
| 64 |
description: |
| 65 |
- The drive's backing storage. |
| 66 |
- Used only when O(state) is V(present). |
| 67 |
type: str |
| 68 |
size: |
| 69 |
description: |
| 70 |
- Desired volume size in GiB to allocate when O(state=present) (specify O(size) without suffix). |
| 71 |
- New (or additional) size of volume when O(state=resized). With the V(+) sign the value is added to the actual size |
| 72 |
of the volume and without it, the value is taken as an absolute one (specify O(size) with suffix V(KMGT)). |
| 73 |
type: str |
| 74 |
bwlimit: |
| 75 |
description: |
| 76 |
- Override I/O bandwidth limit (in KB/s). |
| 77 |
- Used only when O(state=moved). |
| 78 |
type: int |
| 79 |
delete_moved: |
| 80 |
description: |
| 81 |
- Delete the original disk after successful copy. |
| 82 |
- By default the original disk is kept as unused disk. |
| 83 |
- Used only when O(state=moved). |
| 84 |
type: bool |
| 85 |
target_disk: |
| 86 |
description: |
| 87 |
- The config key the disk will be moved to on the target VM (for example, V(ide0) or V(scsi1)). |
| 88 |
- Default is the source disk key. |
| 89 |
- Used only when O(state=moved). |
| 90 |
type: str |
| 91 |
target_storage: |
| 92 |
description: |
| 93 |
- Move the disk to this storage when O(state=moved). |
| 94 |
- You can move between storages only in scope of one VM. |
| 95 |
- Mutually exclusive with O(target_vmid). |
| 96 |
- Consider increasing O(timeout) in case of large disk images or slow storage backend. |
| 97 |
type: str |
| 98 |
target_vmid: |
| 99 |
description: |
| 100 |
- The (unique) ID of the VM where disk will be placed when O(state=moved). |
| 101 |
- You can move disk between VMs only when the same storage is used. |
| 102 |
- Mutually exclusive with O(target_storage). |
| 103 |
type: int |
| 104 |
timeout: |
| 105 |
description: |
| 106 |
- Timeout in seconds to wait for slow operations such as importing disk or moving disk between storages. |
| 107 |
- Used only when O(state) is V(present) or V(moved). |
| 108 |
type: int |
| 109 |
default: 600 |
| 110 |
aio: |
| 111 |
description: |
| 112 |
- AIO type to use. |
| 113 |
type: str |
| 114 |
choices: ['native', 'threads', 'io_uring'] |
| 115 |
backup: |
| 116 |
description: |
| 117 |
- Whether the drive should be included when making backups. |
| 118 |
type: bool |
| 119 |
bps_max_length: |
| 120 |
description: |
| 121 |
- Maximum length of total r/w I/O bursts in seconds. |
| 122 |
type: int |
| 123 |
bps_rd_max_length: |
| 124 |
description: |
| 125 |
- Maximum length of read I/O bursts in seconds. |
| 126 |
type: int |
| 127 |
bps_wr_max_length: |
| 128 |
description: |
| 129 |
- Maximum length of write I/O bursts in seconds. |
| 130 |
type: int |
| 131 |
cache: |
| 132 |
description: |
| 133 |
- The drive's cache mode. |
| 134 |
type: str |
| 135 |
choices: ['none', 'writethrough', 'writeback', 'unsafe', 'directsync'] |
| 136 |
cyls: |
| 137 |
description: |
| 138 |
- Force the drive's physical geometry to have a specific cylinder count. |
| 139 |
type: int |
| 140 |
detect_zeroes: |
| 141 |
description: |
| 142 |
- Control whether to detect and try to optimize writes of zeroes. |
| 143 |
type: bool |
| 144 |
discard: |
| 145 |
description: |
| 146 |
- Control whether to pass discard/trim requests to the underlying storage. |
| 147 |
type: str |
| 148 |
choices: ['ignore', 'on'] |
| 149 |
format: |
| 150 |
description: |
| 151 |
- The drive's backing file's data format. |
| 152 |
type: str |
| 153 |
choices: ['raw', 'cow', 'qcow', 'qed', 'qcow2', 'vmdk', 'cloop'] |
| 154 |
heads: |
| 155 |
description: |
| 156 |
- Force the drive's physical geometry to have a specific head count. |
| 157 |
type: int |
| 158 |
import_from: |
| 159 |
description: |
| 160 |
- Import volume from this existing one. |
| 161 |
- Volume string format. |
| 162 |
- V(<STORAGE>:<VMID>/<FULL_NAME>) or V(<ABSOLUTE_PATH>/<FULL_NAME>). |
| 163 |
- V(<STORAGE>:import/<FULL_NAME>) for PVE 9.x and later, to use storage's import directory. |
| 164 |
- Attention! Only root can use absolute paths. |
| 165 |
- This parameter is mutually exclusive with O(size). |
| 166 |
- Increase O(timeout) parameter when importing large disk images or using slow storage. |
| 167 |
type: str |
| 168 |
iops: |
| 169 |
description: |
| 170 |
- Maximum total r/w I/O in operations per second. |
| 171 |
- You can specify either total limit or per operation (mutually exclusive with O(iops_rd) and O(iops_wr)). |
| 172 |
type: int |
| 173 |
iops_max: |
| 174 |
description: |
| 175 |
- Maximum unthrottled total r/w I/O pool in operations per second. |
| 176 |
type: int |
| 177 |
iops_max_length: |
| 178 |
description: |
| 179 |
- Maximum length of total r/w I/O bursts in seconds. |
| 180 |
type: int |
| 181 |
iops_rd: |
| 182 |
description: |
| 183 |
- Maximum read I/O in operations per second. |
| 184 |
- You can specify either read or total limit (mutually exclusive with O(iops)). |
| 185 |
type: int |
| 186 |
iops_rd_max: |
| 187 |
description: |
| 188 |
- Maximum unthrottled read I/O pool in operations per second. |
| 189 |
type: int |
| 190 |
iops_rd_max_length: |
| 191 |
description: |
| 192 |
- Maximum length of read I/O bursts in seconds. |
| 193 |
type: int |
| 194 |
iops_wr: |
| 195 |
description: |
| 196 |
- Maximum write I/O in operations per second. |
| 197 |
- You can specify either write or total limit (mutually exclusive with O(iops)). |
| 198 |
type: int |
| 199 |
iops_wr_max: |
| 200 |
description: |
| 201 |
- Maximum unthrottled write I/O pool in operations per second. |
| 202 |
type: int |
| 203 |
iops_wr_max_length: |
| 204 |
description: |
| 205 |
- Maximum length of write I/O bursts in seconds. |
| 206 |
type: int |
| 207 |
iothread: |
| 208 |
description: |
| 209 |
- Whether to use iothreads for this drive (only for SCSI and VirtIO). |
| 210 |
type: bool |
| 211 |
mbps: |
| 212 |
description: |
| 213 |
- Maximum total r/w speed in megabytes per second. |
| 214 |
- Can be fractional but use with caution - fractionals less than 1 are not supported officially. |
| 215 |
- You can specify either total limit or per operation (mutually exclusive with O(mbps_rd) and O(mbps_wr)). |
| 216 |
type: float |
| 217 |
mbps_max: |
| 218 |
description: |
| 219 |
- Maximum unthrottled total r/w pool in megabytes per second. |
| 220 |
type: float |
| 221 |
mbps_rd: |
| 222 |
description: |
| 223 |
- Maximum read speed in megabytes per second. |
| 224 |
- You can specify either read or total limit (mutually exclusive with O(mbps)). |
| 225 |
type: float |
| 226 |
mbps_rd_max: |
| 227 |
description: |
| 228 |
- Maximum unthrottled read pool in megabytes per second. |
| 229 |
type: float |
| 230 |
mbps_wr: |
| 231 |
description: |
| 232 |
- Maximum write speed in megabytes per second. |
| 233 |
- You can specify either write or total limit (mutually exclusive with O(mbps)). |
| 234 |
type: float |
| 235 |
mbps_wr_max: |
| 236 |
description: |
| 237 |
- Maximum unthrottled write pool in megabytes per second. |
| 238 |
type: float |
| 239 |
media: |
| 240 |
description: |
| 241 |
- The drive's media type. |
| 242 |
type: str |
| 243 |
choices: ['cdrom', 'disk'] |
| 244 |
iso_image: |
| 245 |
description: |
| 246 |
- The ISO image to be mounted on the specified in O(disk) CD-ROM. |
| 247 |
- O(media=cdrom) needs to be specified for this option to work. |
| 248 |
- Use V(<STORAGE>:iso/<ISO_NAME>) to mount ISO. |
| 249 |
- Use V(cdrom) to access the physical CD/DVD drive. |
| 250 |
- Use V(none) to unmount image from existent CD-ROM or create empty CD-ROM drive. |
| 251 |
type: str |
| 252 |
queues: |
| 253 |
description: |
| 254 |
- Number of queues (SCSI only). |
| 255 |
type: int |
| 256 |
replicate: |
| 257 |
description: |
| 258 |
- Whether the drive should considered for replication jobs. |
| 259 |
type: bool |
| 260 |
rerror: |
| 261 |
description: |
| 262 |
- Read error action. |
| 263 |
type: str |
| 264 |
choices: ['ignore', 'report', 'stop'] |
| 265 |
ro: |
| 266 |
description: |
| 267 |
- Whether the drive is read-only. |
| 268 |
type: bool |
| 269 |
scsiblock: |
| 270 |
description: |
| 271 |
- Whether to use scsi-block for full passthrough of host block device. |
| 272 |
- Can lead to I/O errors in combination with low memory or high memory fragmentation on host. |
| 273 |
type: bool |
| 274 |
secs: |
| 275 |
description: |
| 276 |
- Force the drive's physical geometry to have a specific sector count. |
| 277 |
type: int |
| 278 |
serial: |
| 279 |
description: |
| 280 |
- The drive's reported serial number, url-encoded, up to 20 bytes long. |
| 281 |
type: str |
| 282 |
shared: |
| 283 |
description: |
| 284 |
- Mark this locally-managed volume as available on all nodes. |
| 285 |
- This option does not share the volume automatically, it assumes it is shared already! |
| 286 |
type: bool |
| 287 |
snapshot: |
| 288 |
description: |
| 289 |
- Control qemu's snapshot mode feature. |
| 290 |
- If activated, changes made to the disk are temporary and will be discarded when the VM is shutdown. |
| 291 |
type: bool |
| 292 |
ssd: |
| 293 |
description: |
| 294 |
- Whether to expose this drive as an SSD, rather than a rotational hard disk. |
| 295 |
type: bool |
| 296 |
trans: |
| 297 |
description: |
| 298 |
- Force disk geometry bios translation mode. |
| 299 |
type: str |
| 300 |
choices: ['auto', 'lba', 'none'] |
| 301 |
werror: |
| 302 |
description: |
| 303 |
- Write error action. |
| 304 |
type: str |
| 305 |
choices: ['enospc', 'ignore', 'report', 'stop'] |
| 306 |
wwn: |
| 307 |
description: |
| 308 |
- The drive's worldwide name, encoded as 16 bytes hex string, prefixed by V(0x). |
| 309 |
type: str |
| 310 |
extends_documentation_fragment: |
| 311 |
- community.proxmox.proxmox.actiongroup_proxmox |
| 312 |
- community.proxmox.proxmox.documentation |
| 313 |
- community.proxmox.attributes |
| 314 |
""" |
| 315 |
|
| 316 |
EXAMPLES = r""" |
| 317 |
- name: Create new disk in VM (do not rewrite in case it exists already) |
| 318 |
community.proxmox.proxmox_disk: |
| 319 |
name: vm-name |
| 320 |
disk: scsi3 |
| 321 |
backup: true |
| 322 |
cache: none |
| 323 |
storage: local-zfs |
| 324 |
size: 5 |
| 325 |
state: present |
| 326 |
|
| 327 |
- name: Create new disk in VM (force rewrite in case it exists already) |
| 328 |
community.proxmox.proxmox_disk: |
| 329 |
vmid: 101 |
| 330 |
disk: scsi3 |
| 331 |
format: qcow2 |
| 332 |
storage: local |
| 333 |
size: 16 |
| 334 |
create: forced |
| 335 |
state: present |
| 336 |
|
| 337 |
- name: Update existing disk |
| 338 |
community.proxmox.proxmox_disk: |
| 339 |
vmid: 101 |
| 340 |
disk: ide0 |
| 341 |
backup: false |
| 342 |
ro: true |
| 343 |
aio: native |
| 344 |
state: present |
| 345 |
|
| 346 |
- name: Grow existing disk |
| 347 |
community.proxmox.proxmox_disk: |
| 348 |
vmid: 101 |
| 349 |
disk: sata4 |
| 350 |
size: +5G |
| 351 |
state: resized |
| 352 |
|
| 353 |
- name: Detach disk (leave it unused) |
| 354 |
community.proxmox.proxmox_disk: |
| 355 |
name: vm-name |
| 356 |
disk: virtio0 |
| 357 |
state: detached |
| 358 |
|
| 359 |
- name: Move disk to another storage |
| 360 |
community.proxmox.proxmox_disk: |
| 361 |
vmid: 101 |
| 362 |
disk: scsi7 |
| 363 |
target_storage: local |
| 364 |
format: qcow2 |
| 365 |
state: moved |
| 366 |
|
| 367 |
- name: Move disk from one VM to another |
| 368 |
community.proxmox.proxmox_disk: |
| 369 |
vmid: 101 |
| 370 |
disk: scsi7 |
| 371 |
target_vmid: 201 |
| 372 |
state: moved |
| 373 |
|
| 374 |
- name: Remove disk permanently |
| 375 |
community.proxmox.proxmox_disk: |
| 376 |
vmid: 101 |
| 377 |
disk: scsi4 |
| 378 |
state: absent |
| 379 |
|
| 380 |
- name: Mount ISO image on CD-ROM (create drive if missing) |
| 381 |
community.proxmox.proxmox_disk: |
| 382 |
vmid: 101 |
| 383 |
disk: ide2 |
| 384 |
media: cdrom |
| 385 |
iso_image: local:iso/favorite_distro_amd64.iso |
| 386 |
state: present |
| 387 |
""" |
| 388 |
|
| 389 |
RETURN = r""" |
| 390 |
vmid: |
| 391 |
description: The VM vmid. |
| 392 |
returned: success |
| 393 |
type: int |
| 394 |
sample: 101 |
| 395 |
msg: |
| 396 |
description: A short message on what the module did. |
| 397 |
returned: always |
| 398 |
type: str |
| 399 |
sample: "Disk scsi3 created in VM 101" |
| 400 |
""" |
| 401 |
|
| 402 |
import re |
| 403 |
|
| 404 |
from ansible_collections.community.proxmox.plugins.module_utils.proxmox import ( |
| 405 |
ProxmoxAnsible, |
| 406 |
create_proxmox_module, |
| 407 |
) |
| 408 |
from ansible_collections.community.proxmox.plugins.module_utils.version import LooseVersion |
| 409 |
|
| 410 |
|
| 411 |
def disk_conf_str_to_dict(config_string): |
| 412 |
""" |
| 413 |
Transform Proxmox configuration string for disk element into dictionary which has |
| 414 |
volume option parsed in '{ storage }:{ volume }' format and other options parsed |
| 415 |
in '{ option }={ value }' format. This dictionary will be compared afterward with |
| 416 |
attributes that user passed to this module in playbook.\n |
| 417 |
config_string examples: |
| 418 |
- local-lvm:vm-100-disk-0,ssd=1,discard=on,size=25G |
| 419 |
- local:iso/new-vm-ignition.iso,media=cdrom,size=70k |
| 420 |
- none,media=cdrom |
| 421 |
:param config_string: Retrieved from Proxmox API configuration string |
| 422 |
:return: Dictionary with volume option divided into parts ('volume_name', 'storage_name', 'volume') \n |
| 423 |
and other options as key:value. |
| 424 |
""" |
| 425 |
config = config_string.split(",") |
| 426 |
|
| 427 |
# When empty CD-ROM drive present, the volume part of config string is "none". |
| 428 |
storage_volume = config.pop(0) |
| 429 |
if storage_volume in ["none", "cdrom"]: |
| 430 |
config_current = dict( |
| 431 |
volume=storage_volume, |
| 432 |
storage_name=str(None), |
| 433 |
volume_name=str(None), |
| 434 |
size=str(None), |
| 435 |
) |
| 436 |
else: |
| 437 |
storage_volume = storage_volume.split(":") |
| 438 |
storage_name = storage_volume[0] |
| 439 |
volume_name = storage_volume[1] |
| 440 |
config_current = dict( |
| 441 |
volume=f"{storage_name}:{volume_name}", |
| 442 |
storage_name=storage_name, |
| 443 |
volume_name=volume_name, |
| 444 |
) |
| 445 |
|
| 446 |
config.sort() |
| 447 |
for option in config: |
| 448 |
k, v = option.split("=") |
| 449 |
config_current[k] = v |
| 450 |
|
| 451 |
return config_current |
| 452 |
|
| 453 |
|
| 454 |
def module_args(): |
| 455 |
return dict( |
| 456 |
# Proxmox native parameters |
| 457 |
aio=dict(type="str", choices=["native", "threads", "io_uring"]), |
| 458 |
backup=dict(type="bool"), |
| 459 |
bps_max_length=dict(type="int"), |
| 460 |
bps_rd_max_length=dict(type="int"), |
| 461 |
bps_wr_max_length=dict(type="int"), |
| 462 |
cache=dict(type="str", choices=["none", "writethrough", "writeback", "unsafe", "directsync"]), |
| 463 |
cyls=dict(type="int"), |
| 464 |
detect_zeroes=dict(type="bool"), |
| 465 |
discard=dict(type="str", choices=["ignore", "on"]), |
| 466 |
format=dict(type="str", choices=["raw", "cow", "qcow", "qed", "qcow2", "vmdk", "cloop"]), |
| 467 |
heads=dict(type="int"), |
| 468 |
import_from=dict(type="str"), |
| 469 |
iops=dict(type="int"), |
| 470 |
iops_max=dict(type="int"), |
| 471 |
iops_max_length=dict(type="int"), |
| 472 |
iops_rd=dict(type="int"), |
| 473 |
iops_rd_max=dict(type="int"), |
| 474 |
iops_rd_max_length=dict(type="int"), |
| 475 |
iops_wr=dict(type="int"), |
| 476 |
iops_wr_max=dict(type="int"), |
| 477 |
iops_wr_max_length=dict(type="int"), |
| 478 |
iothread=dict(type="bool"), |
| 479 |
iso_image=dict(type="str"), |
| 480 |
mbps=dict(type="float"), |
| 481 |
mbps_max=dict(type="float"), |
| 482 |
mbps_rd=dict(type="float"), |
| 483 |
mbps_rd_max=dict(type="float"), |
| 484 |
mbps_wr=dict(type="float"), |
| 485 |
mbps_wr_max=dict(type="float"), |
| 486 |
media=dict(type="str", choices=["cdrom", "disk"]), |
| 487 |
queues=dict(type="int"), |
| 488 |
replicate=dict(type="bool"), |
| 489 |
rerror=dict(type="str", choices=["ignore", "report", "stop"]), |
| 490 |
ro=dict(type="bool"), |
| 491 |
scsiblock=dict(type="bool"), |
| 492 |
secs=dict(type="int"), |
| 493 |
serial=dict(type="str"), |
| 494 |
shared=dict(type="bool"), |
| 495 |
snapshot=dict(type="bool"), |
| 496 |
ssd=dict(type="bool"), |
| 497 |
trans=dict(type="str", choices=["auto", "lba", "none"]), |
| 498 |
werror=dict(type="str", choices=["enospc", "ignore", "report", "stop"]), |
| 499 |
wwn=dict(type="str"), |
| 500 |
# Disk moving relates parameters |
| 501 |
bwlimit=dict(type="int"), |
| 502 |
target_storage=dict(type="str"), |
| 503 |
target_disk=dict(type="str"), |
| 504 |
target_vmid=dict(type="int"), |
| 505 |
delete_moved=dict(type="bool"), |
| 506 |
timeout=dict(type="int", default="600"), |
| 507 |
# Module related parameters |
| 508 |
name=dict(type="str"), |
| 509 |
vmid=dict(type="int"), |
| 510 |
disk=dict(type="str", required=True), |
| 511 |
storage=dict(type="str"), |
| 512 |
size=dict(type="str"), |
| 513 |
state=dict(type="str", choices=["present", "resized", "detached", "moved", "absent"], default="present"), |
| 514 |
create=dict(type="str", choices=["disabled", "regular", "forced"], default="regular"), |
| 515 |
) |
| 516 |
|
| 517 |
|
| 518 |
def module_options(): |
| 519 |
return dict( |
| 520 |
required_one_of=[("name", "vmid")], |
| 521 |
required_if=[ |
| 522 |
("create", "forced", ["storage"]), |
| 523 |
("state", "resized", ["size"]), |
| 524 |
], |
| 525 |
required_by={ |
| 526 |
"target_disk": "target_vmid", |
| 527 |
"mbps_max": "mbps", |
| 528 |
"mbps_rd_max": "mbps_rd", |
| 529 |
"mbps_wr_max": "mbps_wr", |
| 530 |
"bps_max_length": "mbps_max", |
| 531 |
"bps_rd_max_length": "mbps_rd_max", |
| 532 |
"bps_wr_max_length": "mbps_wr_max", |
| 533 |
"iops_max": "iops", |
| 534 |
"iops_rd_max": "iops_rd", |
| 535 |
"iops_wr_max": "iops_wr", |
| 536 |
"iops_max_length": "iops_max", |
| 537 |
"iops_rd_max_length": "iops_rd_max", |
| 538 |
"iops_wr_max_length": "iops_wr_max", |
| 539 |
"iso_image": "media", |
| 540 |
}, |
| 541 |
supports_check_mode=False, |
| 542 |
mutually_exclusive=[ |
| 543 |
("target_vmid", "target_storage"), |
| 544 |
("mbps", "mbps_rd"), |
| 545 |
("mbps", "mbps_wr"), |
| 546 |
("iops", "iops_rd"), |
| 547 |
("iops", "iops_wr"), |
| 548 |
("import_from", "size"), |
| 549 |
], |
| 550 |
) |
| 551 |
|
| 552 |
|
| 553 |
class ProxmoxDiskAnsible(ProxmoxAnsible): |
| 554 |
create_update_fields = [ |
| 555 |
"aio", |
| 556 |
"backup", |
| 557 |
"bps_max_length", |
| 558 |
"bps_rd_max_length", |
| 559 |
"bps_wr_max_length", |
| 560 |
"cache", |
| 561 |
"cyls", |
| 562 |
"detect_zeroes", |
| 563 |
"discard", |
| 564 |
"format", |
| 565 |
"heads", |
| 566 |
"import_from", |
| 567 |
"iops", |
| 568 |
"iops_max", |
| 569 |
"iops_max_length", |
| 570 |
"iops_rd", |
| 571 |
"iops_rd_max", |
| 572 |
"iops_rd_max_length", |
| 573 |
"iops_wr", |
| 574 |
"iops_wr_max", |
| 575 |
"iops_wr_max_length", |
| 576 |
"iothread", |
| 577 |
"mbps", |
| 578 |
"mbps_max", |
| 579 |
"mbps_rd", |
| 580 |
"mbps_rd_max", |
| 581 |
"mbps_wr", |
| 582 |
"mbps_wr_max", |
| 583 |
"media", |
| 584 |
"queues", |
| 585 |
"replicate", |
| 586 |
"rerror", |
| 587 |
"ro", |
| 588 |
"scsiblock", |
| 589 |
"secs", |
| 590 |
"serial", |
| 591 |
"shared", |
| 592 |
"snapshot", |
| 593 |
"ssd", |
| 594 |
"trans", |
| 595 |
"werror", |
| 596 |
"wwn", |
| 597 |
] |
| 598 |
supported_bus_num_ranges = dict( |
| 599 |
ide=range(0, 4), |
| 600 |
scsi=range(0, 31), |
| 601 |
sata=range(0, 6), |
| 602 |
virtio=range(0, 16), |
| 603 |
unused=range(0, 256), |
| 604 |
efidisk=range(0, 1), |
| 605 |
tpmstate=range(0, 1), |
| 606 |
) |
| 607 |
|
| 608 |
def get_create_attributes(self): |
| 609 |
# Sanitize parameters dictionary: |
| 610 |
# - Remove not defined args |
| 611 |
# - Ensure True and False converted to int. |
| 612 |
# - Remove unnecessary parameters |
| 613 |
params = { |
| 614 |
k: int(v) if isinstance(v, bool) else v |
| 615 |
for k, v in self.module.params.items() |
| 616 |
if v is not None and k in self.create_update_fields |
| 617 |
} |
| 618 |
return params |
| 619 |
|
| 620 |
def create_disk(self, disk, vmid, vm, vm_config): # noqa: PLR0912 |
| 621 |
"""Create a disk in the specified virtual machine. Check if creation is required, |
| 622 |
and if so, compile the disk configuration and create it by updating the virtual |
| 623 |
machine configuration. After calling the API function, wait for the result. |
| 624 |
|
| 625 |
:param disk: ID of the disk in format "<bus><number>". |
| 626 |
:param vmid: ID of the virtual machine where the disk will be created. |
| 627 |
:param vm: Name of the virtual machine where the disk will be created. |
| 628 |
:param vm_config: Configuration of the virtual machine. |
| 629 |
:return: (bool, string) Whether the task was successful or not |
| 630 |
and the message to return to Ansible. |
| 631 |
""" |
| 632 |
create = self.module.params["create"] |
| 633 |
if create == "disabled" and disk not in vm_config: |
| 634 |
# NOOP |
| 635 |
return False, f"Disk {disk} not found in VM {vmid} and creation was disabled in parameters." |
| 636 |
|
| 637 |
timeout_str = "Reached timeout. Last line in task before timeout: %s" |
| 638 |
if (create == "regular" and disk not in vm_config) or (create == "forced"): |
| 639 |
# CREATE |
| 640 |
playbook_config = self.get_create_attributes() |
| 641 |
import_string = playbook_config.pop("import_from", None) |
| 642 |
iso_image = self.module.params.get("iso_image", None) |
| 643 |
|
| 644 |
if import_string: |
| 645 |
# When 'import_from' option is present in task options. |
| 646 |
config_str = f"{self.module.params['storage']}:0,import-from={import_string}" |
| 647 |
timeout_str = "Reached timeout while importing VM disk. Last line in task before timeout: %s" |
| 648 |
ok_str = "Disk %s imported into VM %s" |
| 649 |
elif iso_image is not None: |
| 650 |
# disk=<busN>, media=cdrom, iso_image=<ISO_NAME> |
| 651 |
config_str = iso_image |
| 652 |
ok_str = "CD-ROM was created on %s bus in VM %s" |
| 653 |
else: |
| 654 |
config_str = self.module.params["storage"] |
| 655 |
if not config_str: |
| 656 |
self.module.fail_json(msg="The storage option must be specified.") |
| 657 |
if self.module.params.get("media") != "cdrom": |
| 658 |
config_str += f":{self.module.params['size']}" |
| 659 |
ok_str = "Disk %s created in VM %s" |
| 660 |
timeout_str = "Reached timeout while creating VM disk. Last line in task before timeout: %s" |
| 661 |
|
| 662 |
for k, v in playbook_config.items(): |
| 663 |
config_str += f",{k}={v}" |
| 664 |
|
| 665 |
disk_config_to_apply = {self.module.params["disk"]: config_str} |
| 666 |
|
| 667 |
if create in ["disabled", "regular"] and disk in vm_config: |
| 668 |
# UPDATE |
| 669 |
ok_str = "Disk %s updated in VM %s" |
| 670 |
iso_image = self.module.params.get("iso_image", None) |
| 671 |
|
| 672 |
proxmox_config = disk_conf_str_to_dict(vm_config[disk]) |
| 673 |
# 'import_from' fails on disk updates |
| 674 |
playbook_config = self.get_create_attributes() |
| 675 |
playbook_config.pop("import_from", None) |
| 676 |
|
| 677 |
# Begin composing configuration string |
| 678 |
if iso_image is not None: |
| 679 |
config_str = iso_image |
| 680 |
else: |
| 681 |
config_str = proxmox_config["volume"] |
| 682 |
# Append all mandatory fields from playbook_config |
| 683 |
for k, v in playbook_config.items(): |
| 684 |
config_str += f",{k}={v}" |
| 685 |
|
| 686 |
# Append to playbook_config fields which are constants for disk images |
| 687 |
for option in ["size", "storage_name", "volume", "volume_name"]: |
| 688 |
playbook_config.update({option: proxmox_config[option]}) |
| 689 |
# CD-ROM is special disk device and its disk image is subject to change |
| 690 |
if iso_image is not None: |
| 691 |
playbook_config["volume"] = iso_image |
| 692 |
# Values in params are numbers, but strings are needed to compare with disk_config |
| 693 |
playbook_config = {k: str(v) for k, v in playbook_config.items()} |
| 694 |
|
| 695 |
# Now compare old and new config to detect if changes are needed |
| 696 |
if proxmox_config == playbook_config: |
| 697 |
return False, f"Disk {disk} is up to date in VM {vmid}" |
| 698 |
|
| 699 |
disk_config_to_apply = {self.module.params["disk"]: config_str} |
| 700 |
|
| 701 |
current_task_id = self.proxmox_api.nodes(vm["node"]).qemu(vmid).config.post(**disk_config_to_apply) |
| 702 |
task_success, fail_reason = self.api_task_complete(vm["node"], current_task_id, self.module.params["timeout"]) |
| 703 |
|
| 704 |
if task_success: |
| 705 |
return True, ok_str % (disk, vmid) |
| 706 |
elif fail_reason == ProxmoxAnsible.TASK_TIMED_OUT: |
| 707 |
self.module.fail_json( |
| 708 |
msg=timeout_str % self.proxmox_api.nodes(vm["node"]).tasks(current_task_id).log.get()[:1] |
| 709 |
) |
| 710 |
else: |
| 711 |
self.module.fail_json(msg=f"Error occurred on task execution: {fail_reason}") |
| 712 |
|
| 713 |
def move_disk(self, disk, vmid, vm, vm_config): |
| 714 |
"""Call the `move_disk` API function that moves the disk to another storage and wait for the result. |
| 715 |
|
| 716 |
:param disk: ID of disk in format "<bus><number>". |
| 717 |
:param vmid: ID of virtual machine which disk will be moved. |
| 718 |
:param vm: Name of virtual machine which disk will be moved. |
| 719 |
:param vm_config: Virtual machine configuration. |
| 720 |
:return: (bool, string) Whether the task was successful or not |
| 721 |
and the message to return to Ansible. |
| 722 |
""" |
| 723 |
disk_config = disk_conf_str_to_dict(vm_config[disk]) |
| 724 |
disk_storage = disk_config["storage_name"] |
| 725 |
|
| 726 |
params = dict() |
| 727 |
params["disk"] = disk |
| 728 |
params["vmid"] = vmid |
| 729 |
params["bwlimit"] = self.module.params["bwlimit"] |
| 730 |
params["storage"] = self.module.params["target_storage"] |
| 731 |
params["target-disk"] = self.module.params["target_disk"] |
| 732 |
params["target-vmid"] = self.module.params["target_vmid"] |
| 733 |
params["format"] = self.module.params["format"] |
| 734 |
params["delete"] = 1 if self.module.params.get("delete_moved", False) else 0 |
| 735 |
# Remove not defined args |
| 736 |
params = {k: v for k, v in params.items() if v is not None} |
| 737 |
|
| 738 |
if params.get("storage", False): |
| 739 |
# Check if the disk is already in the target storage. |
| 740 |
disk_config = disk_conf_str_to_dict(vm_config[disk]) |
| 741 |
if params["storage"] == disk_config["storage_name"]: |
| 742 |
return False, f"Disk {disk} already at {disk_storage} storage" |
| 743 |
|
| 744 |
current_task_id = self.proxmox_api.nodes(vm["node"]).qemu(vmid).move_disk.post(**params) |
| 745 |
task_success, fail_reason = self.api_task_complete(vm["node"], current_task_id, self.module.params["timeout"]) |
| 746 |
|
| 747 |
if task_success: |
| 748 |
return True, f"Disk {disk} moved from VM {vmid} storage {disk_storage}" |
| 749 |
elif fail_reason == ProxmoxAnsible.TASK_TIMED_OUT: |
| 750 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(current_task_id).log.get()[:1] |
| 751 |
self.module.fail_json( |
| 752 |
msg=f"Reached timeout while waiting for moving VM disk. Last line in task before timeout: {last_log}" |
| 753 |
) |
| 754 |
else: |
| 755 |
self.module.fail_json(msg=f"Error occurred on task execution: {fail_reason}") |
| 756 |
|
| 757 |
def resize_disk(self, disk, vmid, vm, vm_config): |
| 758 |
"""Call the `resize` API function to change the disk size and wait for the result. |
| 759 |
|
| 760 |
:param disk: ID of disk in format "<bus><number>". |
| 761 |
:param vmid: ID of virtual machine which disk will be resized. |
| 762 |
:param vm: Name of virtual machine which disk will be resized. |
| 763 |
:param vm_config: Virtual machine configuration. |
| 764 |
:return: (Bool, string) Whether the task was successful or not |
| 765 |
and the message to return to Ansible. |
| 766 |
""" |
| 767 |
size = self.module.params["size"] |
| 768 |
if not re.match(r"^\+?\d+(\.\d+)?[KMGT]?$", size): |
| 769 |
self.module.fail_json(msg=f"Unrecognized size pattern for disk {disk}: {size}") |
| 770 |
disk_config = disk_conf_str_to_dict(vm_config[disk]) |
| 771 |
actual_size = disk_config["size"] |
| 772 |
if size == actual_size: |
| 773 |
return False, f"Disk {disk} is already {size} size" |
| 774 |
|
| 775 |
# Resize disk API endpoint has changed at v8.0: PUT method become async. |
| 776 |
version = self.version() |
| 777 |
pve_major_version = 3 if version < LooseVersion("4.0") else version.version[0] |
| 778 |
if pve_major_version >= 8: # noqa: PLR2004 |
| 779 |
current_task_id = self.proxmox_api.nodes(vm["node"]).qemu(vmid).resize.set(disk=disk, size=size) |
| 780 |
task_success, fail_reason = self.api_task_complete( |
| 781 |
vm["node"], current_task_id, self.module.params["timeout"] |
| 782 |
) |
| 783 |
if task_success: |
| 784 |
return True, f"Disk {disk} resized in VM {vmid}" |
| 785 |
elif fail_reason == ProxmoxAnsible.TASK_TIMED_OUT: |
| 786 |
last_log = self.proxmox_api.nodes(vm["node"]).tasks(current_task_id).log.get()[:1] |
| 787 |
self.module.fail_json( |
| 788 |
msg=f"Reached timeout while resizing disk. Last line in task before timeout: {last_log}" |
| 789 |
) |
| 790 |
else: |
| 791 |
self.module.fail_json(msg=f"Error occurred on task execution: {fail_reason}") |
| 792 |
else: |
| 793 |
self.proxmox_api.nodes(vm["node"]).qemu(vmid).resize.set(disk=disk, size=size) |
| 794 |
return True, f"Disk {disk} resized in VM {vmid}" |
| 795 |
|
| 796 |
|
| 797 |
def main(): # noqa: PLR0912, PLR0915 |
| 798 |
module = create_proxmox_module(module_args(), **module_options()) |
| 799 |
proxmox = ProxmoxDiskAnsible(module) |
| 800 |
|
| 801 |
disk = module.params["disk"] |
| 802 |
# Verify disk name has appropriate name |
| 803 |
disk_regex = re.compile(r"^([a-z]+)([0-9]+)$") |
| 804 |
disk_bus = re.sub(disk_regex, r"\1", disk) |
| 805 |
disk_number = int(re.sub(disk_regex, r"\2", disk)) |
| 806 |
if disk_bus not in proxmox.supported_bus_num_ranges: |
| 807 |
proxmox.module.fail_json(msg=f"Unsupported disk bus: {disk_bus}") |
| 808 |
elif disk_number not in proxmox.supported_bus_num_ranges[disk_bus]: |
| 809 |
bus_range = proxmox.supported_bus_num_ranges[disk_bus] |
| 810 |
proxmox.module.fail_json(msg=f"Disk {disk} number not in range {bus_range[0]}..{bus_range[-1]} ") |
| 811 |
|
| 812 |
name = module.params["name"] |
| 813 |
state = module.params["state"] |
| 814 |
vmid = module.params["vmid"] or proxmox.get_vmid(name) |
| 815 |
|
| 816 |
# Ensure VM id exists and retrieve its config |
| 817 |
vm = None |
| 818 |
vm_config = None |
| 819 |
try: |
| 820 |
vm = proxmox.get_vm(vmid) |
| 821 |
vm_config = proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).config.get() |
| 822 |
except Exception as e: |
| 823 |
proxmox.module.fail_json(msg=f"Getting information for VM {vmid} failed with exception: {str(e)}") |
| 824 |
|
| 825 |
# Do not try to perform actions on missing disk |
| 826 |
if disk not in vm_config and state in ["resized", "moved"]: |
| 827 |
module.fail_json(vmid=vmid, msg=f"Unable to process missing disk {disk} in VM {vmid}") |
| 828 |
|
| 829 |
if state == "present": |
| 830 |
try: |
| 831 |
changed, message = proxmox.create_disk(disk, vmid, vm, vm_config) |
| 832 |
module.exit_json(changed=changed, vmid=vmid, msg=message) |
| 833 |
except Exception as e: |
| 834 |
module.fail_json(vmid=vmid, msg=f"Unable to create/update disk {disk} in VM {vmid}: {str(e)}") |
| 835 |
|
| 836 |
elif state == "detached": |
| 837 |
try: |
| 838 |
if disk_bus == "unused": |
| 839 |
module.exit_json(changed=False, vmid=vmid, msg=f"Disk {disk} already detached in VM {vmid}") |
| 840 |
if disk not in vm_config: |
| 841 |
module.exit_json(changed=False, vmid=vmid, msg=f"Disk {disk} not present in VM {vmid} config") |
| 842 |
proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).unlink.put(idlist=disk, force=0) |
| 843 |
module.exit_json(changed=True, vmid=vmid, msg=f"Disk {disk} detached from VM {vmid}") |
| 844 |
except Exception as e: |
| 845 |
module.fail_json(msg=f"Failed to detach disk {disk} from VM {vmid} with exception: {str(e)}") |
| 846 |
|
| 847 |
elif state == "moved": |
| 848 |
try: |
| 849 |
changed, message = proxmox.move_disk(disk, vmid, vm, vm_config) |
| 850 |
module.exit_json(changed=changed, vmid=vmid, msg=message) |
| 851 |
except Exception as e: |
| 852 |
module.fail_json(msg=f"Failed to move disk {disk} in VM {vmid} with exception: {str(e)}") |
| 853 |
|
| 854 |
elif state == "resized": |
| 855 |
try: |
| 856 |
changed, message = proxmox.resize_disk(disk, vmid, vm, vm_config) |
| 857 |
module.exit_json(changed=changed, vmid=vmid, msg=message) |
| 858 |
except Exception as e: |
| 859 |
module.fail_json(msg=f"Failed to resize disk {disk} in VM {vmid} with exception: {str(e)}") |
| 860 |
|
| 861 |
elif state == "absent": |
| 862 |
try: |
| 863 |
if disk not in vm_config: |
| 864 |
module.exit_json(changed=False, vmid=vmid, msg=f"Disk {disk} is already absent in VM {vmid}") |
| 865 |
proxmox.proxmox_api.nodes(vm["node"]).qemu(vmid).unlink.put(idlist=disk, force=1) |
| 866 |
module.exit_json(changed=True, vmid=vmid, msg=f"Disk {disk} removed from VM {vmid}") |
| 867 |
except Exception as e: |
| 868 |
module.fail_json(vmid=vmid, msg=f"Unable to remove disk {disk} from VM {vmid}: {str(e)}") |
| 869 |
|
| 870 |
|
| 871 |
if __name__ == "__main__": |
| 872 |
main() |