| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright: (c) 2018, Ansible Project |
| 5 |
# Copyright: (c) 2018, Abhijeet Kasurde <[email protected]> |
| 6 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 7 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 8 |
|
| 9 |
from __future__ import absolute_import, division, print_function |
| 10 |
__metaclass__ = type |
| 11 |
|
| 12 |
|
| 13 |
DOCUMENTATION = r''' |
| 14 |
--- |
| 15 |
module: vmware_guest_disk |
| 16 |
short_description: Manage disks related to virtual machine in given vCenter infrastructure |
| 17 |
description: |
| 18 |
- This module can be used to add, remove and update disks belonging to given virtual machine. |
| 19 |
- This module is destructive in nature, please read documentation carefully before proceeding. |
| 20 |
- Be careful while removing disk specified as this may lead to data loss. |
| 21 |
author: |
| 22 |
- Abhijeet Kasurde (@Akasurde) <[email protected]> |
| 23 |
options: |
| 24 |
name: |
| 25 |
description: |
| 26 |
- Name of the virtual machine. |
| 27 |
- This is a required parameter, if parameter O(uuid) or O(moid) is not supplied. |
| 28 |
type: str |
| 29 |
uuid: |
| 30 |
description: |
| 31 |
- UUID of the instance to gather facts if known, this is VMware's unique identifier. |
| 32 |
- This is a required parameter, if parameter O(name) or O(moid) is not supplied. |
| 33 |
type: str |
| 34 |
moid: |
| 35 |
description: |
| 36 |
- Managed Object ID of the instance to manage if known, this is a unique identifier only within a single vCenter instance. |
| 37 |
- This is required if O(name) or O(uuid) is not supplied. |
| 38 |
type: str |
| 39 |
folder: |
| 40 |
description: |
| 41 |
- Destination folder, absolute or relative path to find an existing guest. |
| 42 |
- This is a required parameter, only if multiple VMs are found with same name. |
| 43 |
- The folder should include the datacenter. ESX's datacenter is ha-datacenter |
| 44 |
- 'Examples:' |
| 45 |
- ' folder: /ha-datacenter/vm' |
| 46 |
- ' folder: ha-datacenter/vm' |
| 47 |
- ' folder: /datacenter1/vm' |
| 48 |
- ' folder: datacenter1/vm' |
| 49 |
- ' folder: /datacenter1/vm/folder1' |
| 50 |
- ' folder: datacenter1/vm/folder1' |
| 51 |
- ' folder: /folder1/datacenter1/vm' |
| 52 |
- ' folder: folder1/datacenter1/vm' |
| 53 |
- ' folder: /folder1/datacenter1/vm/folder2' |
| 54 |
type: str |
| 55 |
datacenter: |
| 56 |
description: |
| 57 |
- The datacenter name to which virtual machine belongs to. |
| 58 |
required: true |
| 59 |
type: str |
| 60 |
use_instance_uuid: |
| 61 |
description: |
| 62 |
- Whether to use the VMware instance UUID rather than the BIOS UUID. |
| 63 |
default: false |
| 64 |
type: bool |
| 65 |
disk: |
| 66 |
description: |
| 67 |
- A list of disks to add or remove. |
| 68 |
- The virtual disk related information is provided using this list. |
| 69 |
suboptions: |
| 70 |
size: |
| 71 |
description: |
| 72 |
- Disk storage size. |
| 73 |
- If size specified then unit must be specified. There is no space allowed in between size number and unit. |
| 74 |
- Only first occurrence in disk element will be considered, even if there are multiple size* parameters available. |
| 75 |
type: str |
| 76 |
size_kb: |
| 77 |
description: Disk storage size in kb. |
| 78 |
type: int |
| 79 |
size_mb: |
| 80 |
description: Disk storage size in mb. |
| 81 |
type: int |
| 82 |
size_gb: |
| 83 |
description: Disk storage size in gb. |
| 84 |
type: int |
| 85 |
size_tb: |
| 86 |
description: Disk storage size in tb. |
| 87 |
type: int |
| 88 |
type: |
| 89 |
description: |
| 90 |
- The type of disk, if not specified then use V(thick) type for new disk, no eagerzero. |
| 91 |
type: str |
| 92 |
choices: ['thin', 'eagerzeroedthick', 'thick', 'rdm', 'vpmemdisk'] |
| 93 |
disk_mode: |
| 94 |
description: |
| 95 |
- Type of disk mode. If not specified then use V(persistent) mode for new disk. |
| 96 |
- If set to V(persistent) mode, changes are immediately and permanently written to the virtual disk. |
| 97 |
- If set to V(independent_persistent) mode, same as persistent, but not affected by snapshots. |
| 98 |
- If set to V('independent_nonpersistent) mode, changes to virtual disk are made to a redo log and discarded |
| 99 |
at power off, but not affected by snapshots. |
| 100 |
- Not applicable when disk O(disk[].type=vpmemdisk). |
| 101 |
type: str |
| 102 |
choices: ['persistent', 'independent_persistent', 'independent_nonpersistent'] |
| 103 |
rdm_path: |
| 104 |
description: |
| 105 |
- Path of LUN for Raw Device Mapping required for O(disk[].type=rdm). |
| 106 |
- Only valid if O(disk[].type=rdm). |
| 107 |
type: str |
| 108 |
cluster_disk: |
| 109 |
description: |
| 110 |
- This value allows for the sharing of an RDM between two machines. |
| 111 |
- The primary machine holding the RDM uses the default V(false). |
| 112 |
- The secondary machine holding the RDM uses V(true). |
| 113 |
type: bool |
| 114 |
default: false |
| 115 |
compatibility_mode: |
| 116 |
description: Compatibility mode for raw devices. Required when O(disk[].type=rdm). |
| 117 |
type: str |
| 118 |
choices: ['physicalMode','virtualMode'] |
| 119 |
sharing: |
| 120 |
description: |
| 121 |
- The sharing mode of the virtual disk. |
| 122 |
- Setting sharing means that multiple virtual machines can write to the virtual disk. |
| 123 |
- Sharing can only be set if O(disk[].type=eagerzeroedthick) or O(disk[].type=rdm). |
| 124 |
type: bool |
| 125 |
default: false |
| 126 |
datastore: |
| 127 |
description: |
| 128 |
- Name of datastore or datastore cluster to be used for the disk. |
| 129 |
- Not applicable when disk O(disk[].type=vpmemdisk). |
| 130 |
type: str |
| 131 |
autoselect_datastore: |
| 132 |
description: |
| 133 |
- Select the less used datastore. Specify only if O(disk[].datastore) is not specified. |
| 134 |
- Not applicable when disk O(disk[].type=vpmemdisk). |
| 135 |
type: bool |
| 136 |
scsi_controller: |
| 137 |
description: |
| 138 |
- SCSI controller number. Only 4 SCSI controllers are allowed per VM. |
| 139 |
type: int |
| 140 |
choices: [0, 1, 2, 3] |
| 141 |
bus_sharing: |
| 142 |
description: |
| 143 |
- Only functions with Paravirtual SCSI Controller. |
| 144 |
- Allows for the sharing of the scsi bus between two virtual machines. |
| 145 |
type: str |
| 146 |
choices: ['noSharing', 'physicalSharing', 'virtualSharing'] |
| 147 |
default: 'noSharing' |
| 148 |
unit_number: |
| 149 |
description: |
| 150 |
- Disk Unit Number. |
| 151 |
- Valid value range from 0 to 15, except 7 for SCSI Controller. |
| 152 |
- Valid value range from 0 to 64, except 7 for Paravirtual SCSI Controller on Virtual Hardware version 14 or higher. |
| 153 |
- Valid value range from 0 to 29 for SATA controller. |
| 154 |
- Valid value range from 0 to 14 for NVME controller. |
| 155 |
- Valid value range from 0 to 1 for IDE controller. |
| 156 |
type: int |
| 157 |
required: true |
| 158 |
scsi_type: |
| 159 |
description: |
| 160 |
- Type of SCSI controller. This value is required only for the first occurrence of SCSI Controller. |
| 161 |
- This value is ignored, if SCSI Controller is already present or O(disk[].state=absent). |
| 162 |
type: str |
| 163 |
choices: ['buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual'] |
| 164 |
destroy: |
| 165 |
description: If O(disk[].state=absent), make sure the disk file is deleted from the datastore. |
| 166 |
type: bool |
| 167 |
default: true |
| 168 |
filename: |
| 169 |
description: |
| 170 |
- Existing disk image to be used. Filename must already exist on the datastore. |
| 171 |
- Specify filename string in C([datastore_name] path/to/file.vmdk) format. |
| 172 |
- Not applicable when disk O(disk[].type=vpmemdisk). |
| 173 |
type: str |
| 174 |
state: |
| 175 |
description: |
| 176 |
- State of disk. |
| 177 |
- If set to V(absent), disk will be removed permanently from virtual machine configuration and from VMware storage. |
| 178 |
- If set to V(present), disk will be added if not present at given Controller and Unit Number. |
| 179 |
- or disk exists with different size, disk size is increased, reducing disk size is not allowed. |
| 180 |
type: str |
| 181 |
choices: ['present', 'absent'] |
| 182 |
default: 'present' |
| 183 |
controller_type: |
| 184 |
description: |
| 185 |
- This parameter is added for managing disks attaching other types of controllers, e.g., SATA or NVMe. |
| 186 |
- If either O(disk[].controller_type) or O(disk[].scsi_type) is not specified, then use V(paravirtual) type. |
| 187 |
type: str |
| 188 |
choices: ['buslogic', 'lsilogic', 'lsilogicsas', 'paravirtual', 'sata', 'nvme', 'ide'] |
| 189 |
controller_number: |
| 190 |
description: |
| 191 |
- This parameter is used with O(disk[].controller_type) for specifying controller bus number. |
| 192 |
- For O(disk[].controller_type=ide), valid value is 0 or 1. |
| 193 |
type: int |
| 194 |
choices: [0, 1, 2, 3] |
| 195 |
iolimit: |
| 196 |
description: |
| 197 |
- Section specifies the shares and limit for storage I/O resource. |
| 198 |
- Not applicable when O(disk[].type=vpmemdisk). |
| 199 |
suboptions: |
| 200 |
limit: |
| 201 |
description: Section specifies values for limit where the utilization of a virtual machine will not exceed, even if there are available resources. |
| 202 |
type: int |
| 203 |
shares: |
| 204 |
description: Specifies different types of shares user can add for the given disk. |
| 205 |
suboptions: |
| 206 |
level: |
| 207 |
description: Specifies different level for the shares section. |
| 208 |
type: str |
| 209 |
choices: ['low', 'normal', 'high', 'custom'] |
| 210 |
level_value: |
| 211 |
description: Custom value when O(disk[].iolimit.shares.level=custom). |
| 212 |
type: int |
| 213 |
type: dict |
| 214 |
type: dict |
| 215 |
shares: |
| 216 |
description: |
| 217 |
- Section for iolimit section tells about what are all different types of shares user can add for disk. |
| 218 |
- Not applicable when disk O(disk[].type=vpmemdisk). |
| 219 |
suboptions: |
| 220 |
level: |
| 221 |
description: Tells about different level for the shares section. |
| 222 |
type: str |
| 223 |
choices: ['low', 'normal', 'high', 'custom'] |
| 224 |
level_value: |
| 225 |
description: Custom value when O(disk[].shares.level=custom). |
| 226 |
type: int |
| 227 |
type: dict |
| 228 |
default: [] |
| 229 |
type: list |
| 230 |
elements: dict |
| 231 |
extends_documentation_fragment: |
| 232 |
- vmware.vmware.base_options |
| 233 |
''' |
| 234 |
|
| 235 |
EXAMPLES = r''' |
| 236 |
- name: Add disks to virtual machine using UUID |
| 237 |
community.vmware.vmware_guest_disk: |
| 238 |
hostname: "{{ vcenter_hostname }}" |
| 239 |
username: "{{ vcenter_username }}" |
| 240 |
password: "{{ vcenter_password }}" |
| 241 |
datacenter: "{{ datacenter_name }}" |
| 242 |
uuid: 421e4592-c069-924d-ce20-7e7533fab926 |
| 243 |
disk: |
| 244 |
- size_mb: 10 |
| 245 |
type: thin |
| 246 |
datastore: datacluster0 |
| 247 |
state: present |
| 248 |
scsi_controller: 1 |
| 249 |
unit_number: 1 |
| 250 |
scsi_type: 'paravirtual' |
| 251 |
disk_mode: 'persistent' |
| 252 |
- size_gb: 10 |
| 253 |
type: eagerzeroedthick |
| 254 |
state: present |
| 255 |
autoselect_datastore: true |
| 256 |
scsi_controller: 2 |
| 257 |
scsi_type: 'buslogic' |
| 258 |
unit_number: 12 |
| 259 |
disk_mode: 'independent_persistent' |
| 260 |
- size: 10Gb |
| 261 |
type: eagerzeroedthick |
| 262 |
state: present |
| 263 |
autoselect_datastore: true |
| 264 |
scsi_controller: 2 |
| 265 |
scsi_type: 'buslogic' |
| 266 |
unit_number: 1 |
| 267 |
disk_mode: 'independent_nonpersistent' |
| 268 |
- filename: "[datastore1] path/to/existing/disk.vmdk" |
| 269 |
delegate_to: localhost |
| 270 |
register: disk_facts |
| 271 |
|
| 272 |
- name: Add disks with specified shares to the virtual machine |
| 273 |
community.vmware.vmware_guest_disk: |
| 274 |
hostname: "{{ vcenter_hostname }}" |
| 275 |
username: "{{ vcenter_username }}" |
| 276 |
password: "{{ vcenter_password }}" |
| 277 |
datacenter: "{{ datacenter_name }}" |
| 278 |
disk: |
| 279 |
- size_gb: 1 |
| 280 |
type: thin |
| 281 |
datastore: datacluster0 |
| 282 |
state: present |
| 283 |
scsi_controller: 1 |
| 284 |
unit_number: 1 |
| 285 |
disk_mode: 'independent_persistent' |
| 286 |
shares: |
| 287 |
level: custom |
| 288 |
level_value: 1300 |
| 289 |
delegate_to: localhost |
| 290 |
register: test_custom_shares |
| 291 |
|
| 292 |
- name: Add physical raw device mapping to virtual machine using name |
| 293 |
community.vmware.vmware_guest_disk: |
| 294 |
hostname: "{{ vcenter_hostname }}" |
| 295 |
username: "{{ vcenter_username }}" |
| 296 |
password: "{{ vcenter_password }}" |
| 297 |
datacenter: "{{ datacenter_name }}" |
| 298 |
validate_certs: false |
| 299 |
name: "Test_VM" |
| 300 |
disk: |
| 301 |
- type: rdm |
| 302 |
state: present |
| 303 |
scsi_controller: 1 |
| 304 |
unit_number: 5 |
| 305 |
rdm_path: /vmfs/devices/disks/naa.060000003b1234efb453 |
| 306 |
compatibility_mode: 'physicalMode' |
| 307 |
|
| 308 |
- name: Add virtual raw device mapping to virtual machine using name and virtual mode |
| 309 |
community.vmware.vmware_guest_disk: |
| 310 |
hostname: "{{ vcenter_hostname }}" |
| 311 |
username: "{{ vcenter_username }}" |
| 312 |
password: "{{ vcenter_password }}" |
| 313 |
datacenter: "{{ datacenter_name }}" |
| 314 |
validate_certs: false |
| 315 |
name: "Test_VM" |
| 316 |
disk: |
| 317 |
- type: rdm |
| 318 |
state: present |
| 319 |
scsi_controller: 1 |
| 320 |
unit_number: 5 |
| 321 |
rdm_path: /vmfs/devices/disks/naa.060000003b1234efb453 |
| 322 |
compatibility_mode: 'virtualMode' |
| 323 |
disk_mode: 'persistent' |
| 324 |
|
| 325 |
- name: Add raw device mapping to virtual machine with Physical bus sharing |
| 326 |
community.vmware.vmware_guest_disk: |
| 327 |
hostname: "{{ vcenter_hostname }}" |
| 328 |
username: "{{ vcenter_username }}" |
| 329 |
password: "{{ vcenter_password }}" |
| 330 |
datacenter: "{{ datacenter_name }}" |
| 331 |
validate_certs: false |
| 332 |
name: "Test_VM" |
| 333 |
disk: |
| 334 |
- type: rdm |
| 335 |
state: present |
| 336 |
scsi_controller: 1 |
| 337 |
unit_number: 5 |
| 338 |
rdm_path: /vmfs/devices/disks/naa.060000003b1234efb453 |
| 339 |
compatibility_mode: 'virtualMode' |
| 340 |
disk_mode: 'persistent' |
| 341 |
bus_sharing: physicalSharing |
| 342 |
|
| 343 |
- name: Add raw device mapping to virtual machine with Physical bus sharing and clustered disk |
| 344 |
community.vmware.vmware_guest_disk: |
| 345 |
hostname: "{{ vcenter_hostname }}" |
| 346 |
username: "{{ vcenter_username }}" |
| 347 |
password: "{{ vcenter_password }}" |
| 348 |
datacenter: "{{ datacenter_name }}" |
| 349 |
validate_certs: false |
| 350 |
name: "Test_VM" |
| 351 |
disk: |
| 352 |
- type: rdm |
| 353 |
state: present |
| 354 |
scsi_controller: 1 |
| 355 |
unit_number: 5 |
| 356 |
compatibility_mode: 'virtualMode' |
| 357 |
disk_mode: 'persistent' |
| 358 |
bus_sharing: physicalSharing |
| 359 |
filename: "[datastore1] path/to/rdm/disk-marker.vmdk" |
| 360 |
|
| 361 |
- name: create new disk with custom IO limits and shares in IO Limits |
| 362 |
community.vmware.vmware_guest_disk: |
| 363 |
hostname: "{{ vcenter_hostname }}" |
| 364 |
username: "{{ vcenter_username }}" |
| 365 |
password: "{{ vcenter_password }}" |
| 366 |
datacenter: "{{ datacenter_name }}" |
| 367 |
disk: |
| 368 |
- size_gb: 1 |
| 369 |
type: thin |
| 370 |
datastore: datacluster0 |
| 371 |
state: present |
| 372 |
scsi_controller: 1 |
| 373 |
unit_number: 1 |
| 374 |
disk_mode: 'independent_persistent' |
| 375 |
iolimit: |
| 376 |
limit: 1506 |
| 377 |
shares: |
| 378 |
level: custom |
| 379 |
level_value: 1305 |
| 380 |
delegate_to: localhost |
| 381 |
register: test_custom_IoLimit_shares |
| 382 |
|
| 383 |
- name: Remove disks from virtual machine using name |
| 384 |
community.vmware.vmware_guest_disk: |
| 385 |
hostname: "{{ vcenter_hostname }}" |
| 386 |
username: "{{ vcenter_username }}" |
| 387 |
password: "{{ vcenter_password }}" |
| 388 |
datacenter: "{{ datacenter_name }}" |
| 389 |
name: VM_225 |
| 390 |
disk: |
| 391 |
- state: absent |
| 392 |
scsi_controller: 1 |
| 393 |
unit_number: 1 |
| 394 |
delegate_to: localhost |
| 395 |
register: disk_facts |
| 396 |
|
| 397 |
- name: Remove disk from virtual machine using moid |
| 398 |
community.vmware.vmware_guest_disk: |
| 399 |
hostname: "{{ vcenter_hostname }}" |
| 400 |
username: "{{ vcenter_username }}" |
| 401 |
password: "{{ vcenter_password }}" |
| 402 |
datacenter: "{{ datacenter_name }}" |
| 403 |
moid: vm-42 |
| 404 |
disk: |
| 405 |
- state: absent |
| 406 |
scsi_controller: 1 |
| 407 |
unit_number: 1 |
| 408 |
delegate_to: localhost |
| 409 |
register: disk_facts |
| 410 |
|
| 411 |
- name: Remove disk from virtual machine but keep the VMDK file on the datastore |
| 412 |
community.vmware.vmware_guest_disk: |
| 413 |
hostname: "{{ vcenter_hostname }}" |
| 414 |
username: "{{ vcenter_username }}" |
| 415 |
password: "{{ vcenter_password }}" |
| 416 |
datacenter: "{{ datacenter_name }}" |
| 417 |
name: VM_225 |
| 418 |
disk: |
| 419 |
- state: absent |
| 420 |
scsi_controller: 1 |
| 421 |
unit_number: 2 |
| 422 |
destroy: false |
| 423 |
delegate_to: localhost |
| 424 |
register: disk_facts |
| 425 |
|
| 426 |
- name: Add disks to virtual machine using UUID to SATA and NVMe controller |
| 427 |
community.vmware.vmware_guest_disk: |
| 428 |
hostname: "{{ vcenter_hostname }}" |
| 429 |
username: "{{ vcenter_username }}" |
| 430 |
password: "{{ vcenter_password }}" |
| 431 |
datacenter: "{{ datacenter_name }}" |
| 432 |
validate_certs: false |
| 433 |
uuid: 421e4592-c069-924d-ce20-7e7533fab926 |
| 434 |
disk: |
| 435 |
- size_mb: 256 |
| 436 |
type: thin |
| 437 |
datastore: datacluster0 |
| 438 |
state: present |
| 439 |
controller_type: sata |
| 440 |
controller_number: 1 |
| 441 |
unit_number: 1 |
| 442 |
disk_mode: 'persistent' |
| 443 |
- size_gb: 1 |
| 444 |
state: present |
| 445 |
autoselect_datastore: true |
| 446 |
controller_type: nvme |
| 447 |
controller_number: 2 |
| 448 |
unit_number: 3 |
| 449 |
disk_mode: 'independent_persistent' |
| 450 |
delegate_to: localhost |
| 451 |
register: disk_facts |
| 452 |
|
| 453 |
- name: Add a new vPMem disk to virtual machine to SATA controller |
| 454 |
community.vmware.vmware_guest_disk: |
| 455 |
hostname: "{{ vcenter_hostname }}" |
| 456 |
username: "{{ vcenter_username }}" |
| 457 |
password: "{{ vcenter_password }}" |
| 458 |
datacenter: "{{ datacenter_name }}" |
| 459 |
validate_certs: false |
| 460 |
name: VM_226 |
| 461 |
disk: |
| 462 |
- type: vpmemdisk |
| 463 |
size_gb: 1 |
| 464 |
state: present |
| 465 |
controller_type: sata |
| 466 |
controller_number: 1 |
| 467 |
unit_number: 2 |
| 468 |
delegate_to: localhost |
| 469 |
register: disk_facts |
| 470 |
''' |
| 471 |
|
| 472 |
RETURN = r''' |
| 473 |
disk_data: |
| 474 |
description: metadata about the virtual machine's disks after managing them |
| 475 |
returned: always |
| 476 |
type: dict |
| 477 |
sample: { |
| 478 |
"0": { |
| 479 |
"backing_datastore": "datastore2", |
| 480 |
"backing_disk_mode": "persistent", |
| 481 |
"backing_eagerlyscrub": false, |
| 482 |
"backing_filename": "[datastore2] VM_225/VM_225.vmdk", |
| 483 |
"backing_thinprovisioned": false, |
| 484 |
"backing_writethrough": false, |
| 485 |
"backing_uuid": "421e4592-c069-924d-ce20-7e7533fab926", |
| 486 |
"capacity_in_bytes": 10485760, |
| 487 |
"capacity_in_kb": 10240, |
| 488 |
"controller_key": 1000, |
| 489 |
"key": 2000, |
| 490 |
"label": "Hard disk 1", |
| 491 |
"summary": "10,240 KB", |
| 492 |
"unit_number": 0 |
| 493 |
}, |
| 494 |
} |
| 495 |
disk_changes: |
| 496 |
description: result of each task, key is the 0-based index with the same sequence in which the tasks were defined |
| 497 |
returned: always |
| 498 |
type: dict |
| 499 |
sample: { |
| 500 |
"0": "Disk deleted.", |
| 501 |
"1": "Disk created." |
| 502 |
} |
| 503 |
''' |
| 504 |
|
| 505 |
import re |
| 506 |
try: |
| 507 |
from pyVmomi import vim |
| 508 |
except ImportError: |
| 509 |
pass |
| 510 |
|
| 511 |
from random import randint |
| 512 |
from ansible.module_utils.basic import AnsibleModule |
| 513 |
from ansible.module_utils.common.text.converters import to_native |
| 514 |
from ansible_collections.community.vmware.plugins.module_utils.vmware import PyVmomi, \ |
| 515 |
wait_for_task, find_obj, get_all_objs, get_parent_datacenter |
| 516 |
from ansible_collections.vmware.vmware.plugins.module_utils.argument_spec import base_argument_spec |
| 517 |
from ansible_collections.community.vmware.plugins.module_utils.vm_device_helper import PyVmomiDeviceHelper |
| 518 |
|
| 519 |
|
| 520 |
class PyVmomiHelper(PyVmomi): |
| 521 |
def __init__(self, module): |
| 522 |
super(PyVmomiHelper, self).__init__(module) |
| 523 |
self.device_helper = PyVmomiDeviceHelper(self.module) |
| 524 |
self.desired_disks = self.params['disk'] # Match with vmware_guest parameter |
| 525 |
self.vm = None |
| 526 |
self.config_spec = vim.vm.ConfigSpec() |
| 527 |
self.config_spec.deviceChange = [] |
| 528 |
|
| 529 |
def find_disk_by_key(self, disk_key, disk_unit_number): |
| 530 |
found_disk = None |
| 531 |
for device in self.vm.config.hardware.device: |
| 532 |
if isinstance(device, vim.vm.device.VirtualDisk) and device.key == disk_key: |
| 533 |
if device.unitNumber == disk_unit_number: |
| 534 |
found_disk = device |
| 535 |
break |
| 536 |
|
| 537 |
return found_disk |
| 538 |
|
| 539 |
@staticmethod |
| 540 |
def create_disk(ctl_key, disk): |
| 541 |
""" |
| 542 |
Create Virtual Device Spec for virtual disk |
| 543 |
Args: |
| 544 |
ctl_key: Unique SCSI Controller Key |
| 545 |
disk: The disk configurations dict |
| 546 |
|
| 547 |
Returns: Virtual Device Spec for virtual disk |
| 548 |
|
| 549 |
""" |
| 550 |
disk_spec = vim.vm.device.VirtualDeviceSpec() |
| 551 |
disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.add |
| 552 |
disk_spec.device = vim.vm.device.VirtualDisk() |
| 553 |
disk_spec.device.key = -randint(20000, 24999) |
| 554 |
|
| 555 |
# Check if RDM first as changing backing later on will erase some settings like disk_mode |
| 556 |
if disk['disk_type'] == 'rdm': |
| 557 |
disk_spec.device.backing = vim.vm.device.VirtualDisk.RawDiskMappingVer1BackingInfo() |
| 558 |
disk_spec.device.backing.deviceName = disk['rdm_path'] |
| 559 |
disk_spec.device.backing.compatibilityMode = disk['compatibility_mode'] |
| 560 |
elif disk['disk_type'] == 'vpmemdisk': |
| 561 |
disk_spec.device.backing = vim.vm.device.VirtualDisk.LocalPMemBackingInfo() |
| 562 |
else: |
| 563 |
disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() |
| 564 |
|
| 565 |
if disk['disk_type'] != 'vpmemdisk': |
| 566 |
disk_spec.device.backing.diskMode = disk['disk_mode'] |
| 567 |
disk_spec.device.backing.sharing = disk['sharing'] |
| 568 |
|
| 569 |
if disk['disk_type'] == 'thin': |
| 570 |
disk_spec.device.backing.thinProvisioned = True |
| 571 |
elif disk['disk_type'] == 'eagerzeroedthick': |
| 572 |
disk_spec.device.backing.eagerlyScrub = True |
| 573 |
|
| 574 |
disk_spec.device.controllerKey = ctl_key |
| 575 |
disk_spec.device.unitNumber = disk['disk_unit_number'] |
| 576 |
|
| 577 |
return disk_spec |
| 578 |
|
| 579 |
def reconfigure_vm(self, config_spec, device_type): |
| 580 |
""" |
| 581 |
Reconfigure virtual machine after modifying device spec |
| 582 |
Args: |
| 583 |
config_spec: Config Spec |
| 584 |
device_type: Type of device being modified |
| 585 |
|
| 586 |
Returns: Boolean status 'changed' and actual task result |
| 587 |
|
| 588 |
""" |
| 589 |
changed, results = (False, '') |
| 590 |
try: |
| 591 |
# Perform actual VM reconfiguration |
| 592 |
task = self.vm.ReconfigVM_Task(spec=config_spec) |
| 593 |
changed, results = wait_for_task(task) |
| 594 |
except vim.fault.InvalidDeviceSpec as invalid_device_spec: |
| 595 |
self.module.fail_json(msg="Failed to manage '%s' on given virtual machine due to invalid" |
| 596 |
" device spec : %s" % (device_type, to_native(invalid_device_spec.msg)), |
| 597 |
details="Please check ESXi server logs for more details.") |
| 598 |
except vim.fault.RestrictedVersion as e: |
| 599 |
self.module.fail_json(msg="Failed to reconfigure virtual machine due to" |
| 600 |
" product versioning restrictions: %s" % to_native(e.msg)) |
| 601 |
|
| 602 |
return changed, results |
| 603 |
|
| 604 |
def get_ioandshares_diskconfig(self, disk_spec, disk): |
| 605 |
io_disk_spec = vim.StorageResourceManager.IOAllocationInfo() |
| 606 |
if 'iolimit' in disk: |
| 607 |
io_disk_spec.limit = disk['iolimit']['limit'] |
| 608 |
if 'shares' in disk['iolimit']: |
| 609 |
shares_spec = vim.SharesInfo() |
| 610 |
shares_spec.level = disk['iolimit']['shares']['level'] |
| 611 |
if shares_spec.level == 'custom': |
| 612 |
shares_spec.shares = disk['iolimit']['shares']['level_value'] |
| 613 |
io_disk_spec.shares = shares_spec |
| 614 |
disk_spec.device.storageIOAllocation = io_disk_spec |
| 615 |
if 'shares' in disk: |
| 616 |
shares_spec = vim.SharesInfo() |
| 617 |
shares_spec.level = disk['shares']['level'] |
| 618 |
if shares_spec.level == 'custom': |
| 619 |
shares_spec.shares = disk['shares']['level_value'] |
| 620 |
io_disk_spec.shares = shares_spec |
| 621 |
disk_spec.device.storageIOAllocation = io_disk_spec |
| 622 |
return disk_spec |
| 623 |
|
| 624 |
def get_sharing(self, disk, disk_type, disk_index): |
| 625 |
""" |
| 626 |
Get the sharing mode of the virtual disk |
| 627 |
Args: |
| 628 |
disk: Virtual disk data object |
| 629 |
disk_type: Disk type of the virtual disk |
| 630 |
disk_index: Disk unit number at which disk needs to be attached |
| 631 |
|
| 632 |
Returns: |
| 633 |
sharing_mode: The sharing mode of the virtual disk |
| 634 |
|
| 635 |
""" |
| 636 |
sharing = disk.get('sharing') |
| 637 |
if sharing and disk_type != 'eagerzeroedthick' and disk_type != 'rdm': |
| 638 |
self.module.fail_json(msg="Invalid 'sharing' mode specified for disk index [%s]. 'disk_mode'" |
| 639 |
" must be 'eagerzeroedthick' or 'rdm' when 'sharing'." % disk_index) |
| 640 |
if sharing: |
| 641 |
sharing_mode = 'sharingMultiWriter' |
| 642 |
else: |
| 643 |
sharing_mode = 'sharingNone' |
| 644 |
return sharing_mode |
| 645 |
|
| 646 |
def ensure_disks(self, vm_obj=None): |
| 647 |
""" |
| 648 |
Manage internal state of virtual machine disks |
| 649 |
Args: |
| 650 |
vm_obj: Managed object of virtual machine |
| 651 |
|
| 652 |
""" |
| 653 |
# Set vm object |
| 654 |
self.vm = vm_obj |
| 655 |
vm_files_datastore = self.vm.config.files.vmPathName.split(' ')[0].strip('[]') |
| 656 |
# Sanitize user input |
| 657 |
disk_data = self.sanitize_disk_inputs() |
| 658 |
ctl_changed = False |
| 659 |
disk_change_list = list() |
| 660 |
results = dict(changed=False, disk_data=None, disk_changes=dict()) |
| 661 |
new_added_disk_ctl = list() |
| 662 |
sharesval = {'low': 500, 'normal': 1000, 'high': 2000} |
| 663 |
|
| 664 |
# Deal with controller |
| 665 |
for disk in disk_data: |
| 666 |
ctl_found = False |
| 667 |
# check if disk controller is in the new adding queue |
| 668 |
for new_ctl in new_added_disk_ctl: |
| 669 |
if new_ctl['controller_type'] == disk['controller_type'] and new_ctl['controller_number'] == disk['controller_number']: |
| 670 |
ctl_found = True |
| 671 |
break |
| 672 |
# check if disk controller already exists |
| 673 |
if not ctl_found: |
| 674 |
for device in self.vm.config.hardware.device: |
| 675 |
if isinstance(device, self.device_helper.disk_ctl_device_type[disk['controller_type']]): |
| 676 |
if device.busNumber == disk['controller_number']: |
| 677 |
ctl_found = True |
| 678 |
break |
| 679 |
# create disk controller when not found and disk state is present |
| 680 |
if not ctl_found and disk['state'] == 'present': |
| 681 |
# Create new controller |
| 682 |
if disk['controller_type'] in self.device_helper.scsi_device_type.keys(): |
| 683 |
ctl_spec = self.device_helper.create_scsi_controller(disk['controller_type'], disk['controller_number'], disk['bus_sharing']) |
| 684 |
elif disk['controller_type'] == 'sata': |
| 685 |
ctl_spec = self.device_helper.create_sata_controller(disk['controller_number']) |
| 686 |
elif disk['controller_type'] == 'nvme': |
| 687 |
ctl_spec = self.device_helper.create_nvme_controller(disk['controller_number']) |
| 688 |
new_added_disk_ctl.append({'controller_type': disk['controller_type'], 'controller_number': disk['controller_number']}) |
| 689 |
ctl_changed = True |
| 690 |
self.config_spec.deviceChange.append(ctl_spec) |
| 691 |
elif not ctl_found and disk['state'] == 'absent': |
| 692 |
self.module.fail_json(msg="Not found 'controller_type': '%s', 'controller_number': '%s', so can not" |
| 693 |
" remove this disk, please make sure 'controller_type' and" |
| 694 |
" 'controller_number' are correct." % (disk['controller_type'], disk['controller_number'])) |
| 695 |
if ctl_changed: |
| 696 |
self.reconfigure_vm(self.config_spec, 'Disk Controller') |
| 697 |
self.config_spec = vim.vm.ConfigSpec() |
| 698 |
self.config_spec.deviceChange = [] |
| 699 |
|
| 700 |
# Deal with Disks |
| 701 |
for disk in disk_data: |
| 702 |
disk_found = False |
| 703 |
update_io = False |
| 704 |
disk_change = False |
| 705 |
ctl_found = False |
| 706 |
for device in self.vm.config.hardware.device: |
| 707 |
if isinstance(device, self.device_helper.disk_ctl_device_type[disk['controller_type']]) and device.busNumber == disk['controller_number']: |
| 708 |
for disk_key in device.device: |
| 709 |
disk_device = self.find_disk_by_key(disk_key, disk['disk_unit_number']) |
| 710 |
if disk_device is not None: |
| 711 |
disk_found = True |
| 712 |
if disk['state'] == 'present': |
| 713 |
disk_spec = vim.vm.device.VirtualDeviceSpec() |
| 714 |
disk_spec.device = disk_device |
| 715 |
# Deal with iolimit. Note that if iolimit is set, you HAVE TO both set limit and shares, |
| 716 |
# or ansible will break with "'NoneType' object is not subscriptable" |
| 717 |
if 'iolimit' in disk: |
| 718 |
if disk['iolimit']['limit'] != disk_spec.device.storageIOAllocation.limit: |
| 719 |
update_io = True |
| 720 |
|
| 721 |
if 'shares' in disk['iolimit']: |
| 722 |
# 'low', 'normal' and 'high' values in disk['iolimit']['shares']['level'] are converted to int values on vcenter side |
| 723 |
if (disk['iolimit']['shares']['level'] != 'custom' |
| 724 |
and sharesval.get(disk['iolimit']['shares']['level'], 0) != disk_spec.device.storageIOAllocation.shares.shares) or \ |
| 725 |
(disk['iolimit']['shares']['level'] == 'custom' |
| 726 |
and disk['iolimit']['shares']['level_value'] != disk_spec.device.storageIOAllocation.shares.shares): |
| 727 |
update_io = True |
| 728 |
|
| 729 |
if update_io: |
| 730 |
# set the operation to edit so that it knows to keep other settings |
| 731 |
disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit |
| 732 |
disk_spec = self.get_ioandshares_diskconfig(disk_spec, disk) |
| 733 |
disk_change = True |
| 734 |
|
| 735 |
# If this is an RDM ignore disk size |
| 736 |
if disk['disk_type'] != 'rdm': |
| 737 |
if disk['size'] < disk_spec.device.capacityInKB: |
| 738 |
self.module.fail_json(msg="Given disk size at disk index [%s] is smaller than found" |
| 739 |
" (%d < %d). Reducing disks is not allowed." |
| 740 |
% (disk['disk_index'], disk['size'], |
| 741 |
disk_spec.device.capacityInKB)) |
| 742 |
if disk['size'] != disk_spec.device.capacityInKB: |
| 743 |
# set the operation to edit so that it knows to keep other settings |
| 744 |
disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.edit |
| 745 |
if disk['disk_type'] != 'vpmemdisk': |
| 746 |
disk_spec = self.get_ioandshares_diskconfig(disk_spec, disk) |
| 747 |
disk_spec.device.capacityInKB = disk['size'] |
| 748 |
disk_change = True |
| 749 |
|
| 750 |
if disk_change: |
| 751 |
self.config_spec.deviceChange.append(disk_spec) |
| 752 |
disk_change_list.append(disk_change) |
| 753 |
results['disk_changes'][str(disk['disk_index'])] = "Disk reconfigured." |
| 754 |
|
| 755 |
elif disk['state'] == 'absent': |
| 756 |
# Disk already exists, deleting |
| 757 |
disk_spec = vim.vm.device.VirtualDeviceSpec() |
| 758 |
disk_spec.operation = vim.vm.device.VirtualDeviceSpec.Operation.remove |
| 759 |
if disk['destroy'] is True: |
| 760 |
disk_spec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.destroy |
| 761 |
disk_spec.device = disk_device |
| 762 |
self.config_spec.deviceChange.append(disk_spec) |
| 763 |
disk_change = True |
| 764 |
disk_change_list.append(disk_change) |
| 765 |
results['disk_changes'][str(disk['disk_index'])] = "Disk deleted." |
| 766 |
break |
| 767 |
|
| 768 |
if disk_found: |
| 769 |
break |
| 770 |
if not disk_found and disk['state'] == 'present': |
| 771 |
# Add new disk |
| 772 |
disk_spec = self.create_disk(device.key, disk) |
| 773 |
# get Storage DRS recommended datastore from the datastore cluster |
| 774 |
if disk['disk_type'] == 'rdm': |
| 775 |
# Since RDMs can be shared between two machines cluster_disk with rdm will |
| 776 |
# invoke a copy of the existing disk instead of trying to create a new one which causes |
| 777 |
# file lock issues in VSphere. This ensures we dont add a "create" operation. |
| 778 |
if disk['filename'] is not None and disk['cluster_disk'] is True: |
| 779 |
disk_spec.device.backing.fileName = disk['filename'] |
| 780 |
else: |
| 781 |
disk_spec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create |
| 782 |
else: |
| 783 |
if disk['filename'] is None: |
| 784 |
if disk['datastore_cluster'] is not None: |
| 785 |
datastore_name = self.get_recommended_datastore(datastore_cluster_obj=disk['datastore_cluster'], disk_spec_obj=disk_spec) |
| 786 |
disk['datastore'] = find_obj(self.content, [vim.Datastore], datastore_name) |
| 787 |
|
| 788 |
disk_spec.fileOperation = vim.vm.device.VirtualDeviceSpec.FileOperation.create |
| 789 |
disk_spec.device.capacityInKB = disk['size'] |
| 790 |
# Set backing filename when datastore is configured and not the same as VM datastore |
| 791 |
# If datastore is not configured or backing filename is not set, default is VM datastore |
| 792 |
if disk['datastore'] is not None and disk['datastore'].name != vm_files_datastore: |
| 793 |
disk_spec.device.backing.datastore = disk['datastore'] |
| 794 |
disk_spec.device.backing.fileName = "[%s] %s/%s_%s_%s_%s.vmdk" % (disk['datastore'].name, |
| 795 |
self.vm.name, |
| 796 |
self.vm.name, |
| 797 |
device.key, |
| 798 |
str(disk['disk_unit_number']), |
| 799 |
str(randint(1, 10000))) |
| 800 |
elif disk['filename'] is not None: |
| 801 |
disk_spec.device.backing.fileName = disk['filename'] |
| 802 |
disk_spec = self.get_ioandshares_diskconfig(disk_spec, disk) |
| 803 |
|
| 804 |
self.config_spec.deviceChange.append(disk_spec) |
| 805 |
disk_change = True |
| 806 |
disk_change_list.append(disk_change) |
| 807 |
results['disk_changes'][str(disk['disk_index'])] = "Disk created." |
| 808 |
break |
| 809 |
if disk_change: |
| 810 |
# Adding multiple disks in a single attempt raises weird errors |
| 811 |
# So adding single disk at a time. |
| 812 |
self.reconfigure_vm(self.config_spec, 'disks') |
| 813 |
self.config_spec = vim.vm.ConfigSpec() |
| 814 |
self.config_spec.deviceChange = [] |
| 815 |
if any(disk_change_list): |
| 816 |
results['changed'] = True |
| 817 |
results['disk_data'] = self.device_helper.gather_disk_info(self.vm) |
| 818 |
self.module.exit_json(**results) |
| 819 |
|
| 820 |
def sanitize_disk_inputs(self): |
| 821 |
""" |
| 822 |
Check correctness of disk input provided by user |
| 823 |
|
| 824 |
Returns: A list of dictionary containing disk information |
| 825 |
|
| 826 |
""" |
| 827 |
disks_data = list() |
| 828 |
if not self.desired_disks: |
| 829 |
self.module.exit_json(changed=False, msg="No disks provided for virtual machine '%s' for management." |
| 830 |
% self.vm.name) |
| 831 |
|
| 832 |
for disk_index, disk in enumerate(self.desired_disks): |
| 833 |
# Initialize default value for disk |
| 834 |
current_disk = dict(disk_index=disk_index, |
| 835 |
state='present', |
| 836 |
destroy=True, |
| 837 |
filename=None, |
| 838 |
datastore_cluster=None, |
| 839 |
datastore=None, |
| 840 |
autoselect_datastore=True, |
| 841 |
disk_unit_number=0, |
| 842 |
controller_number=0, |
| 843 |
disk_mode='persistent', |
| 844 |
disk_type='thick', |
| 845 |
sharing=False, |
| 846 |
bus_sharing='noSharing', |
| 847 |
cluster_disk=False) |
| 848 |
# Type of Disk |
| 849 |
if disk['type'] is not None: |
| 850 |
current_disk['disk_type'] = disk['type'] |
| 851 |
if current_disk['disk_type'] == 'vpmemdisk': |
| 852 |
if self.vm.runtime.powerState != vim.VirtualMachinePowerState.poweredOff: |
| 853 |
self.module.fail_json(msg="Please make sure VM is in powered off state before doing vPMem disk" |
| 854 |
" reconfiguration.") |
| 855 |
disk['datastore'] = None |
| 856 |
disk['autoselect_datastore'] = None |
| 857 |
disk['filename'] = None |
| 858 |
disk['disk_mode'] = None |
| 859 |
|
| 860 |
# Check state |
| 861 |
if disk['state'] is not None: |
| 862 |
current_disk['state'] = disk['state'] |
| 863 |
|
| 864 |
# Check controller type |
| 865 |
if disk['scsi_type'] is not None and disk['controller_type'] is None: |
| 866 |
current_disk['controller_type'] = disk['scsi_type'] |
| 867 |
elif disk['scsi_type'] is None and disk['controller_type'] is None: |
| 868 |
current_disk['controller_type'] = 'paravirtual' |
| 869 |
elif disk['controller_type'] is not None and disk['scsi_type'] is None: |
| 870 |
current_disk['controller_type'] = disk['controller_type'] |
| 871 |
else: |
| 872 |
self.module.fail_json(msg="Please specify either 'scsi_type' or 'controller_type' for disk index [%s]." |
| 873 |
% disk_index) |
| 874 |
if current_disk['controller_type'] == 'ide': |
| 875 |
if self.vm.runtime.powerState != vim.VirtualMachinePowerState.poweredOff: |
| 876 |
self.module.fail_json(msg="Please make sure VM is in powered off state before doing IDE disk" |
| 877 |
" reconfiguration.") |
| 878 |
|
| 879 |
# Check controller bus number |
| 880 |
if disk['scsi_controller'] is not None and disk['controller_number'] is None and disk['controller_type'] is None: |
| 881 |
temp_disk_controller = disk['scsi_controller'] |
| 882 |
elif disk['controller_number'] is not None and disk['scsi_controller'] is None and disk['scsi_type'] is None: |
| 883 |
temp_disk_controller = disk['controller_number'] |
| 884 |
else: |
| 885 |
self.module.fail_json(msg="Please specify 'scsi_controller' with 'scsi_type', or 'controller_number'" |
| 886 |
" with 'controller_type' under disk parameter for disk index [%s], which is" |
| 887 |
" required while creating or configuring disk." % disk_index) |
| 888 |
try: |
| 889 |
disk_controller = int(temp_disk_controller) |
| 890 |
except ValueError: |
| 891 |
self.module.fail_json(msg="Invalid controller bus number '%s' specified" |
| 892 |
" for disk index [%s]" % (temp_disk_controller, disk_index)) |
| 893 |
if current_disk['controller_type'] == 'ide' and disk_controller not in [0, 1]: |
| 894 |
self.module.fail_json(msg="Invalid controller bus number '%s' specified" |
| 895 |
" for disk index [%s], valid value is 0 or 1" % (disk_controller, disk_index)) |
| 896 |
|
| 897 |
current_disk['controller_number'] = disk_controller |
| 898 |
|
| 899 |
try: |
| 900 |
temp_disk_unit_number = int(disk['unit_number']) |
| 901 |
except ValueError: |
| 902 |
self.module.fail_json(msg="Invalid Disk unit number ID '%s' specified at index [%s]." |
| 903 |
% (disk['unit_number'], disk_index)) |
| 904 |
if current_disk['controller_type'] in self.device_helper.scsi_device_type.keys(): |
| 905 |
# the Paravirtual SCSI Controller Supports up to 64 disks in vSphere 6.7. Using hardware |
| 906 |
# version 14 or higher from the vm config should catch this appropriately. |
| 907 |
hw_version = int(self.vm.config.version.split('-')[1]) |
| 908 |
if current_disk['controller_type'] == 'paravirtual' and hw_version >= 14: |
| 909 |
if temp_disk_unit_number not in range(0, 64): |
| 910 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for disk [%s] at index [%s]," |
| 911 |
" please specify value between 0 to 64 only (excluding 7)." |
| 912 |
% (temp_disk_unit_number, disk_index)) |
| 913 |
if temp_disk_unit_number == 7: |
| 914 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for disk at index [%s], please" |
| 915 |
" specify value other than 7 as it is reserved for SCSI Controller." |
| 916 |
% disk_index) |
| 917 |
|
| 918 |
else: |
| 919 |
if temp_disk_unit_number not in range(0, 16): |
| 920 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for disk [%s] at index [%s]," |
| 921 |
" please specify value between 0 to 15 only (excluding 7)." |
| 922 |
% (temp_disk_unit_number, disk_index)) |
| 923 |
if temp_disk_unit_number == 7: |
| 924 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for disk at index [%s], please" |
| 925 |
" specify value other than 7 as it is reserved for SCSI Controller." |
| 926 |
% disk_index) |
| 927 |
elif current_disk['controller_type'] == 'sata' and temp_disk_unit_number not in range(0, 30): |
| 928 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for SATA disk [%s] at index [%s]," |
| 929 |
" please specify value between 0 to 29" % (temp_disk_unit_number, disk_index)) |
| 930 |
elif current_disk['controller_type'] == 'nvme' and temp_disk_unit_number not in range(0, 15): |
| 931 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for NVMe disk [%s] at index [%s]," |
| 932 |
" please specify value between 0 to 14" % (temp_disk_unit_number, disk_index)) |
| 933 |
elif current_disk['controller_type'] == 'ide' and temp_disk_unit_number not in [0, 1]: |
| 934 |
self.module.fail_json(msg="Invalid Disk unit number ID specified for IDE disk [%s] at index [%s]," |
| 935 |
" please specify value 0 or 1" % (temp_disk_unit_number, disk_index)) |
| 936 |
current_disk['disk_unit_number'] = temp_disk_unit_number |
| 937 |
|
| 938 |
# By default destroy file from datastore if 'destroy' parameter is not provided |
| 939 |
if current_disk['state'] == 'absent': |
| 940 |
current_disk['destroy'] = disk.get('destroy', True) |
| 941 |
elif current_disk['state'] == 'present': |
| 942 |
# Select datastore or datastore cluster |
| 943 |
if disk['datastore'] is not None: |
| 944 |
if disk['autoselect_datastore'] is not None: |
| 945 |
self.module.fail_json(msg="Please specify either 'datastore' or 'autoselect_datastore' for" |
| 946 |
" disk index [%s]" % disk_index) |
| 947 |
# Check if given value is datastore or datastore cluster |
| 948 |
datastore_name = disk['datastore'] |
| 949 |
datastore_cluster = find_obj(self.content, [vim.StoragePod], datastore_name) |
| 950 |
datastore = find_obj(self.content, [vim.Datastore], datastore_name) |
| 951 |
if datastore is None and datastore_cluster is None: |
| 952 |
self.module.fail_json(msg="Failed to find datastore or datastore cluster named '%s' " |
| 953 |
"in given configuration." % disk['datastore']) |
| 954 |
if datastore_cluster: |
| 955 |
# If user specified datastore cluster, keep track of that for determining datastore later |
| 956 |
current_disk['datastore_cluster'] = datastore_cluster |
| 957 |
elif datastore: |
| 958 |
ds_datacenter = get_parent_datacenter(datastore) |
| 959 |
if ds_datacenter.name != self.module.params['datacenter']: |
| 960 |
self.module.fail_json(msg="Get datastore '%s' in datacenter '%s', not the configured" |
| 961 |
" datacenter '%s'" % (datastore.name, ds_datacenter.name, |
| 962 |
self.module.params['datacenter'])) |
| 963 |
current_disk['datastore'] = datastore |
| 964 |
current_disk['autoselect_datastore'] = False |
| 965 |
elif disk['autoselect_datastore'] is not None: |
| 966 |
# Find datastore which fits requirement |
| 967 |
datastores = get_all_objs(self.content, [vim.Datastore]) |
| 968 |
if not datastores: |
| 969 |
self.module.fail_json(msg="Failed to gather information about available datastores in given" |
| 970 |
" datacenter '%s'." % self.module.params['datacenter']) |
| 971 |
datastore = None |
| 972 |
datastore_freespace = 0 |
| 973 |
for ds in datastores: |
| 974 |
if ds.summary.freeSpace > datastore_freespace: |
| 975 |
# If datastore field is provided, filter destination datastores |
| 976 |
datastore = ds |
| 977 |
datastore_freespace = ds.summary.freeSpace |
| 978 |
current_disk['datastore'] = datastore |
| 979 |
else: |
| 980 |
if current_disk['disk_type'] == 'vpmemdisk': |
| 981 |
current_disk['datastore'] = None |
| 982 |
current_disk['autoselect_datastore'] = False |
| 983 |
|
| 984 |
if disk['filename'] is not None: |
| 985 |
current_disk['filename'] = disk['filename'] |
| 986 |
|
| 987 |
if [x for x in disk.keys() if ((x.startswith('size_') or x == 'size') and disk[x] is not None)]: |
| 988 |
# size, size_tb, size_gb, size_mb, size_kb |
| 989 |
disk_size_parse_failed = False |
| 990 |
if disk['size'] is not None: |
| 991 |
size_regex = re.compile(r'(\d+(?:\.\d+)?)([tgmkTGMK][bB])') |
| 992 |
disk_size_m = size_regex.match(disk['size']) |
| 993 |
if disk_size_m: |
| 994 |
expected = disk_size_m.group(1) |
| 995 |
unit = disk_size_m.group(2) |
| 996 |
else: |
| 997 |
disk_size_parse_failed = True |
| 998 |
try: |
| 999 |
if re.match(r'\d+\.\d+', expected): |
| 1000 |
# We found float value in string, let's typecast it |
| 1001 |
expected = float(expected) |
| 1002 |
else: |
| 1003 |
# We found int value in string, let's typecast it |
| 1004 |
expected = int(expected) |
| 1005 |
except (TypeError, ValueError, NameError): |
| 1006 |
disk_size_parse_failed = True |
| 1007 |
else: |
| 1008 |
# Even multiple size_ parameter provided by user, |
| 1009 |
# consider first value only |
| 1010 |
param = [x for x in disk.keys() if (x.startswith('size_') and disk[x] is not None)][0] |
| 1011 |
unit = param.split('_')[-1] |
| 1012 |
disk_size = disk[param] |
| 1013 |
if isinstance(disk_size, (float, int)): |
| 1014 |
disk_size = str(disk_size) |
| 1015 |
|
| 1016 |
try: |
| 1017 |
if re.match(r'\d+\.\d+', disk_size): |
| 1018 |
# We found float value in string, let's typecast it |
| 1019 |
expected = float(disk_size) |
| 1020 |
else: |
| 1021 |
# We found int value in string, let's typecast it |
| 1022 |
expected = int(disk_size) |
| 1023 |
except (TypeError, ValueError, NameError): |
| 1024 |
disk_size_parse_failed = True |
| 1025 |
|
| 1026 |
if disk_size_parse_failed: |
| 1027 |
# Common failure |
| 1028 |
self.module.fail_json(msg="Failed to parse disk size for disk index [%s]," |
| 1029 |
" please review value provided" |
| 1030 |
" using documentation." % disk_index) |
| 1031 |
|
| 1032 |
disk_units = dict(tb=3, gb=2, mb=1, kb=0) |
| 1033 |
unit = unit.lower() |
| 1034 |
if unit in disk_units: |
| 1035 |
current_disk['size'] = round(expected * (1024 ** disk_units[unit])) |
| 1036 |
else: |
| 1037 |
self.module.fail_json(msg="%s is not a supported unit for disk size for disk index [%s]." |
| 1038 |
" Supported units are ['%s']." % (unit, disk_index, "', '".join(disk_units.keys()))) |
| 1039 |
elif current_disk['filename'] is None and disk['type'] != 'rdm': |
| 1040 |
# No size found but disk, fail. Excepting RDMs because the cluster_disk will need a filename. |
| 1041 |
self.module.fail_json(msg="No size, size_kb, size_mb, size_gb or size_tb" |
| 1042 |
" attribute found into disk index [%s] configuration." % disk_index) |
| 1043 |
|
| 1044 |
# Mode of Disk |
| 1045 |
if disk['disk_mode'] is not None: |
| 1046 |
current_disk['disk_mode'] = disk['disk_mode'] |
| 1047 |
|
| 1048 |
if current_disk['disk_type'] != 'vpmemdisk': |
| 1049 |
# Sharing mode of disk |
| 1050 |
current_disk['sharing'] = self.get_sharing(disk, current_disk['disk_type'], disk_index) |
| 1051 |
|
| 1052 |
if disk['shares'] is not None: |
| 1053 |
current_disk['shares'] = disk['shares'] |
| 1054 |
if disk['iolimit'] is not None: |
| 1055 |
current_disk['iolimit'] = disk['iolimit'] |
| 1056 |
|
| 1057 |
# Deal with RDM disk needs. RDMS require some different values compared to Virtual Disks |
| 1058 |
if disk['type'] == 'rdm': |
| 1059 |
compatibility_mode = disk.get('compatibility_mode', 'physicalMode') |
| 1060 |
if compatibility_mode not in ['physicalMode', 'virtualMode']: |
| 1061 |
self.module.fail_json(msg="Invalid 'compatibility_mode' specified for disk index [%s]. Please specify" |
| 1062 |
"'compatibility_mode' value from ['physicalMode', 'virtualMode']." % disk_index) |
| 1063 |
current_disk['compatibility_mode'] = compatibility_mode |
| 1064 |
|
| 1065 |
# RDMs need a path |
| 1066 |
if 'rdm_path' not in disk and 'filename' not in disk: |
| 1067 |
self.module.fail_json(msg="rdm_path and/or 'filename' needs must be specified when using disk type 'rdm'" |
| 1068 |
"for disk index [%s]" % disk_index) |
| 1069 |
else: |
| 1070 |
current_disk['rdm_path'] = disk.get('rdm_path') |
| 1071 |
|
| 1072 |
if disk['filename'] and disk['rdm_path'] is None and disk['cluster_disk'] is False: |
| 1073 |
self.module.fail_json(msg=" 'filename' requires setting 'cluster_disk' to True when using disk type 'rdm' without a" |
| 1074 |
"'rdm_path' for disk index [%s]" % disk_index) |
| 1075 |
else: |
| 1076 |
current_disk['cluster_disk'] = disk.get('cluster_disk') |
| 1077 |
|
| 1078 |
# Enable Physical or virtual SCSI Bus Sharing |
| 1079 |
if disk['bus_sharing']: |
| 1080 |
bus_sharing = disk.get('bus_sharing', 'noSharing') |
| 1081 |
if bus_sharing not in ['noSharing', 'physicalSharing', 'virtualSharing']: |
| 1082 |
self.module.fail_json(msg="Invalid SCSI 'bus_sharing' specied for disk index [%s]. Please " |
| 1083 |
"specify 'bus_sharing' value from " |
| 1084 |
"['noSharing', 'physicalSharing', 'virtualSharing']." % disk_index) |
| 1085 |
current_disk['bus_sharing'] = bus_sharing |
| 1086 |
|
| 1087 |
disks_data.append(current_disk) |
| 1088 |
|
| 1089 |
return disks_data |
| 1090 |
|
| 1091 |
def get_recommended_datastore(self, datastore_cluster_obj, disk_spec_obj): |
| 1092 |
""" |
| 1093 |
Return Storage DRS recommended datastore from datastore cluster |
| 1094 |
Args: |
| 1095 |
datastore_cluster_obj: datastore cluster managed object |
| 1096 |
|
| 1097 |
Returns: Name of recommended datastore from the given datastore cluster, |
| 1098 |
Returns None if no datastore recommendation found. |
| 1099 |
|
| 1100 |
""" |
| 1101 |
# Check if Datastore Cluster provided by user is SDRS ready |
| 1102 |
sdrs_status = datastore_cluster_obj.podStorageDrsEntry.storageDrsConfig.podConfig.enabled |
| 1103 |
if sdrs_status: |
| 1104 |
# We can get storage recommendation only if SDRS is enabled on given datastorage cluster |
| 1105 |
disk_loc = vim.storageDrs.PodSelectionSpec.DiskLocator() |
| 1106 |
pod_config = vim.storageDrs.PodSelectionSpec.VmPodConfig() |
| 1107 |
pod_config.storagePod = datastore_cluster_obj |
| 1108 |
pod_config.disk = [disk_loc] |
| 1109 |
pod_sel_spec = vim.storageDrs.PodSelectionSpec() |
| 1110 |
pod_sel_spec.initialVmConfig = [pod_config] |
| 1111 |
storage_spec = vim.storageDrs.StoragePlacementSpec() |
| 1112 |
storage_spec.configSpec = vim.vm.ConfigSpec() |
| 1113 |
storage_spec.configSpec.deviceChange.append(disk_spec_obj) |
| 1114 |
storage_spec.resourcePool = self.vm.resourcePool |
| 1115 |
storage_spec.podSelectionSpec = pod_sel_spec |
| 1116 |
storage_spec.vm = self.vm |
| 1117 |
storage_spec.type = 'reconfigure' |
| 1118 |
|
| 1119 |
try: |
| 1120 |
rec = self.content.storageResourceManager.RecommendDatastores(storageSpec=storage_spec) |
| 1121 |
rec_action = rec.recommendations[0].action[0] |
| 1122 |
return rec_action.destination.name |
| 1123 |
except Exception: |
| 1124 |
# There is some error so we fall back to general workflow |
| 1125 |
pass |
| 1126 |
datastore = None |
| 1127 |
datastore_freespace = 0 |
| 1128 |
for ds in datastore_cluster_obj.childEntity: |
| 1129 |
if ds.summary.maintenanceMode == "inMaintenance": |
| 1130 |
continue |
| 1131 |
if ds.summary.freeSpace > datastore_freespace: |
| 1132 |
# If datastore field is provided, filter destination datastores |
| 1133 |
datastore = ds |
| 1134 |
datastore_freespace = ds.summary.freeSpace |
| 1135 |
if datastore: |
| 1136 |
return datastore.name |
| 1137 |
return None |
| 1138 |
|
| 1139 |
|
| 1140 |
def main(): |
| 1141 |
argument_spec = base_argument_spec() |
| 1142 |
argument_spec.update( |
| 1143 |
name=dict(type='str'), |
| 1144 |
uuid=dict(type='str'), |
| 1145 |
moid=dict(type='str'), |
| 1146 |
folder=dict(type='str'), |
| 1147 |
datacenter=dict(type='str', required=True), |
| 1148 |
use_instance_uuid=dict(type='bool', default=False), |
| 1149 |
disk=dict( |
| 1150 |
type='list', |
| 1151 |
default=[], |
| 1152 |
elements='dict', |
| 1153 |
options=dict( |
| 1154 |
size=dict(type='str'), |
| 1155 |
size_kb=dict(type='int'), |
| 1156 |
size_mb=dict(type='int'), |
| 1157 |
size_gb=dict(type='int'), |
| 1158 |
size_tb=dict(type='int'), |
| 1159 |
type=dict(type='str', choices=['thin', 'eagerzeroedthick', 'thick', 'rdm', 'vpmemdisk']), |
| 1160 |
disk_mode=dict(type='str', choices=['persistent', 'independent_persistent', 'independent_nonpersistent']), |
| 1161 |
compatibility_mode=dict(type='str', choices=['physicalMode', 'virtualMode']), |
| 1162 |
rdm_path=dict(type='str'), |
| 1163 |
sharing=dict(type='bool', default=False), |
| 1164 |
datastore=dict(type='str'), |
| 1165 |
autoselect_datastore=dict(type='bool'), |
| 1166 |
scsi_controller=dict(type='int', choices=[0, 1, 2, 3]), |
| 1167 |
unit_number=dict(type='int', required=True), |
| 1168 |
scsi_type=dict(type='str', choices=['buslogic', 'lsilogic', 'paravirtual', 'lsilogicsas']), |
| 1169 |
destroy=dict(type='bool', default=True), |
| 1170 |
filename=dict(type='str'), |
| 1171 |
state=dict(type='str', default='present', choices=['present', 'absent']), |
| 1172 |
controller_type=dict(type='str', choices=['buslogic', 'lsilogic', 'paravirtual', 'lsilogicsas', 'sata', 'nvme', 'ide']), |
| 1173 |
controller_number=dict(type='int', choices=[0, 1, 2, 3]), |
| 1174 |
bus_sharing=dict(type='str', choices=['noSharing', 'physicalSharing', 'virtualSharing'], default='noSharing'), |
| 1175 |
cluster_disk=dict(type='bool', default=False), |
| 1176 |
iolimit=dict( |
| 1177 |
type='dict', |
| 1178 |
options=dict( |
| 1179 |
limit=dict(type='int'), |
| 1180 |
shares=dict( |
| 1181 |
type='dict', |
| 1182 |
options=dict( |
| 1183 |
level=dict(type='str', choices=['low', 'high', 'normal', 'custom']), |
| 1184 |
level_value=dict(type='int'), |
| 1185 |
), |
| 1186 |
), |
| 1187 |
)), |
| 1188 |
shares=dict( |
| 1189 |
type='dict', |
| 1190 |
options=dict( |
| 1191 |
level=dict(type='str', choices=['low', 'high', 'normal', 'custom']), |
| 1192 |
level_value=dict(type='int'), |
| 1193 |
), |
| 1194 |
), |
| 1195 |
), |
| 1196 |
), |
| 1197 |
) |
| 1198 |
module = AnsibleModule( |
| 1199 |
argument_spec=argument_spec, |
| 1200 |
required_one_of=[['name', 'uuid', 'moid']], |
| 1201 |
) |
| 1202 |
|
| 1203 |
if module.params['folder']: |
| 1204 |
# FindByInventoryPath() does not require an absolute path |
| 1205 |
# so we should leave the input folder path unmodified |
| 1206 |
module.params['folder'] = module.params['folder'].rstrip('/') |
| 1207 |
|
| 1208 |
pyv = PyVmomiHelper(module) |
| 1209 |
# Check if the VM exists before continuing |
| 1210 |
vm = pyv.get_vm() |
| 1211 |
|
| 1212 |
if not vm: |
| 1213 |
# We unable to find the virtual machine user specified |
| 1214 |
# Bail out |
| 1215 |
vm_id = (module.params.get('name') or module.params.get('uuid') or module.params.get('moid')) |
| 1216 |
module.fail_json(msg="Unable to manage disks for non-existing" |
| 1217 |
" virtual machine '%s'." % vm_id) |
| 1218 |
|
| 1219 |
# VM exists |
| 1220 |
try: |
| 1221 |
pyv.ensure_disks(vm_obj=vm) |
| 1222 |
except Exception as exc: |
| 1223 |
module.fail_json(msg="Failed to manage disks for virtual machine" |
| 1224 |
" '%s' with exception : %s" % (vm.name, |
| 1225 |
to_native(exc))) |
| 1226 |
|
| 1227 |
|
| 1228 |
if __name__ == '__main__': |
| 1229 |
main() |