| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2018, Bojan Vitnik <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: xenserver_guest |
| 11 |
short_description: Manages virtual machines running on Citrix Hypervisor/XenServer host or pool |
| 12 |
description: >- |
| 13 |
This module can be used to create new virtual machines from templates or other virtual machines, modify various virtual |
| 14 |
machine components like network and disk, rename a virtual machine and remove a virtual machine with associated components. |
| 15 |
author: |
| 16 |
- Bojan Vitnik (@bvitnik) <[email protected]> |
| 17 |
notes: |
| 18 |
- Minimal supported version of XenServer is 5.6. |
| 19 |
- Module was tested with XenServer 6.5, 7.1, 7.2, 7.6, Citrix Hypervisor 8.0, XCP-ng 7.6 and 8.0. |
| 20 |
- 'To acquire XenAPI Python library, just run C(pip install XenAPI) on your Ansible Control Node. The library can also be |
| 21 |
found inside Citrix Hypervisor/XenServer SDK (downloadable from Citrix website). Copy the C(XenAPI.py) file from the SDK |
| 22 |
to your Python site-packages on your Ansible Control Node to use it. Latest version of the library can also be acquired |
| 23 |
from GitHub: U(https://raw.githubusercontent.com/xapi-project/xen-api/master/scripts/examples/python/XenAPI/XenAPI.py).' |
| 24 |
- If no scheme is specified in O(hostname), module defaults to C(http://) because C(https://) is problematic in most setups. |
| 25 |
Make sure you are accessing XenServer host in trusted environment or use C(https://) scheme explicitly. |
| 26 |
- To use C(https://) scheme for O(hostname) you have to either import host certificate to your OS certificate store or use |
| 27 |
O(validate_certs=false) which requires XenAPI library from XenServer 7.2 SDK or newer and Python 2.7.9 or newer. |
| 28 |
- 'Network configuration inside a guest OS, by using parameters O(networks[].type), O(networks[].ip), O(networks[].gateway) |
| 29 |
and so on, is supported on XenServer 7.0 or newer for Windows guests by using official XenServer Guest agent support for |
| 30 |
network configuration. The module tries to detect if such support is available and utilize it, else it uses a custom method |
| 31 |
of configuration using xenstore. Since XenServer Guest agent only support None and Static types of network configuration, |
| 32 |
where None means DHCP configured interface, O(networks[].type) and O(networks[].type6) values V(none) and V(dhcp) have |
| 33 |
same effect. More info here: |
| 34 |
U(https://web.archive.org/web/20180218110151/https://xenserver.org/blog/entry/set-windows-guest-vm-static-ip-address-in-xenserver.html).' |
| 35 |
- 'On platforms without official support for network configuration inside a guest OS, network parameters are written to |
| 36 |
xenstore C(vm-data/networks/<vif_device>) key. Parameters can be inspected by using C(xenstore ls) and C(xenstore read) |
| 37 |
tools on \*nix guests or through WMI interface on Windows guests. They can also be found in VM facts C(instance.xenstore_data) |
| 38 |
key as returned by the module. It is up to the user to implement a boot time scripts or custom agent that reads the parameters |
| 39 |
from xenstore and configure network with given parameters. Take note that for xenstore data to become available inside |
| 40 |
a guest, a VM restart is needed hence module requires VM restart if any parameter is changed. This is a limitation of |
| 41 |
XenAPI and xenstore. Considering these limitations, network configuration through xenstore is most useful for bootstrapping |
| 42 |
newly deployed VMs, much less for reconfiguring existing ones. More info here: U(https://support.citrix.com/article/CTX226713).' |
| 43 |
requirements: |
| 44 |
- XenAPI |
| 45 |
attributes: |
| 46 |
check_mode: |
| 47 |
support: full |
| 48 |
diff_mode: |
| 49 |
support: none |
| 50 |
options: |
| 51 |
state: |
| 52 |
description: |
| 53 |
- Specify the state VM should be in. |
| 54 |
- If O(state) is set to V(present) and VM exists, ensure the VM configuration conforms to given parameters. |
| 55 |
- If O(state) is set to V(present) and VM does not exist, then VM is deployed with given parameters. |
| 56 |
- If O(state) is set to V(absent) and VM exists, then VM is removed with its associated components. |
| 57 |
- If O(state) is set to V(poweredon) and VM does not exist, then VM is deployed with given parameters and powered on |
| 58 |
automatically. |
| 59 |
type: str |
| 60 |
default: present |
| 61 |
choices: [present, absent, poweredon] |
| 62 |
name: |
| 63 |
description: |
| 64 |
- Name of the VM to work with. |
| 65 |
- VMs running on XenServer do not necessarily have unique names. The module fails if multiple VMs with same name are |
| 66 |
found. |
| 67 |
- In case of multiple VMs with same name, use O(uuid) to uniquely specify VM to manage. |
| 68 |
- This parameter is case sensitive. |
| 69 |
type: str |
| 70 |
aliases: [name_label] |
| 71 |
name_desc: |
| 72 |
description: |
| 73 |
- VM description. |
| 74 |
type: str |
| 75 |
uuid: |
| 76 |
description: |
| 77 |
- UUID of the VM to manage if known. This is XenServer's unique identifier. |
| 78 |
- It is required if name is not unique. |
| 79 |
- Please note that a supplied UUID is ignored on VM creation, as XenServer creates the UUID internally. |
| 80 |
type: str |
| 81 |
template: |
| 82 |
description: |
| 83 |
- Name of a template, an existing VM (must be shut down) or a snapshot that should be used to create VM. |
| 84 |
- Templates/VMs/snapshots on XenServer do not necessarily have unique names. The module fails if multiple templates |
| 85 |
with same name are found. |
| 86 |
- In case of multiple templates/VMs/snapshots with same name, use O(template_uuid) to uniquely specify source template. |
| 87 |
- If VM already exists, this setting is ignored. |
| 88 |
- This parameter is case sensitive. |
| 89 |
type: str |
| 90 |
aliases: [template_src] |
| 91 |
template_uuid: |
| 92 |
description: |
| 93 |
- UUID of a template, an existing VM or a snapshot that should be used to create VM. |
| 94 |
- It is required if template name is not unique. |
| 95 |
type: str |
| 96 |
is_template: |
| 97 |
description: |
| 98 |
- Convert VM to template. |
| 99 |
type: bool |
| 100 |
default: false |
| 101 |
folder: |
| 102 |
description: |
| 103 |
- Destination folder for VM. |
| 104 |
- This parameter is case sensitive. |
| 105 |
- 'Example: O(folder=/folder1/folder2).' |
| 106 |
type: str |
| 107 |
hardware: |
| 108 |
description: |
| 109 |
- Manage VM's hardware parameters. VM needs to be shut down to reconfigure these parameters. |
| 110 |
type: dict |
| 111 |
suboptions: |
| 112 |
num_cpus: |
| 113 |
description: |
| 114 |
- Number of CPUs. |
| 115 |
type: int |
| 116 |
num_cpu_cores_per_socket: |
| 117 |
description: |
| 118 |
- Number of Cores Per Socket. O(hardware.num_cpus) has to be a multiple of O(hardware.num_cpu_cores_per_socket). |
| 119 |
type: int |
| 120 |
memory_mb: |
| 121 |
description: |
| 122 |
- Amount of memory in MB. |
| 123 |
type: int |
| 124 |
disks: |
| 125 |
description: |
| 126 |
- A list of disks to add to VM. |
| 127 |
- All parameters are case sensitive. |
| 128 |
- Removing or detaching existing disks of VM is not supported. |
| 129 |
- New disks are required to have either a O(disks[].size) or one of O(ignore:disks[].size_[tb,gb,mb,kb,b]) parameters |
| 130 |
specified. |
| 131 |
- VM needs to be shut down to reconfigure disk size. |
| 132 |
type: list |
| 133 |
elements: dict |
| 134 |
aliases: [disk] |
| 135 |
suboptions: |
| 136 |
size: |
| 137 |
description: |
| 138 |
- 'Disk size with unit. Unit must be: V(b), V(kb), V(mb), V(gb), V(tb). VM needs to be shut down to reconfigure |
| 139 |
this parameter.' |
| 140 |
- If no unit is specified, size is assumed to be in bytes. |
| 141 |
type: str |
| 142 |
size_b: |
| 143 |
description: |
| 144 |
- Disk size in bytes. |
| 145 |
type: str |
| 146 |
size_kb: |
| 147 |
description: |
| 148 |
- Disk size in kilobytes. |
| 149 |
type: str |
| 150 |
size_mb: |
| 151 |
description: |
| 152 |
- Disk size in megabytes. |
| 153 |
type: str |
| 154 |
size_gb: |
| 155 |
description: |
| 156 |
- Disk size in gigabytes. |
| 157 |
type: str |
| 158 |
size_tb: |
| 159 |
description: |
| 160 |
- Disk size in terabytes. |
| 161 |
type: str |
| 162 |
name: |
| 163 |
description: |
| 164 |
- Disk name. |
| 165 |
type: str |
| 166 |
aliases: [name_label] |
| 167 |
name_desc: |
| 168 |
description: |
| 169 |
- Disk description. |
| 170 |
type: str |
| 171 |
sr: |
| 172 |
description: |
| 173 |
- Storage Repository to create disk on. If not specified, it uses default SR. Cannot be used for moving disk to |
| 174 |
other SR. |
| 175 |
type: str |
| 176 |
sr_uuid: |
| 177 |
description: |
| 178 |
- UUID of a SR to create disk on. Use if SR name is not unique. |
| 179 |
type: str |
| 180 |
cdrom: |
| 181 |
description: |
| 182 |
- A CD-ROM configuration for the VM. |
| 183 |
- All parameters are case sensitive. |
| 184 |
type: dict |
| 185 |
suboptions: |
| 186 |
type: |
| 187 |
description: |
| 188 |
- The type of CD-ROM. When V(none) the CD-ROM device is present but empty. |
| 189 |
type: str |
| 190 |
choices: [none, iso] |
| 191 |
iso_name: |
| 192 |
description: |
| 193 |
- The file name of an ISO image from one of the XenServer ISO Libraries (implies O(cdrom.type=iso)). |
| 194 |
- Required if O(cdrom.type) is set to V(iso). |
| 195 |
type: str |
| 196 |
networks: |
| 197 |
description: |
| 198 |
- A list of networks (in the order of the NICs). |
| 199 |
- All parameters are case sensitive. |
| 200 |
- Name is required for new NICs. Other parameters are optional in all cases. |
| 201 |
type: list |
| 202 |
elements: dict |
| 203 |
aliases: [network] |
| 204 |
suboptions: |
| 205 |
name: |
| 206 |
description: |
| 207 |
- Name of a XenServer network to attach the network interface to. |
| 208 |
type: str |
| 209 |
aliases: [name_label] |
| 210 |
mac: |
| 211 |
description: |
| 212 |
- Customize MAC address of the interface. |
| 213 |
type: str |
| 214 |
type: |
| 215 |
description: |
| 216 |
- Type of IPv4 assignment. Value V(none) means whatever is default for OS. |
| 217 |
- On some operating systems it could be DHCP configured (for example Windows) or unconfigured interface (for example |
| 218 |
Linux). |
| 219 |
type: str |
| 220 |
choices: [none, dhcp, static] |
| 221 |
ip: |
| 222 |
description: |
| 223 |
- Static IPv4 address (implies O(networks[].type=static)). Can include prefix in format C(<IPv4 address>/<prefix>) |
| 224 |
instead of using C(netmask). |
| 225 |
type: str |
| 226 |
netmask: |
| 227 |
description: |
| 228 |
- Static IPv4 netmask required for O(networks[].ip) if prefix is not specified. |
| 229 |
type: str |
| 230 |
gateway: |
| 231 |
description: |
| 232 |
- Static IPv4 gateway. |
| 233 |
type: str |
| 234 |
type6: |
| 235 |
description: |
| 236 |
- Type of IPv6 assignment. Value V(none) means whatever is default for OS. |
| 237 |
type: str |
| 238 |
choices: [none, dhcp, static] |
| 239 |
ip6: |
| 240 |
description: |
| 241 |
- Static IPv6 address (implies O(networks[].type6=static)) with prefix in format C(<IPv6 address>/<prefix>). |
| 242 |
type: str |
| 243 |
gateway6: |
| 244 |
description: |
| 245 |
- Static IPv6 gateway. |
| 246 |
type: str |
| 247 |
home_server: |
| 248 |
description: |
| 249 |
- Name of a XenServer host that is a Home Server for the VM. |
| 250 |
- This parameter is case sensitive. |
| 251 |
type: str |
| 252 |
custom_params: |
| 253 |
description: |
| 254 |
- Define a list of custom VM params to set on VM. |
| 255 |
- Useful for advanced users familiar with managing VM params through C(xe) CLI. |
| 256 |
- A custom value object takes two fields O(custom_params[].key) and O(custom_params[].value) (see example below). |
| 257 |
type: list |
| 258 |
elements: dict |
| 259 |
suboptions: |
| 260 |
key: |
| 261 |
description: |
| 262 |
- VM param name. |
| 263 |
type: str |
| 264 |
required: true |
| 265 |
value: |
| 266 |
description: |
| 267 |
- VM param value. |
| 268 |
type: raw |
| 269 |
required: true |
| 270 |
wait_for_ip_address: |
| 271 |
description: |
| 272 |
- Wait until XenServer detects an IP address for the VM. If O(state) is set to V(absent), this parameter is ignored. |
| 273 |
- This requires XenServer Tools to be preinstalled on the VM to work properly. |
| 274 |
type: bool |
| 275 |
default: false |
| 276 |
state_change_timeout: |
| 277 |
description: |
| 278 |
- By default, the module waits indefinitely for VM to acquire an IP address if O(wait_for_ip_address=true). |
| 279 |
- If this parameter is set to a positive value, the module instead waits the specified number of seconds for the state |
| 280 |
change. |
| 281 |
- In case of timeout, module generates an error message. |
| 282 |
type: int |
| 283 |
default: 0 |
| 284 |
linked_clone: |
| 285 |
description: |
| 286 |
- Whether to create a Linked Clone from the template, existing VM or snapshot. If V(false), it creates a full copy. |
| 287 |
- This is equivalent to C(Use storage-level fast disk clone) option in XenCenter. |
| 288 |
type: bool |
| 289 |
default: false |
| 290 |
force: |
| 291 |
description: |
| 292 |
- Ignore warnings and complete the actions. |
| 293 |
- This parameter is useful for removing VM in running state or reconfiguring VM params that require VM to be shut down. |
| 294 |
type: bool |
| 295 |
default: false |
| 296 |
extends_documentation_fragment: |
| 297 |
- community.general._xenserver.documentation |
| 298 |
- community.general._attributes |
| 299 |
""" |
| 300 |
|
| 301 |
EXAMPLES = r""" |
| 302 |
- name: Create a VM from a template |
| 303 |
community.general.xenserver_guest: |
| 304 |
hostname: "{{ xenserver_hostname }}" |
| 305 |
username: "{{ xenserver_username }}" |
| 306 |
password: "{{ xenserver_password }}" |
| 307 |
folder: /testvms |
| 308 |
name: testvm_2 |
| 309 |
state: poweredon |
| 310 |
template: CentOS 7 |
| 311 |
disks: |
| 312 |
- size_gb: 10 |
| 313 |
sr: my_sr |
| 314 |
hardware: |
| 315 |
num_cpus: 6 |
| 316 |
num_cpu_cores_per_socket: 3 |
| 317 |
memory_mb: 512 |
| 318 |
cdrom: |
| 319 |
type: iso |
| 320 |
iso_name: guest-tools.iso |
| 321 |
networks: |
| 322 |
- name: VM Network |
| 323 |
mac: aa:bb:dd:aa:00:14 |
| 324 |
wait_for_ip_address: true |
| 325 |
delegate_to: localhost |
| 326 |
register: deploy |
| 327 |
|
| 328 |
- name: Create a VM template |
| 329 |
community.general.xenserver_guest: |
| 330 |
hostname: "{{ xenserver_hostname }}" |
| 331 |
username: "{{ xenserver_username }}" |
| 332 |
password: "{{ xenserver_password }}" |
| 333 |
folder: /testvms |
| 334 |
name: testvm_6 |
| 335 |
is_template: true |
| 336 |
disk: |
| 337 |
- size_gb: 10 |
| 338 |
sr: my_sr |
| 339 |
hardware: |
| 340 |
memory_mb: 512 |
| 341 |
num_cpus: 1 |
| 342 |
delegate_to: localhost |
| 343 |
register: deploy |
| 344 |
|
| 345 |
- name: Rename a VM (requires the VM's UUID) |
| 346 |
community.general.xenserver_guest: |
| 347 |
hostname: "{{ xenserver_hostname }}" |
| 348 |
username: "{{ xenserver_username }}" |
| 349 |
password: "{{ xenserver_password }}" |
| 350 |
uuid: 421e4592-c069-924d-ce20-7e7533fab926 |
| 351 |
name: new_name |
| 352 |
state: present |
| 353 |
delegate_to: localhost |
| 354 |
|
| 355 |
- name: Remove a VM by UUID |
| 356 |
community.general.xenserver_guest: |
| 357 |
hostname: "{{ xenserver_hostname }}" |
| 358 |
username: "{{ xenserver_username }}" |
| 359 |
password: "{{ xenserver_password }}" |
| 360 |
uuid: 421e4592-c069-924d-ce20-7e7533fab926 |
| 361 |
state: absent |
| 362 |
delegate_to: localhost |
| 363 |
|
| 364 |
- name: Modify custom params (boot order) |
| 365 |
community.general.xenserver_guest: |
| 366 |
hostname: "{{ xenserver_hostname }}" |
| 367 |
username: "{{ xenserver_username }}" |
| 368 |
password: "{{ xenserver_password }}" |
| 369 |
name: testvm_8 |
| 370 |
state: present |
| 371 |
custom_params: |
| 372 |
- key: HVM_boot_params |
| 373 |
value: {"order": "ndc"} |
| 374 |
delegate_to: localhost |
| 375 |
|
| 376 |
- name: Customize network parameters |
| 377 |
community.general.xenserver_guest: |
| 378 |
hostname: "{{ xenserver_hostname }}" |
| 379 |
username: "{{ xenserver_username }}" |
| 380 |
password: "{{ xenserver_password }}" |
| 381 |
name: testvm_10 |
| 382 |
networks: |
| 383 |
- name: VM Network |
| 384 |
ip: 192.168.1.100/24 |
| 385 |
gateway: 192.168.1.1 |
| 386 |
- type: dhcp |
| 387 |
delegate_to: localhost |
| 388 |
""" |
| 389 |
|
| 390 |
RETURN = r""" |
| 391 |
instance: |
| 392 |
description: Metadata about the VM. |
| 393 |
returned: always |
| 394 |
type: dict |
| 395 |
sample: |
| 396 |
{ |
| 397 |
"cdrom": { |
| 398 |
"type": "none" |
| 399 |
}, |
| 400 |
"customization_agent": "native", |
| 401 |
"disks": [ |
| 402 |
{ |
| 403 |
"name": "testvm_11-0", |
| 404 |
"name_desc": "", |
| 405 |
"os_device": "xvda", |
| 406 |
"size": 42949672960, |
| 407 |
"sr": "Local storage", |
| 408 |
"sr_uuid": "0af1245e-bdb0-ba33-1446-57a962ec4075", |
| 409 |
"vbd_userdevice": "0" |
| 410 |
}, |
| 411 |
{ |
| 412 |
"name": "testvm_11-1", |
| 413 |
"name_desc": "", |
| 414 |
"os_device": "xvdb", |
| 415 |
"size": 42949672960, |
| 416 |
"sr": "Local storage", |
| 417 |
"sr_uuid": "0af1245e-bdb0-ba33-1446-57a962ec4075", |
| 418 |
"vbd_userdevice": "1" |
| 419 |
} |
| 420 |
], |
| 421 |
"domid": "56", |
| 422 |
"folder": "", |
| 423 |
"hardware": { |
| 424 |
"memory_mb": 8192, |
| 425 |
"num_cpu_cores_per_socket": 2, |
| 426 |
"num_cpus": 4 |
| 427 |
}, |
| 428 |
"home_server": "", |
| 429 |
"is_template": false, |
| 430 |
"name": "testvm_11", |
| 431 |
"name_desc": "", |
| 432 |
"networks": [ |
| 433 |
{ |
| 434 |
"gateway": "192.168.0.254", |
| 435 |
"gateway6": "fc00::fffe", |
| 436 |
"ip": "192.168.0.200", |
| 437 |
"ip6": [ |
| 438 |
"fe80:0000:0000:0000:e9cb:625a:32c5:c291", |
| 439 |
"fc00:0000:0000:0000:0000:0000:0000:0001" |
| 440 |
], |
| 441 |
"mac": "ba:91:3a:48:20:76", |
| 442 |
"mtu": "1500", |
| 443 |
"name": "Pool-wide network associated with eth1", |
| 444 |
"netmask": "255.255.255.128", |
| 445 |
"prefix": "25", |
| 446 |
"prefix6": "64", |
| 447 |
"vif_device": "0" |
| 448 |
} |
| 449 |
], |
| 450 |
"other_config": { |
| 451 |
"base_template_name": "Windows Server 2016 (64-bit)", |
| 452 |
"import_task": "OpaqueRef:e43eb71c-45d6-5351-09ff-96e4fb7d0fa5", |
| 453 |
"install-methods": "cdrom", |
| 454 |
"instant": "true", |
| 455 |
"mac_seed": "f83e8d8a-cfdc-b105-b054-ef5cb416b77e" |
| 456 |
}, |
| 457 |
"platform": { |
| 458 |
"acpi": "1", |
| 459 |
"apic": "true", |
| 460 |
"cores-per-socket": "2", |
| 461 |
"device_id": "0002", |
| 462 |
"hpet": "true", |
| 463 |
"nx": "true", |
| 464 |
"pae": "true", |
| 465 |
"timeoffset": "-25200", |
| 466 |
"vga": "std", |
| 467 |
"videoram": "8", |
| 468 |
"viridian": "true", |
| 469 |
"viridian_reference_tsc": "true", |
| 470 |
"viridian_time_ref_count": "true" |
| 471 |
}, |
| 472 |
"state": "poweredon", |
| 473 |
"uuid": "e3c0b2d5-5f05-424e-479c-d3df8b3e7cda", |
| 474 |
"xenstore_data": { |
| 475 |
"vm-data": "" |
| 476 |
} |
| 477 |
} |
| 478 |
changes: |
| 479 |
description: Detected or made changes to VM. |
| 480 |
returned: always |
| 481 |
type: list |
| 482 |
sample: |
| 483 |
[ |
| 484 |
{ |
| 485 |
"hardware": [ |
| 486 |
"num_cpus" |
| 487 |
] |
| 488 |
}, |
| 489 |
{ |
| 490 |
"disks_changed": [ |
| 491 |
[], |
| 492 |
[ |
| 493 |
"size" |
| 494 |
] |
| 495 |
] |
| 496 |
}, |
| 497 |
{ |
| 498 |
"disks_new": [ |
| 499 |
{ |
| 500 |
"name": "new-disk", |
| 501 |
"name_desc": "", |
| 502 |
"position": 2, |
| 503 |
"size_gb": "4", |
| 504 |
"vbd_userdevice": "2" |
| 505 |
} |
| 506 |
] |
| 507 |
}, |
| 508 |
{ |
| 509 |
"cdrom": [ |
| 510 |
"type", |
| 511 |
"iso_name" |
| 512 |
] |
| 513 |
}, |
| 514 |
{ |
| 515 |
"networks_changed": [ |
| 516 |
[ |
| 517 |
"mac" |
| 518 |
] |
| 519 |
] |
| 520 |
}, |
| 521 |
{ |
| 522 |
"networks_new": [ |
| 523 |
{ |
| 524 |
"name": "Pool-wide network associated with eth2", |
| 525 |
"position": 1, |
| 526 |
"vif_device": "1" |
| 527 |
} |
| 528 |
] |
| 529 |
}, |
| 530 |
"need_poweredoff" |
| 531 |
] |
| 532 |
""" |
| 533 |
|
| 534 |
import re |
| 535 |
|
| 536 |
HAS_XENAPI = False |
| 537 |
try: |
| 538 |
import XenAPI |
| 539 |
|
| 540 |
HAS_XENAPI = True |
| 541 |
except ImportError: |
| 542 |
pass |
| 543 |
|
| 544 |
from ansible.module_utils.basic import AnsibleModule |
| 545 |
from ansible.module_utils.common.network import is_mac |
| 546 |
|
| 547 |
from ansible_collections.community.general.plugins.module_utils._xenserver import ( |
| 548 |
XenServerObject, |
| 549 |
gather_vm_facts, |
| 550 |
gather_vm_params, |
| 551 |
get_object_ref, |
| 552 |
ip_netmask_to_prefix, |
| 553 |
ip_prefix_to_netmask, |
| 554 |
is_valid_ip6_addr, |
| 555 |
is_valid_ip6_prefix, |
| 556 |
is_valid_ip_addr, |
| 557 |
is_valid_ip_netmask, |
| 558 |
is_valid_ip_prefix, |
| 559 |
set_vm_power_state, |
| 560 |
wait_for_vm_ip_address, |
| 561 |
xenserver_common_argument_spec, |
| 562 |
) |
| 563 |
|
| 564 |
|
| 565 |
class XenServerVM(XenServerObject): |
| 566 |
"""Class for managing XenServer VM. |
| 567 |
|
| 568 |
Attributes: |
| 569 |
vm_ref (str): XAPI reference to VM. |
| 570 |
vm_params (dict): A dictionary with VM parameters as returned |
| 571 |
by gather_vm_params() function. |
| 572 |
""" |
| 573 |
|
| 574 |
def __init__(self, module): |
| 575 |
"""Inits XenServerVM using module parameters. |
| 576 |
|
| 577 |
Args: |
| 578 |
module: Reference to Ansible module object. |
| 579 |
""" |
| 580 |
super().__init__(module) |
| 581 |
|
| 582 |
self.vm_ref = get_object_ref( |
| 583 |
self.module, |
| 584 |
self.module.params["name"], |
| 585 |
self.module.params["uuid"], |
| 586 |
obj_type="VM", |
| 587 |
fail=False, |
| 588 |
msg_prefix="VM search: ", |
| 589 |
) |
| 590 |
self.gather_params() |
| 591 |
|
| 592 |
def exists(self): |
| 593 |
"""Returns True if VM exists, else False.""" |
| 594 |
return True if self.vm_ref is not None else False |
| 595 |
|
| 596 |
def gather_params(self): |
| 597 |
"""Gathers all VM parameters available in XAPI database.""" |
| 598 |
self.vm_params = gather_vm_params(self.module, self.vm_ref) |
| 599 |
|
| 600 |
def gather_facts(self): |
| 601 |
"""Gathers and returns VM facts.""" |
| 602 |
return gather_vm_facts(self.module, self.vm_params) |
| 603 |
|
| 604 |
def set_power_state(self, power_state): |
| 605 |
"""Controls VM power state.""" |
| 606 |
state_changed, current_state = set_vm_power_state( |
| 607 |
self.module, self.vm_ref, power_state, self.module.params["state_change_timeout"] |
| 608 |
) |
| 609 |
|
| 610 |
# If state has changed, update vm_params. |
| 611 |
if state_changed: |
| 612 |
self.vm_params["power_state"] = current_state.capitalize() |
| 613 |
|
| 614 |
return state_changed |
| 615 |
|
| 616 |
def wait_for_ip_address(self): |
| 617 |
"""Waits for VM to acquire an IP address.""" |
| 618 |
self.vm_params["guest_metrics"] = wait_for_vm_ip_address( |
| 619 |
self.module, self.vm_ref, self.module.params["state_change_timeout"] |
| 620 |
) |
| 621 |
|
| 622 |
def deploy(self): |
| 623 |
"""Deploys new VM from template.""" |
| 624 |
# Safety check. |
| 625 |
if self.exists(): |
| 626 |
self.module.fail_json(msg="Called deploy on existing VM!") |
| 627 |
|
| 628 |
try: |
| 629 |
templ_ref = get_object_ref( |
| 630 |
self.module, |
| 631 |
self.module.params["template"], |
| 632 |
self.module.params["template_uuid"], |
| 633 |
obj_type="template", |
| 634 |
fail=True, |
| 635 |
msg_prefix="VM deploy: ", |
| 636 |
) |
| 637 |
|
| 638 |
# Is this an existing running VM? |
| 639 |
if self.xapi_session.xenapi.VM.get_power_state(templ_ref).lower() != "halted": |
| 640 |
self.module.fail_json(msg="VM deploy: running VM cannot be used as a template!") |
| 641 |
|
| 642 |
# Find a SR we can use for VM.copy(). We use SR of the first disk |
| 643 |
# if specified or default SR if not specified. |
| 644 |
disk_params_list = self.module.params["disks"] |
| 645 |
|
| 646 |
sr_ref = None |
| 647 |
|
| 648 |
if disk_params_list: |
| 649 |
disk_params = disk_params_list[0] |
| 650 |
|
| 651 |
disk_sr_uuid = disk_params.get("sr_uuid") |
| 652 |
disk_sr = disk_params.get("sr") |
| 653 |
|
| 654 |
if disk_sr_uuid is not None or disk_sr is not None: |
| 655 |
sr_ref = get_object_ref( |
| 656 |
self.module, disk_sr, disk_sr_uuid, obj_type="SR", fail=True, msg_prefix="VM deploy disks[0]: " |
| 657 |
) |
| 658 |
|
| 659 |
if not sr_ref: |
| 660 |
if self.default_sr_ref != "OpaqueRef:NULL": |
| 661 |
sr_ref = self.default_sr_ref |
| 662 |
else: |
| 663 |
self.module.fail_json( |
| 664 |
msg="VM deploy disks[0]: no default SR found! You must specify SR explicitly." |
| 665 |
) |
| 666 |
|
| 667 |
# VM name could be an empty string which is bad. |
| 668 |
if self.module.params["name"] is not None and not self.module.params["name"]: |
| 669 |
self.module.fail_json(msg="VM deploy: VM name must not be an empty string!") |
| 670 |
|
| 671 |
# Support for Ansible check mode. |
| 672 |
if self.module.check_mode: |
| 673 |
return |
| 674 |
|
| 675 |
# Now we can instantiate VM. We use VM.clone for linked_clone and |
| 676 |
# VM.copy for non linked_clone. |
| 677 |
if self.module.params["linked_clone"]: |
| 678 |
self.vm_ref = self.xapi_session.xenapi.VM.clone(templ_ref, self.module.params["name"]) |
| 679 |
else: |
| 680 |
self.vm_ref = self.xapi_session.xenapi.VM.copy(templ_ref, self.module.params["name"], sr_ref) |
| 681 |
|
| 682 |
# Description is copied over from template so we reset it. |
| 683 |
self.xapi_session.xenapi.VM.set_name_description(self.vm_ref, "") |
| 684 |
|
| 685 |
# If template is one of built-in XenServer templates, we have to |
| 686 |
# do some additional steps. |
| 687 |
# Note: VM.get_is_default_template() is supported from XenServer 7.2 |
| 688 |
# onward so we use an alternative way. |
| 689 |
templ_other_config = self.xapi_session.xenapi.VM.get_other_config(templ_ref) |
| 690 |
|
| 691 |
if "default_template" in templ_other_config and templ_other_config["default_template"]: |
| 692 |
# other_config of built-in XenServer templates have a key called |
| 693 |
# 'disks' with the following content: |
| 694 |
# disks: <provision><disk bootable="true" device="0" size="10737418240" sr="" type="system"/></provision> |
| 695 |
# This value of other_data is copied to cloned or copied VM and |
| 696 |
# it prevents provisioning of VM because sr is not specified and |
| 697 |
# XAPI returns an error. To get around this, we remove the |
| 698 |
# 'disks' key and add disks to VM later ourselves. |
| 699 |
vm_other_config = self.xapi_session.xenapi.VM.get_other_config(self.vm_ref) |
| 700 |
|
| 701 |
if "disks" in vm_other_config: |
| 702 |
del vm_other_config["disks"] |
| 703 |
|
| 704 |
self.xapi_session.xenapi.VM.set_other_config(self.vm_ref, vm_other_config) |
| 705 |
|
| 706 |
# At this point we have VM ready for provisioning. |
| 707 |
self.xapi_session.xenapi.VM.provision(self.vm_ref) |
| 708 |
|
| 709 |
# After provisioning we can prepare vm_params for reconfigure(). |
| 710 |
self.gather_params() |
| 711 |
|
| 712 |
# VM is almost ready. We just need to reconfigure it... |
| 713 |
self.reconfigure() |
| 714 |
|
| 715 |
# Power on VM if needed. |
| 716 |
if self.module.params["state"] == "poweredon": |
| 717 |
self.set_power_state("poweredon") |
| 718 |
|
| 719 |
except XenAPI.Failure as f: |
| 720 |
self.module.fail_json(msg=f"XAPI ERROR: {f.details}") |
| 721 |
|
| 722 |
def reconfigure(self): |
| 723 |
"""Reconfigures an existing VM. |
| 724 |
|
| 725 |
Returns: |
| 726 |
list: parameters that were reconfigured. |
| 727 |
""" |
| 728 |
# Safety check. |
| 729 |
if not self.exists(): |
| 730 |
self.module.fail_json(msg="Called reconfigure on non existing VM!") |
| 731 |
|
| 732 |
config_changes = self.get_changes() |
| 733 |
|
| 734 |
vm_power_state_save = self.vm_params["power_state"].lower() |
| 735 |
|
| 736 |
if "need_poweredoff" in config_changes and vm_power_state_save != "halted" and not self.module.params["force"]: |
| 737 |
self.module.fail_json( |
| 738 |
msg="VM reconfigure: VM has to be in powered off state to reconfigure but force was not specified!" |
| 739 |
) |
| 740 |
|
| 741 |
# Support for Ansible check mode. |
| 742 |
if self.module.check_mode: |
| 743 |
return config_changes |
| 744 |
|
| 745 |
if "need_poweredoff" in config_changes and vm_power_state_save != "halted" and self.module.params["force"]: |
| 746 |
self.set_power_state("shutdownguest") |
| 747 |
|
| 748 |
try: |
| 749 |
for change in config_changes: |
| 750 |
if isinstance(change, str): |
| 751 |
if change == "name": |
| 752 |
self.xapi_session.xenapi.VM.set_name_label(self.vm_ref, self.module.params["name"]) |
| 753 |
elif change == "name_desc": |
| 754 |
self.xapi_session.xenapi.VM.set_name_description(self.vm_ref, self.module.params["name_desc"]) |
| 755 |
elif change == "folder": |
| 756 |
self.xapi_session.xenapi.VM.remove_from_other_config(self.vm_ref, "folder") |
| 757 |
|
| 758 |
if self.module.params["folder"]: |
| 759 |
self.xapi_session.xenapi.VM.add_to_other_config( |
| 760 |
self.vm_ref, "folder", self.module.params["folder"] |
| 761 |
) |
| 762 |
elif change == "home_server": |
| 763 |
if self.module.params["home_server"]: |
| 764 |
host_ref = self.xapi_session.xenapi.host.get_by_name_label( |
| 765 |
self.module.params["home_server"] |
| 766 |
)[0] |
| 767 |
else: |
| 768 |
host_ref = "OpaqueRef:NULL" |
| 769 |
|
| 770 |
self.xapi_session.xenapi.VM.set_affinity(self.vm_ref, host_ref) |
| 771 |
elif isinstance(change, dict): |
| 772 |
if change.get("hardware"): |
| 773 |
for hardware_change in change["hardware"]: |
| 774 |
if hardware_change == "num_cpus": |
| 775 |
num_cpus = int(self.module.params["hardware"]["num_cpus"]) |
| 776 |
|
| 777 |
if num_cpus < int(self.vm_params["VCPUs_at_startup"]): |
| 778 |
self.xapi_session.xenapi.VM.set_VCPUs_at_startup(self.vm_ref, str(num_cpus)) |
| 779 |
self.xapi_session.xenapi.VM.set_VCPUs_max(self.vm_ref, str(num_cpus)) |
| 780 |
else: |
| 781 |
self.xapi_session.xenapi.VM.set_VCPUs_max(self.vm_ref, str(num_cpus)) |
| 782 |
self.xapi_session.xenapi.VM.set_VCPUs_at_startup(self.vm_ref, str(num_cpus)) |
| 783 |
elif hardware_change == "num_cpu_cores_per_socket": |
| 784 |
self.xapi_session.xenapi.VM.remove_from_platform(self.vm_ref, "cores-per-socket") |
| 785 |
num_cpu_cores_per_socket = int( |
| 786 |
self.module.params["hardware"]["num_cpu_cores_per_socket"] |
| 787 |
) |
| 788 |
|
| 789 |
if num_cpu_cores_per_socket > 1: |
| 790 |
self.xapi_session.xenapi.VM.add_to_platform( |
| 791 |
self.vm_ref, "cores-per-socket", str(num_cpu_cores_per_socket) |
| 792 |
) |
| 793 |
elif hardware_change == "memory_mb": |
| 794 |
memory_b = str(int(self.module.params["hardware"]["memory_mb"]) * 1048576) |
| 795 |
vm_memory_static_min_b = str( |
| 796 |
min(int(memory_b), int(self.vm_params["memory_static_min"])) |
| 797 |
) |
| 798 |
|
| 799 |
self.xapi_session.xenapi.VM.set_memory_limits( |
| 800 |
self.vm_ref, vm_memory_static_min_b, memory_b, memory_b, memory_b |
| 801 |
) |
| 802 |
|
| 803 |
elif change.get("cdrom"): |
| 804 |
vm_cdrom_params_list = [ |
| 805 |
cdrom_params for cdrom_params in self.vm_params["VBDs"] if cdrom_params["type"] == "CD" |
| 806 |
] |
| 807 |
|
| 808 |
# If there is no CD present, we have to create one. |
| 809 |
if not vm_cdrom_params_list: |
| 810 |
# We will try to place cdrom at userdevice position |
| 811 |
# 3 (which is default) if it is not already occupied |
| 812 |
# else we will place it at first allowed position. |
| 813 |
cdrom_userdevices_allowed = self.xapi_session.xenapi.VM.get_allowed_VBD_devices(self.vm_ref) |
| 814 |
|
| 815 |
if "3" in cdrom_userdevices_allowed: |
| 816 |
cdrom_userdevice = "3" |
| 817 |
else: |
| 818 |
cdrom_userdevice = cdrom_userdevices_allowed[0] |
| 819 |
|
| 820 |
cdrom_vbd = { |
| 821 |
"VM": self.vm_ref, |
| 822 |
"VDI": "OpaqueRef:NULL", |
| 823 |
"userdevice": cdrom_userdevice, |
| 824 |
"bootable": False, |
| 825 |
"mode": "RO", |
| 826 |
"type": "CD", |
| 827 |
"empty": True, |
| 828 |
"other_config": {}, |
| 829 |
"qos_algorithm_type": "", |
| 830 |
"qos_algorithm_params": {}, |
| 831 |
} |
| 832 |
|
| 833 |
cdrom_vbd_ref = self.xapi_session.xenapi.VBD.create(cdrom_vbd) |
| 834 |
else: |
| 835 |
cdrom_vbd_ref = self.xapi_session.xenapi.VBD.get_by_uuid(vm_cdrom_params_list[0]["uuid"]) |
| 836 |
|
| 837 |
cdrom_is_empty = self.xapi_session.xenapi.VBD.get_empty(cdrom_vbd_ref) |
| 838 |
|
| 839 |
for cdrom_change in change["cdrom"]: |
| 840 |
if cdrom_change == "type": |
| 841 |
cdrom_type = self.module.params["cdrom"]["type"] |
| 842 |
|
| 843 |
if cdrom_type == "none" and not cdrom_is_empty: |
| 844 |
self.xapi_session.xenapi.VBD.eject(cdrom_vbd_ref) |
| 845 |
elif cdrom_type == "host": |
| 846 |
# Unimplemented! |
| 847 |
pass |
| 848 |
|
| 849 |
elif cdrom_change == "iso_name": |
| 850 |
if not cdrom_is_empty: |
| 851 |
self.xapi_session.xenapi.VBD.eject(cdrom_vbd_ref) |
| 852 |
|
| 853 |
cdrom_vdi_ref = self.xapi_session.xenapi.VDI.get_by_name_label( |
| 854 |
self.module.params["cdrom"]["iso_name"] |
| 855 |
)[0] |
| 856 |
self.xapi_session.xenapi.VBD.insert(cdrom_vbd_ref, cdrom_vdi_ref) |
| 857 |
|
| 858 |
elif change.get("disks_changed"): |
| 859 |
vm_disk_params_list = [ |
| 860 |
disk_params for disk_params in self.vm_params["VBDs"] if disk_params["type"] == "Disk" |
| 861 |
] |
| 862 |
|
| 863 |
for position, disk_change_list in enumerate(change["disks_changed"]): |
| 864 |
for disk_change in disk_change_list: |
| 865 |
vdi_ref = self.xapi_session.xenapi.VDI.get_by_uuid( |
| 866 |
vm_disk_params_list[position]["VDI"]["uuid"] |
| 867 |
) |
| 868 |
|
| 869 |
if disk_change == "name": |
| 870 |
self.xapi_session.xenapi.VDI.set_name_label( |
| 871 |
vdi_ref, self.module.params["disks"][position]["name"] |
| 872 |
) |
| 873 |
elif disk_change == "name_desc": |
| 874 |
self.xapi_session.xenapi.VDI.set_name_description( |
| 875 |
vdi_ref, self.module.params["disks"][position]["name_desc"] |
| 876 |
) |
| 877 |
elif disk_change == "size": |
| 878 |
self.xapi_session.xenapi.VDI.resize( |
| 879 |
vdi_ref, |
| 880 |
str( |
| 881 |
self.get_normalized_disk_size( |
| 882 |
self.module.params["disks"][position], |
| 883 |
f"VM reconfigure disks[{position}]: ", |
| 884 |
) |
| 885 |
), |
| 886 |
) |
| 887 |
|
| 888 |
elif change.get("disks_new"): |
| 889 |
for position, disk_userdevice in change["disks_new"]: |
| 890 |
disk_params = self.module.params["disks"][position] |
| 891 |
|
| 892 |
disk_name = ( |
| 893 |
disk_params["name"] |
| 894 |
if disk_params.get("name") |
| 895 |
else f"{self.vm_params['name_label']}-{position}" |
| 896 |
) |
| 897 |
disk_name_desc = disk_params["name_desc"] if disk_params.get("name_desc") else "" |
| 898 |
|
| 899 |
if disk_params.get("sr_uuid"): |
| 900 |
sr_ref = self.xapi_session.xenapi.SR.get_by_uuid(disk_params["sr_uuid"]) |
| 901 |
elif disk_params.get("sr"): |
| 902 |
sr_ref = self.xapi_session.xenapi.SR.get_by_name_label(disk_params["sr"])[0] |
| 903 |
else: |
| 904 |
sr_ref = self.default_sr_ref |
| 905 |
|
| 906 |
disk_size = str( |
| 907 |
self.get_normalized_disk_size( |
| 908 |
self.module.params["disks"][position], f"VM reconfigure disks[{position}]: " |
| 909 |
) |
| 910 |
) |
| 911 |
|
| 912 |
new_disk_vdi = { |
| 913 |
"name_label": disk_name, |
| 914 |
"name_description": disk_name_desc, |
| 915 |
"SR": sr_ref, |
| 916 |
"virtual_size": disk_size, |
| 917 |
"type": "user", |
| 918 |
"sharable": False, |
| 919 |
"read_only": False, |
| 920 |
"other_config": {}, |
| 921 |
} |
| 922 |
|
| 923 |
new_disk_vbd = { |
| 924 |
"VM": self.vm_ref, |
| 925 |
"VDI": None, |
| 926 |
"userdevice": disk_userdevice, |
| 927 |
"bootable": False, |
| 928 |
"mode": "RW", |
| 929 |
"type": "Disk", |
| 930 |
"empty": False, |
| 931 |
"other_config": {}, |
| 932 |
"qos_algorithm_type": "", |
| 933 |
"qos_algorithm_params": {}, |
| 934 |
} |
| 935 |
|
| 936 |
new_disk_vbd["VDI"] = self.xapi_session.xenapi.VDI.create(new_disk_vdi) |
| 937 |
vbd_ref_new = self.xapi_session.xenapi.VBD.create(new_disk_vbd) |
| 938 |
|
| 939 |
if self.vm_params["power_state"].lower() == "running": |
| 940 |
self.xapi_session.xenapi.VBD.plug(vbd_ref_new) |
| 941 |
|
| 942 |
elif change.get("networks_changed"): |
| 943 |
for position, network_change_list in enumerate(change["networks_changed"]): |
| 944 |
if network_change_list: |
| 945 |
vm_vif_params = self.vm_params["VIFs"][position] |
| 946 |
network_params = self.module.params["networks"][position] |
| 947 |
|
| 948 |
vif_ref = self.xapi_session.xenapi.VIF.get_by_uuid(vm_vif_params["uuid"]) |
| 949 |
network_ref = self.xapi_session.xenapi.network.get_by_uuid( |
| 950 |
vm_vif_params["network"]["uuid"] |
| 951 |
) |
| 952 |
|
| 953 |
vif_recreated = False |
| 954 |
|
| 955 |
if "name" in network_change_list or "mac" in network_change_list: |
| 956 |
# To change network or MAC, we destroy old |
| 957 |
# VIF and then create a new one with changed |
| 958 |
# parameters. That's how XenCenter does it. |
| 959 |
|
| 960 |
# Copy all old parameters to new VIF record. |
| 961 |
vif = { |
| 962 |
"device": vm_vif_params["device"], |
| 963 |
"network": network_ref, |
| 964 |
"VM": vm_vif_params["VM"], |
| 965 |
"MAC": vm_vif_params["MAC"], |
| 966 |
"MTU": vm_vif_params["MTU"], |
| 967 |
"other_config": vm_vif_params["other_config"], |
| 968 |
"qos_algorithm_type": vm_vif_params["qos_algorithm_type"], |
| 969 |
"qos_algorithm_params": vm_vif_params["qos_algorithm_params"], |
| 970 |
"locking_mode": vm_vif_params["locking_mode"], |
| 971 |
"ipv4_allowed": vm_vif_params["ipv4_allowed"], |
| 972 |
"ipv6_allowed": vm_vif_params["ipv6_allowed"], |
| 973 |
} |
| 974 |
|
| 975 |
if "name" in network_change_list: |
| 976 |
network_ref_new = self.xapi_session.xenapi.network.get_by_name_label( |
| 977 |
network_params["name"] |
| 978 |
)[0] |
| 979 |
vif["network"] = network_ref_new |
| 980 |
vif["MTU"] = self.xapi_session.xenapi.network.get_MTU(network_ref_new) |
| 981 |
|
| 982 |
if "mac" in network_change_list: |
| 983 |
vif["MAC"] = network_params["mac"].lower() |
| 984 |
|
| 985 |
if self.vm_params["power_state"].lower() == "running": |
| 986 |
self.xapi_session.xenapi.VIF.unplug(vif_ref) |
| 987 |
|
| 988 |
self.xapi_session.xenapi.VIF.destroy(vif_ref) |
| 989 |
vif_ref_new = self.xapi_session.xenapi.VIF.create(vif) |
| 990 |
|
| 991 |
if self.vm_params["power_state"].lower() == "running": |
| 992 |
self.xapi_session.xenapi.VIF.plug(vif_ref_new) |
| 993 |
|
| 994 |
vif_ref = vif_ref_new |
| 995 |
vif_recreated = True |
| 996 |
|
| 997 |
if self.vm_params["customization_agent"] == "native": |
| 998 |
vif_reconfigure_needed = False |
| 999 |
|
| 1000 |
if "type" in network_change_list: |
| 1001 |
network_type = network_params["type"].capitalize() |
| 1002 |
vif_reconfigure_needed = True |
| 1003 |
else: |
| 1004 |
network_type = vm_vif_params["ipv4_configuration_mode"] |
| 1005 |
|
| 1006 |
if "ip" in network_change_list: |
| 1007 |
network_ip = network_params["ip"] |
| 1008 |
vif_reconfigure_needed = True |
| 1009 |
elif vm_vif_params["ipv4_addresses"]: |
| 1010 |
network_ip = vm_vif_params["ipv4_addresses"][0].split("/")[0] |
| 1011 |
else: |
| 1012 |
network_ip = "" |
| 1013 |
|
| 1014 |
if "prefix" in network_change_list: |
| 1015 |
network_prefix = f"/{network_params['prefix']}" |
| 1016 |
vif_reconfigure_needed = True |
| 1017 |
elif vm_vif_params["ipv4_addresses"] and vm_vif_params["ipv4_addresses"][0]: |
| 1018 |
network_prefix = f"/{vm_vif_params['ipv4_addresses'][0].split('/')[1]}" |
| 1019 |
else: |
| 1020 |
network_prefix = "" |
| 1021 |
|
| 1022 |
if "gateway" in network_change_list: |
| 1023 |
network_gateway = network_params["gateway"] |
| 1024 |
vif_reconfigure_needed = True |
| 1025 |
else: |
| 1026 |
network_gateway = vm_vif_params["ipv4_gateway"] |
| 1027 |
|
| 1028 |
if vif_recreated or vif_reconfigure_needed: |
| 1029 |
self.xapi_session.xenapi.VIF.configure_ipv4( |
| 1030 |
vif_ref, network_type, f"{network_ip}{network_prefix}", network_gateway |
| 1031 |
) |
| 1032 |
|
| 1033 |
vif_reconfigure_needed = False |
| 1034 |
|
| 1035 |
if "type6" in network_change_list: |
| 1036 |
network_type6 = network_params["type6"].capitalize() |
| 1037 |
vif_reconfigure_needed = True |
| 1038 |
else: |
| 1039 |
network_type6 = vm_vif_params["ipv6_configuration_mode"] |
| 1040 |
|
| 1041 |
if "ip6" in network_change_list: |
| 1042 |
network_ip6 = network_params["ip6"] |
| 1043 |
vif_reconfigure_needed = True |
| 1044 |
elif vm_vif_params["ipv6_addresses"]: |
| 1045 |
network_ip6 = vm_vif_params["ipv6_addresses"][0].split("/")[0] |
| 1046 |
else: |
| 1047 |
network_ip6 = "" |
| 1048 |
|
| 1049 |
if "prefix6" in network_change_list: |
| 1050 |
network_prefix6 = f"/{network_params['prefix6']}" |
| 1051 |
vif_reconfigure_needed = True |
| 1052 |
elif vm_vif_params["ipv6_addresses"] and vm_vif_params["ipv6_addresses"][0]: |
| 1053 |
network_prefix6 = f"/{vm_vif_params['ipv6_addresses'][0].split('/')[1]}" |
| 1054 |
else: |
| 1055 |
network_prefix6 = "" |
| 1056 |
|
| 1057 |
if "gateway6" in network_change_list: |
| 1058 |
network_gateway6 = network_params["gateway6"] |
| 1059 |
vif_reconfigure_needed = True |
| 1060 |
else: |
| 1061 |
network_gateway6 = vm_vif_params["ipv6_gateway"] |
| 1062 |
|
| 1063 |
if vif_recreated or vif_reconfigure_needed: |
| 1064 |
self.xapi_session.xenapi.VIF.configure_ipv6( |
| 1065 |
vif_ref, network_type6, f"{network_ip6}{network_prefix6}", network_gateway6 |
| 1066 |
) |
| 1067 |
|
| 1068 |
elif self.vm_params["customization_agent"] == "custom": |
| 1069 |
vif_device = vm_vif_params["device"] |
| 1070 |
|
| 1071 |
# A user could have manually changed network |
| 1072 |
# or mac e.g. through XenCenter and then also |
| 1073 |
# make those changes in playbook manually. |
| 1074 |
# In that case, module will not detect any |
| 1075 |
# changes and info in xenstore_data will |
| 1076 |
# become stale. For that reason we always |
| 1077 |
# update name and mac in xenstore_data. |
| 1078 |
|
| 1079 |
# Since we handle name and mac differently, |
| 1080 |
# we have to remove them from |
| 1081 |
# network_change_list. |
| 1082 |
network_change_list_tmp = [ |
| 1083 |
net_chg for net_chg in network_change_list if net_chg not in ["name", "mac"] |
| 1084 |
] |
| 1085 |
|
| 1086 |
for network_change in network_change_list_tmp + ["name", "mac"]: |
| 1087 |
self.xapi_session.xenapi.VM.remove_from_xenstore_data( |
| 1088 |
self.vm_ref, f"vm-data/networks/{vif_device}/{network_change}" |
| 1089 |
) |
| 1090 |
|
| 1091 |
if network_params.get("name"): |
| 1092 |
network_name = network_params["name"] |
| 1093 |
else: |
| 1094 |
network_name = vm_vif_params["network"]["name_label"] |
| 1095 |
|
| 1096 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1097 |
self.vm_ref, f"vm-data/networks/{vif_device}/name", network_name |
| 1098 |
) |
| 1099 |
|
| 1100 |
if network_params.get("mac"): |
| 1101 |
network_mac = network_params["mac"].lower() |
| 1102 |
else: |
| 1103 |
network_mac = vm_vif_params["MAC"].lower() |
| 1104 |
|
| 1105 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1106 |
self.vm_ref, f"vm-data/networks/{vif_device}/mac", network_mac |
| 1107 |
) |
| 1108 |
|
| 1109 |
for network_change in network_change_list_tmp: |
| 1110 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1111 |
self.vm_ref, |
| 1112 |
f"vm-data/networks/{vif_device}/{network_change}", |
| 1113 |
network_params[network_change], |
| 1114 |
) |
| 1115 |
|
| 1116 |
elif change.get("networks_new"): |
| 1117 |
for position, vif_device in change["networks_new"]: |
| 1118 |
network_params = self.module.params["networks"][position] |
| 1119 |
|
| 1120 |
network_ref = self.xapi_session.xenapi.network.get_by_name_label(network_params["name"])[0] |
| 1121 |
|
| 1122 |
network_name = network_params["name"] |
| 1123 |
network_mac = network_params["mac"] if network_params.get("mac") else "" |
| 1124 |
network_type = network_params.get("type") |
| 1125 |
network_ip = network_params["ip"] if network_params.get("ip") else "" |
| 1126 |
network_prefix = network_params["prefix"] if network_params.get("prefix") else "" |
| 1127 |
network_netmask = network_params["netmask"] if network_params.get("netmask") else "" |
| 1128 |
network_gateway = network_params["gateway"] if network_params.get("gateway") else "" |
| 1129 |
network_type6 = network_params.get("type6") |
| 1130 |
network_ip6 = network_params["ip6"] if network_params.get("ip6") else "" |
| 1131 |
network_prefix6 = network_params["prefix6"] if network_params.get("prefix6") else "" |
| 1132 |
network_gateway6 = network_params["gateway6"] if network_params.get("gateway6") else "" |
| 1133 |
|
| 1134 |
vif = { |
| 1135 |
"device": vif_device, |
| 1136 |
"network": network_ref, |
| 1137 |
"VM": self.vm_ref, |
| 1138 |
"MAC": network_mac, |
| 1139 |
"MTU": self.xapi_session.xenapi.network.get_MTU(network_ref), |
| 1140 |
"other_config": {}, |
| 1141 |
"qos_algorithm_type": "", |
| 1142 |
"qos_algorithm_params": {}, |
| 1143 |
} |
| 1144 |
|
| 1145 |
vif_ref_new = self.xapi_session.xenapi.VIF.create(vif) |
| 1146 |
|
| 1147 |
if self.vm_params["power_state"].lower() == "running": |
| 1148 |
self.xapi_session.xenapi.VIF.plug(vif_ref_new) |
| 1149 |
|
| 1150 |
if self.vm_params["customization_agent"] == "native": |
| 1151 |
if network_type and network_type == "static": |
| 1152 |
self.xapi_session.xenapi.VIF.configure_ipv4( |
| 1153 |
vif_ref_new, "Static", f"{network_ip}/{network_prefix}", network_gateway |
| 1154 |
) |
| 1155 |
|
| 1156 |
if network_type6 and network_type6 == "static": |
| 1157 |
self.xapi_session.xenapi.VIF.configure_ipv6( |
| 1158 |
vif_ref_new, "Static", f"{network_ip6}/{network_prefix6}", network_gateway6 |
| 1159 |
) |
| 1160 |
elif self.vm_params["customization_agent"] == "custom": |
| 1161 |
# We first have to remove any existing data |
| 1162 |
# from xenstore_data because there could be |
| 1163 |
# some old leftover data from some interface |
| 1164 |
# that once occupied same device location as |
| 1165 |
# our new interface. |
| 1166 |
for network_param in [ |
| 1167 |
"name", |
| 1168 |
"mac", |
| 1169 |
"type", |
| 1170 |
"ip", |
| 1171 |
"prefix", |
| 1172 |
"netmask", |
| 1173 |
"gateway", |
| 1174 |
"type6", |
| 1175 |
"ip6", |
| 1176 |
"prefix6", |
| 1177 |
"gateway6", |
| 1178 |
]: |
| 1179 |
self.xapi_session.xenapi.VM.remove_from_xenstore_data( |
| 1180 |
self.vm_ref, f"vm-data/networks/{vif_device}/{network_param}" |
| 1181 |
) |
| 1182 |
|
| 1183 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1184 |
self.vm_ref, f"vm-data/networks/{vif_device}/name", network_name |
| 1185 |
) |
| 1186 |
|
| 1187 |
# We get MAC from VIF itself instead of |
| 1188 |
# networks.mac because it could be |
| 1189 |
# autogenerated. |
| 1190 |
vm_vif_mac = self.xapi_session.xenapi.VIF.get_MAC(vif_ref_new) |
| 1191 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1192 |
self.vm_ref, f"vm-data/networks/{vif_device}/mac", vm_vif_mac |
| 1193 |
) |
| 1194 |
|
| 1195 |
if network_type: |
| 1196 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1197 |
self.vm_ref, f"vm-data/networks/{vif_device}/type", network_type |
| 1198 |
) |
| 1199 |
|
| 1200 |
if network_type == "static": |
| 1201 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1202 |
self.vm_ref, f"vm-data/networks/{vif_device}/ip", network_ip |
| 1203 |
) |
| 1204 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1205 |
self.vm_ref, f"vm-data/networks/{vif_device}/prefix", network_prefix |
| 1206 |
) |
| 1207 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1208 |
self.vm_ref, f"vm-data/networks/{vif_device}/netmask", network_netmask |
| 1209 |
) |
| 1210 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1211 |
self.vm_ref, f"vm-data/networks/{vif_device}/gateway", network_gateway |
| 1212 |
) |
| 1213 |
|
| 1214 |
if network_type6: |
| 1215 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1216 |
self.vm_ref, f"vm-data/networks/{vif_device}/type6", network_type6 |
| 1217 |
) |
| 1218 |
|
| 1219 |
if network_type6 == "static": |
| 1220 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1221 |
self.vm_ref, f"vm-data/networks/{vif_device}/ip6", network_ip6 |
| 1222 |
) |
| 1223 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1224 |
self.vm_ref, f"vm-data/networks/{vif_device}/prefix6", network_prefix6 |
| 1225 |
) |
| 1226 |
self.xapi_session.xenapi.VM.add_to_xenstore_data( |
| 1227 |
self.vm_ref, f"vm-data/networks/{vif_device}/gateway6", network_gateway6 |
| 1228 |
) |
| 1229 |
|
| 1230 |
elif change.get("custom_params"): |
| 1231 |
for position in change["custom_params"]: |
| 1232 |
custom_param_key = self.module.params["custom_params"][position]["key"] |
| 1233 |
custom_param_value = self.module.params["custom_params"][position]["value"] |
| 1234 |
self.xapi_session.xenapi_request( |
| 1235 |
f"VM.set_{custom_param_key}", (self.vm_ref, custom_param_value) |
| 1236 |
) |
| 1237 |
|
| 1238 |
if self.module.params["is_template"]: |
| 1239 |
self.xapi_session.xenapi.VM.set_is_a_template(self.vm_ref, True) |
| 1240 |
elif ( |
| 1241 |
"need_poweredoff" in config_changes and self.module.params["force"] and vm_power_state_save != "halted" |
| 1242 |
): |
| 1243 |
self.set_power_state("poweredon") |
| 1244 |
|
| 1245 |
# Gather new params after reconfiguration. |
| 1246 |
self.gather_params() |
| 1247 |
|
| 1248 |
except XenAPI.Failure as f: |
| 1249 |
self.module.fail_json(msg=f"XAPI ERROR: {f.details}") |
| 1250 |
|
| 1251 |
return config_changes |
| 1252 |
|
| 1253 |
def destroy(self): |
| 1254 |
"""Removes an existing VM with associated disks""" |
| 1255 |
# Safety check. |
| 1256 |
if not self.exists(): |
| 1257 |
self.module.fail_json(msg="Called destroy on non existing VM!") |
| 1258 |
|
| 1259 |
if self.vm_params["power_state"].lower() != "halted" and not self.module.params["force"]: |
| 1260 |
self.module.fail_json( |
| 1261 |
msg="VM destroy: VM has to be in powered off state to destroy but force was not specified!" |
| 1262 |
) |
| 1263 |
|
| 1264 |
# Support for Ansible check mode. |
| 1265 |
if self.module.check_mode: |
| 1266 |
return |
| 1267 |
|
| 1268 |
# Make sure that VM is poweredoff before we can destroy it. |
| 1269 |
self.set_power_state("poweredoff") |
| 1270 |
|
| 1271 |
try: |
| 1272 |
# Destroy VM! |
| 1273 |
self.xapi_session.xenapi.VM.destroy(self.vm_ref) |
| 1274 |
|
| 1275 |
vm_disk_params_list = [ |
| 1276 |
disk_params for disk_params in self.vm_params["VBDs"] if disk_params["type"] == "Disk" |
| 1277 |
] |
| 1278 |
|
| 1279 |
# Destroy all VDIs associated with VM! |
| 1280 |
for vm_disk_params in vm_disk_params_list: |
| 1281 |
vdi_ref = self.xapi_session.xenapi.VDI.get_by_uuid(vm_disk_params["VDI"]["uuid"]) |
| 1282 |
|
| 1283 |
self.xapi_session.xenapi.VDI.destroy(vdi_ref) |
| 1284 |
|
| 1285 |
except XenAPI.Failure as f: |
| 1286 |
self.module.fail_json(msg=f"XAPI ERROR: {f.details}") |
| 1287 |
|
| 1288 |
def get_changes(self): |
| 1289 |
"""Finds VM parameters that differ from specified ones. |
| 1290 |
|
| 1291 |
This method builds a dictionary with hierarchy of VM parameters |
| 1292 |
that differ from those specified in module parameters. |
| 1293 |
|
| 1294 |
Returns: |
| 1295 |
list: VM parameters that differ from those specified in |
| 1296 |
module parameters. |
| 1297 |
""" |
| 1298 |
# Safety check. |
| 1299 |
if not self.exists(): |
| 1300 |
self.module.fail_json(msg="Called get_changes on non existing VM!") |
| 1301 |
|
| 1302 |
need_poweredoff = False |
| 1303 |
|
| 1304 |
if self.module.params["is_template"]: |
| 1305 |
need_poweredoff = True |
| 1306 |
|
| 1307 |
try: |
| 1308 |
# This VM could be a template or a snapshot. In that case we fail |
| 1309 |
# because we can't reconfigure them or it would just be too |
| 1310 |
# dangerous. |
| 1311 |
if self.vm_params["is_a_template"] and not self.vm_params["is_a_snapshot"]: |
| 1312 |
self.module.fail_json( |
| 1313 |
msg="VM check: targeted VM is a template! Template reconfiguration is not supported." |
| 1314 |
) |
| 1315 |
|
| 1316 |
if self.vm_params["is_a_snapshot"]: |
| 1317 |
self.module.fail_json( |
| 1318 |
msg="VM check: targeted VM is a snapshot! Snapshot reconfiguration is not supported." |
| 1319 |
) |
| 1320 |
|
| 1321 |
# Let's build a list of parameters that changed. |
| 1322 |
config_changes = [] |
| 1323 |
|
| 1324 |
# Name could only differ if we found an existing VM by uuid. |
| 1325 |
if self.module.params["name"] is not None and self.module.params["name"] != self.vm_params["name_label"]: |
| 1326 |
if self.module.params["name"]: |
| 1327 |
config_changes.append("name") |
| 1328 |
else: |
| 1329 |
self.module.fail_json(msg="VM check name: VM name cannot be an empty string!") |
| 1330 |
|
| 1331 |
if ( |
| 1332 |
self.module.params["name_desc"] is not None |
| 1333 |
and self.module.params["name_desc"] != self.vm_params["name_description"] |
| 1334 |
): |
| 1335 |
config_changes.append("name_desc") |
| 1336 |
|
| 1337 |
# Folder parameter is found in other_config. |
| 1338 |
vm_other_config = self.vm_params["other_config"] |
| 1339 |
vm_folder = vm_other_config.get("folder", "") |
| 1340 |
|
| 1341 |
if self.module.params["folder"] is not None and self.module.params["folder"] != vm_folder: |
| 1342 |
config_changes.append("folder") |
| 1343 |
|
| 1344 |
if self.module.params["home_server"] is not None: |
| 1345 |
if self.module.params["home_server"] and ( |
| 1346 |
not self.vm_params["affinity"] |
| 1347 |
or self.module.params["home_server"] != self.vm_params["affinity"]["name_label"] |
| 1348 |
): |
| 1349 |
# Check existence only. Ignore return value. |
| 1350 |
get_object_ref( |
| 1351 |
self.module, |
| 1352 |
self.module.params["home_server"], |
| 1353 |
uuid=None, |
| 1354 |
obj_type="home server", |
| 1355 |
fail=True, |
| 1356 |
msg_prefix="VM check home_server: ", |
| 1357 |
) |
| 1358 |
|
| 1359 |
config_changes.append("home_server") |
| 1360 |
elif not self.module.params["home_server"] and self.vm_params["affinity"]: |
| 1361 |
config_changes.append("home_server") |
| 1362 |
|
| 1363 |
config_changes_hardware = [] |
| 1364 |
|
| 1365 |
if self.module.params["hardware"]: |
| 1366 |
num_cpus = self.module.params["hardware"].get("num_cpus") |
| 1367 |
|
| 1368 |
if num_cpus is not None: |
| 1369 |
# Kept for compatibility with older Ansible versions that |
| 1370 |
# do not support subargument specs. |
| 1371 |
try: |
| 1372 |
num_cpus = int(num_cpus) |
| 1373 |
except ValueError: |
| 1374 |
self.module.fail_json(msg="VM check hardware.num_cpus: parameter should be an integer value!") |
| 1375 |
|
| 1376 |
if num_cpus < 1: |
| 1377 |
self.module.fail_json(msg="VM check hardware.num_cpus: parameter should be greater than zero!") |
| 1378 |
|
| 1379 |
# We can use VCPUs_at_startup or VCPUs_max parameter. I'd |
| 1380 |
# say the former is the way to go but this needs |
| 1381 |
# confirmation and testing. |
| 1382 |
if num_cpus != int(self.vm_params["VCPUs_at_startup"]): |
| 1383 |
config_changes_hardware.append("num_cpus") |
| 1384 |
# For now, we don't support hotpluging so VM has to be in |
| 1385 |
# poweredoff state to reconfigure. |
| 1386 |
need_poweredoff = True |
| 1387 |
|
| 1388 |
num_cpu_cores_per_socket = self.module.params["hardware"].get("num_cpu_cores_per_socket") |
| 1389 |
|
| 1390 |
if num_cpu_cores_per_socket is not None: |
| 1391 |
# Kept for compatibility with older Ansible versions that |
| 1392 |
# do not support subargument specs. |
| 1393 |
try: |
| 1394 |
num_cpu_cores_per_socket = int(num_cpu_cores_per_socket) |
| 1395 |
except ValueError: |
| 1396 |
self.module.fail_json( |
| 1397 |
msg="VM check hardware.num_cpu_cores_per_socket: parameter should be an integer value!" |
| 1398 |
) |
| 1399 |
|
| 1400 |
if num_cpu_cores_per_socket < 1: |
| 1401 |
self.module.fail_json( |
| 1402 |
msg="VM check hardware.num_cpu_cores_per_socket: parameter should be greater than zero!" |
| 1403 |
) |
| 1404 |
|
| 1405 |
if num_cpus and num_cpus % num_cpu_cores_per_socket != 0: |
| 1406 |
self.module.fail_json( |
| 1407 |
msg="VM check hardware.num_cpus: parameter should be a multiple of hardware.num_cpu_cores_per_socket!" |
| 1408 |
) |
| 1409 |
|
| 1410 |
vm_platform = self.vm_params["platform"] |
| 1411 |
vm_cores_per_socket = int(vm_platform.get("cores-per-socket", 1)) |
| 1412 |
|
| 1413 |
if num_cpu_cores_per_socket != vm_cores_per_socket: |
| 1414 |
config_changes_hardware.append("num_cpu_cores_per_socket") |
| 1415 |
# For now, we don't support hotpluging so VM has to be |
| 1416 |
# in poweredoff state to reconfigure. |
| 1417 |
need_poweredoff = True |
| 1418 |
|
| 1419 |
memory_mb = self.module.params["hardware"].get("memory_mb") |
| 1420 |
|
| 1421 |
if memory_mb is not None: |
| 1422 |
# Kept for compatibility with older Ansible versions that |
| 1423 |
# do not support subargument specs. |
| 1424 |
try: |
| 1425 |
memory_mb = int(memory_mb) |
| 1426 |
except ValueError: |
| 1427 |
self.module.fail_json(msg="VM check hardware.memory_mb: parameter should be an integer value!") |
| 1428 |
|
| 1429 |
if memory_mb < 1: |
| 1430 |
self.module.fail_json(msg="VM check hardware.memory_mb: parameter should be greater than zero!") |
| 1431 |
|
| 1432 |
# There are multiple memory parameters: |
| 1433 |
# - memory_dynamic_max |
| 1434 |
# - memory_dynamic_min |
| 1435 |
# - memory_static_max |
| 1436 |
# - memory_static_min |
| 1437 |
# - memory_target |
| 1438 |
# |
| 1439 |
# memory_target seems like a good candidate but it returns 0 for |
| 1440 |
# halted VMs so we can't use it. |
| 1441 |
# |
| 1442 |
# I decided to use memory_dynamic_max and memory_static_max |
| 1443 |
# and use whichever is larger. This strategy needs validation |
| 1444 |
# and testing. |
| 1445 |
# |
| 1446 |
# XenServer stores memory size in bytes so we need to divide |
| 1447 |
# it by 1024*1024 = 1048576. |
| 1448 |
if memory_mb != int( |
| 1449 |
max(int(self.vm_params["memory_dynamic_max"]), int(self.vm_params["memory_static_max"])) |
| 1450 |
/ 1048576 |
| 1451 |
): |
| 1452 |
config_changes_hardware.append("memory_mb") |
| 1453 |
# For now, we don't support hotpluging so VM has to be in |
| 1454 |
# poweredoff state to reconfigure. |
| 1455 |
need_poweredoff = True |
| 1456 |
|
| 1457 |
if config_changes_hardware: |
| 1458 |
config_changes.append({"hardware": config_changes_hardware}) |
| 1459 |
|
| 1460 |
# Find allowed userdevices. |
| 1461 |
vbd_userdevices_allowed = self.xapi_session.xenapi.VM.get_allowed_VBD_devices(self.vm_ref) |
| 1462 |
|
| 1463 |
config_changes_cdrom = [] |
| 1464 |
|
| 1465 |
if self.module.params["cdrom"]: |
| 1466 |
# Get the list of all CD-ROMs. Filter out any regular disks |
| 1467 |
# found. If we found no existing CD-ROM, we will create it |
| 1468 |
# later else take the first one found. |
| 1469 |
vm_cdrom_params_list = [ |
| 1470 |
cdrom_params for cdrom_params in self.vm_params["VBDs"] if cdrom_params["type"] == "CD" |
| 1471 |
] |
| 1472 |
|
| 1473 |
# If no existing CD-ROM is found, we will need to add one. |
| 1474 |
if not vm_cdrom_params_list: |
| 1475 |
# We need to check if there is any userdevice allowed. |
| 1476 |
if not vbd_userdevices_allowed: |
| 1477 |
self.module.fail_json(msg="VM check cdrom: maximum number of devices reached!") |
| 1478 |
|
| 1479 |
# If userdevice position 3 is available, we reserve it for |
| 1480 |
# CD-ROM to prevent any disk taking the same position. If the |
| 1481 |
# position 3 is not available, we reserve the first available |
| 1482 |
# one to prevent any disk from taking it. |
| 1483 |
if "3" in vbd_userdevices_allowed: |
| 1484 |
vbd_userdevices_allowed.remove("3") |
| 1485 |
else: |
| 1486 |
vbd_userdevices_allowed.pop(0) |
| 1487 |
|
| 1488 |
cdrom_type = self.module.params["cdrom"].get("type") |
| 1489 |
cdrom_iso_name = self.module.params["cdrom"].get("iso_name") |
| 1490 |
|
| 1491 |
# If cdrom.iso_name is specified but cdrom.type is not, |
| 1492 |
# then set cdrom.type to 'iso', unless cdrom.iso_name is |
| 1493 |
# an empty string, in that case set cdrom.type to 'none'. |
| 1494 |
if not cdrom_type: |
| 1495 |
if cdrom_iso_name: |
| 1496 |
cdrom_type = "iso" |
| 1497 |
elif cdrom_iso_name is not None: |
| 1498 |
cdrom_type = "none" |
| 1499 |
|
| 1500 |
self.module.params["cdrom"]["type"] = cdrom_type |
| 1501 |
|
| 1502 |
# If type changed. |
| 1503 |
if cdrom_type and ( |
| 1504 |
not vm_cdrom_params_list or cdrom_type != self.get_cdrom_type(vm_cdrom_params_list[0]) |
| 1505 |
): |
| 1506 |
config_changes_cdrom.append("type") |
| 1507 |
|
| 1508 |
if cdrom_type == "iso": |
| 1509 |
# Check if ISO exists. |
| 1510 |
# Check existence only. Ignore return value. |
| 1511 |
get_object_ref( |
| 1512 |
self.module, |
| 1513 |
cdrom_iso_name, |
| 1514 |
uuid=None, |
| 1515 |
obj_type="ISO image", |
| 1516 |
fail=True, |
| 1517 |
msg_prefix="VM check cdrom.iso_name: ", |
| 1518 |
) |
| 1519 |
|
| 1520 |
# Is ISO image changed? |
| 1521 |
if cdrom_iso_name and ( |
| 1522 |
not vm_cdrom_params_list |
| 1523 |
or not vm_cdrom_params_list[0]["VDI"] |
| 1524 |
or cdrom_iso_name != vm_cdrom_params_list[0]["VDI"]["name_label"] |
| 1525 |
): |
| 1526 |
config_changes_cdrom.append("iso_name") |
| 1527 |
|
| 1528 |
if config_changes_cdrom: |
| 1529 |
config_changes.append({"cdrom": config_changes_cdrom}) |
| 1530 |
|
| 1531 |
config_changes_disks = [] |
| 1532 |
config_new_disks = [] |
| 1533 |
|
| 1534 |
if self.module.params["disks"]: |
| 1535 |
# Get the list of all disk. Filter out any CDs found. |
| 1536 |
vm_disk_params_list = [ |
| 1537 |
disk_params for disk_params in self.vm_params["VBDs"] if disk_params["type"] == "Disk" |
| 1538 |
] |
| 1539 |
|
| 1540 |
# Number of disks defined in module params have to be same or |
| 1541 |
# higher than a number of existing disks attached to the VM. |
| 1542 |
# We don't support removal or detachment of disks. |
| 1543 |
if len(self.module.params["disks"]) < len(vm_disk_params_list): |
| 1544 |
self.module.fail_json( |
| 1545 |
msg=f"VM check disks: provided disks configuration has less disks than the " |
| 1546 |
f"target VM ({len(self.module.params['disks'])} < {len(vm_disk_params_list)})!" |
| 1547 |
) |
| 1548 |
|
| 1549 |
# Find the highest disk occupied userdevice. |
| 1550 |
if not vm_disk_params_list: |
| 1551 |
vm_disk_userdevice_highest = "-1" |
| 1552 |
else: |
| 1553 |
vm_disk_userdevice_highest = vm_disk_params_list[-1]["userdevice"] |
| 1554 |
|
| 1555 |
for position in range(len(self.module.params["disks"])): |
| 1556 |
if position < len(vm_disk_params_list): |
| 1557 |
vm_disk_params = vm_disk_params_list[position] |
| 1558 |
else: |
| 1559 |
vm_disk_params = None |
| 1560 |
|
| 1561 |
disk_params = self.module.params["disks"][position] |
| 1562 |
|
| 1563 |
disk_size = self.get_normalized_disk_size( |
| 1564 |
self.module.params["disks"][position], f"VM check disks[{position}]: " |
| 1565 |
) |
| 1566 |
|
| 1567 |
disk_name = disk_params.get("name") |
| 1568 |
|
| 1569 |
if disk_name is not None and not disk_name: |
| 1570 |
self.module.fail_json(msg=f"VM check disks[{position}]: disk name cannot be an empty string!") |
| 1571 |
|
| 1572 |
# If this is an existing disk. |
| 1573 |
if vm_disk_params and vm_disk_params["VDI"]: |
| 1574 |
disk_changes = [] |
| 1575 |
|
| 1576 |
if disk_name and disk_name != vm_disk_params["VDI"]["name_label"]: |
| 1577 |
disk_changes.append("name") |
| 1578 |
|
| 1579 |
disk_name_desc = disk_params.get("name_desc") |
| 1580 |
|
| 1581 |
if disk_name_desc is not None and disk_name_desc != vm_disk_params["VDI"]["name_description"]: |
| 1582 |
disk_changes.append("name_desc") |
| 1583 |
|
| 1584 |
if disk_size: |
| 1585 |
if disk_size > int(vm_disk_params["VDI"]["virtual_size"]): |
| 1586 |
disk_changes.append("size") |
| 1587 |
need_poweredoff = True |
| 1588 |
elif disk_size < int(vm_disk_params["VDI"]["virtual_size"]): |
| 1589 |
self.module.fail_json( |
| 1590 |
msg=f"VM check disks[{position}]: disk size is smaller than existing ({disk_size} bytes < " |
| 1591 |
f"{vm_disk_params['VDI']['virtual_size']} bytes). Reducing disk size is not allowed!" |
| 1592 |
) |
| 1593 |
|
| 1594 |
config_changes_disks.append(disk_changes) |
| 1595 |
# If this is a new disk. |
| 1596 |
else: |
| 1597 |
if not disk_size: |
| 1598 |
self.module.fail_json( |
| 1599 |
msg=f"VM check disks[{position}]: no valid disk size specification found!" |
| 1600 |
) |
| 1601 |
|
| 1602 |
disk_sr_uuid = disk_params.get("sr_uuid") |
| 1603 |
disk_sr = disk_params.get("sr") |
| 1604 |
|
| 1605 |
if disk_sr_uuid is not None or disk_sr is not None: |
| 1606 |
# Check existence only. Ignore return value. |
| 1607 |
get_object_ref( |
| 1608 |
self.module, |
| 1609 |
disk_sr, |
| 1610 |
disk_sr_uuid, |
| 1611 |
obj_type="SR", |
| 1612 |
fail=True, |
| 1613 |
msg_prefix=f"VM check disks[{position}]: ", |
| 1614 |
) |
| 1615 |
elif self.default_sr_ref == "OpaqueRef:NULL": |
| 1616 |
self.module.fail_json( |
| 1617 |
msg=f"VM check disks[{position}]: no default SR found! You must specify SR explicitly." |
| 1618 |
) |
| 1619 |
|
| 1620 |
if not vbd_userdevices_allowed: |
| 1621 |
self.module.fail_json(msg=f"VM check disks[{position}]: maximum number of devices reached!") |
| 1622 |
|
| 1623 |
disk_userdevice = None |
| 1624 |
|
| 1625 |
# We need to place a new disk right above the highest |
| 1626 |
# placed existing disk to maintain relative disk |
| 1627 |
# positions pairable with disk specifications in |
| 1628 |
# module params. That place must not be occupied by |
| 1629 |
# some other device like CD-ROM. We also skip the |
| 1630 |
# position number 3 to keep it reserved for the |
| 1631 |
# CD-ROM drive. If CD-ROM drive ends up in the |
| 1632 |
# position above 3 because we used it for a disk, |
| 1633 |
# booting from ISO will not work (#11624). |
| 1634 |
for userdevice in vbd_userdevices_allowed: |
| 1635 |
if userdevice != "3" and int(userdevice) > int(vm_disk_userdevice_highest): |
| 1636 |
disk_userdevice = userdevice |
| 1637 |
vbd_userdevices_allowed.remove(userdevice) |
| 1638 |
vm_disk_userdevice_highest = userdevice |
| 1639 |
break |
| 1640 |
|
| 1641 |
# If no place was found. |
| 1642 |
if disk_userdevice is None: |
| 1643 |
# Highest occupied place could be a CD-ROM device |
| 1644 |
# so we have to include all devices regardless of |
| 1645 |
# type when calculating out-of-bound position. |
| 1646 |
disk_userdevice = str(int(self.vm_params["VBDs"][-1]["userdevice"]) + 1) |
| 1647 |
self.module.fail_json( |
| 1648 |
msg=f"VM check disks[{position}]: new disk position {disk_userdevice} is out of bounds!" |
| 1649 |
) |
| 1650 |
|
| 1651 |
# For new disks we only track their position. |
| 1652 |
config_new_disks.append((position, disk_userdevice)) |
| 1653 |
|
| 1654 |
# We should append config_changes_disks to config_changes only |
| 1655 |
# if there is at least one changed disk, else skip. |
| 1656 |
for disk_change in config_changes_disks: |
| 1657 |
if disk_change: |
| 1658 |
config_changes.append({"disks_changed": config_changes_disks}) |
| 1659 |
break |
| 1660 |
|
| 1661 |
if config_new_disks: |
| 1662 |
config_changes.append({"disks_new": config_new_disks}) |
| 1663 |
|
| 1664 |
config_changes_networks = [] |
| 1665 |
config_new_networks = [] |
| 1666 |
|
| 1667 |
# Find allowed devices. |
| 1668 |
vif_devices_allowed = self.xapi_session.xenapi.VM.get_allowed_VIF_devices(self.vm_ref) |
| 1669 |
|
| 1670 |
if self.module.params["networks"]: |
| 1671 |
# Number of VIFs defined in module params have to be same or |
| 1672 |
# higher than a number of existing VIFs attached to the VM. |
| 1673 |
# We don't support removal of VIFs. |
| 1674 |
if len(self.module.params["networks"]) < len(self.vm_params["VIFs"]): |
| 1675 |
self.module.fail_json( |
| 1676 |
msg=f"VM check networks: provided networks configuration has less interfaces than the target " |
| 1677 |
f"VM ({len(self.module.params['networks'])} < {len(self.vm_params['VIFs'])})!" |
| 1678 |
) |
| 1679 |
|
| 1680 |
# Find the highest occupied device. |
| 1681 |
if not self.vm_params["VIFs"]: |
| 1682 |
vif_device_highest = "-1" |
| 1683 |
else: |
| 1684 |
vif_device_highest = self.vm_params["VIFs"][-1]["device"] |
| 1685 |
|
| 1686 |
for position in range(len(self.module.params["networks"])): |
| 1687 |
if position < len(self.vm_params["VIFs"]): |
| 1688 |
vm_vif_params = self.vm_params["VIFs"][position] |
| 1689 |
else: |
| 1690 |
vm_vif_params = None |
| 1691 |
|
| 1692 |
network_params = self.module.params["networks"][position] |
| 1693 |
|
| 1694 |
network_name = network_params.get("name") |
| 1695 |
|
| 1696 |
if network_name is not None and not network_name: |
| 1697 |
self.module.fail_json( |
| 1698 |
msg=f"VM check networks[{position}]: network name cannot be an empty string!" |
| 1699 |
) |
| 1700 |
|
| 1701 |
if network_name: |
| 1702 |
# Check existence only. Ignore return value. |
| 1703 |
get_object_ref( |
| 1704 |
self.module, |
| 1705 |
network_name, |
| 1706 |
uuid=None, |
| 1707 |
obj_type="network", |
| 1708 |
fail=True, |
| 1709 |
msg_prefix=f"VM check networks[{position}]: ", |
| 1710 |
) |
| 1711 |
|
| 1712 |
network_mac = network_params.get("mac") |
| 1713 |
|
| 1714 |
if network_mac is not None: |
| 1715 |
network_mac = network_mac.lower() |
| 1716 |
|
| 1717 |
if not is_mac(network_mac): |
| 1718 |
self.module.fail_json( |
| 1719 |
msg=f"VM check networks[{position}]: specified MAC address '{network_mac}' is not valid!" |
| 1720 |
) |
| 1721 |
|
| 1722 |
# IPv4 reconfiguration. |
| 1723 |
network_type = network_params.get("type") |
| 1724 |
network_ip = network_params.get("ip") |
| 1725 |
network_netmask = network_params.get("netmask") |
| 1726 |
network_prefix = None |
| 1727 |
|
| 1728 |
# If networks.ip is specified and networks.type is not, |
| 1729 |
# then set networks.type to 'static'. |
| 1730 |
if not network_type and network_ip: |
| 1731 |
network_type = "static" |
| 1732 |
|
| 1733 |
# XenServer natively supports only 'none' and 'static' |
| 1734 |
# type with 'none' being the same as 'dhcp'. |
| 1735 |
if self.vm_params["customization_agent"] == "native" and network_type and network_type == "dhcp": |
| 1736 |
network_type = "none" |
| 1737 |
|
| 1738 |
if network_type and network_type == "static": |
| 1739 |
if network_ip is not None: |
| 1740 |
network_ip_split = network_ip.split("/") |
| 1741 |
network_ip = network_ip_split[0] |
| 1742 |
|
| 1743 |
if network_ip and not is_valid_ip_addr(network_ip): |
| 1744 |
self.module.fail_json( |
| 1745 |
msg=f"VM check networks[{position}]: specified IPv4 address '{network_ip}' is not valid!" |
| 1746 |
) |
| 1747 |
|
| 1748 |
if len(network_ip_split) > 1: |
| 1749 |
network_prefix = network_ip_split[1] |
| 1750 |
|
| 1751 |
if not is_valid_ip_prefix(network_prefix): |
| 1752 |
self.module.fail_json( |
| 1753 |
msg=f"VM check networks[{position}]: specified IPv4 prefix '{network_prefix}' is not valid!" |
| 1754 |
) |
| 1755 |
|
| 1756 |
if network_netmask is not None: |
| 1757 |
if not is_valid_ip_netmask(network_netmask): |
| 1758 |
self.module.fail_json( |
| 1759 |
msg=f"VM check networks[{position}]: specified IPv4 netmask '{network_netmask}' is not valid!" |
| 1760 |
) |
| 1761 |
|
| 1762 |
network_prefix = ip_netmask_to_prefix(network_netmask, skip_check=True) |
| 1763 |
elif network_prefix is not None: |
| 1764 |
network_netmask = ip_prefix_to_netmask(network_prefix, skip_check=True) |
| 1765 |
|
| 1766 |
# If any parameter is overridden at this point, update it. |
| 1767 |
if network_type: |
| 1768 |
network_params["type"] = network_type |
| 1769 |
|
| 1770 |
if network_ip: |
| 1771 |
network_params["ip"] = network_ip |
| 1772 |
|
| 1773 |
if network_netmask: |
| 1774 |
network_params["netmask"] = network_netmask |
| 1775 |
|
| 1776 |
if network_prefix: |
| 1777 |
network_params["prefix"] = network_prefix |
| 1778 |
|
| 1779 |
network_gateway = network_params.get("gateway") |
| 1780 |
|
| 1781 |
# Gateway can be an empty string (when removing gateway |
| 1782 |
# configuration) but if it is not, it should be validated. |
| 1783 |
if network_gateway and not is_valid_ip_addr(network_gateway): |
| 1784 |
self.module.fail_json( |
| 1785 |
msg=f"VM check networks[{position}]: specified IPv4 gateway '{network_gateway}' is not valid!" |
| 1786 |
) |
| 1787 |
|
| 1788 |
# IPv6 reconfiguration. |
| 1789 |
network_type6 = network_params.get("type6") |
| 1790 |
network_ip6 = network_params.get("ip6") |
| 1791 |
network_prefix6 = None |
| 1792 |
|
| 1793 |
# If networks.ip6 is specified and networks.type6 is not, |
| 1794 |
# then set networks.type6 to 'static'. |
| 1795 |
if not network_type6 and network_ip6: |
| 1796 |
network_type6 = "static" |
| 1797 |
|
| 1798 |
# XenServer natively supports only 'none' and 'static' |
| 1799 |
# type with 'none' being the same as 'dhcp'. |
| 1800 |
if self.vm_params["customization_agent"] == "native" and network_type6 and network_type6 == "dhcp": |
| 1801 |
network_type6 = "none" |
| 1802 |
|
| 1803 |
if network_type6 and network_type6 == "static": |
| 1804 |
if network_ip6 is not None: |
| 1805 |
network_ip6_split = network_ip6.split("/") |
| 1806 |
network_ip6 = network_ip6_split[0] |
| 1807 |
|
| 1808 |
if network_ip6 and not is_valid_ip6_addr(network_ip6): |
| 1809 |
self.module.fail_json( |
| 1810 |
msg=f"VM check networks[{position}]: specified IPv6 address '{network_ip6}' is not valid!" |
| 1811 |
) |
| 1812 |
|
| 1813 |
if len(network_ip6_split) > 1: |
| 1814 |
network_prefix6 = network_ip6_split[1] |
| 1815 |
|
| 1816 |
if not is_valid_ip6_prefix(network_prefix6): |
| 1817 |
self.module.fail_json( |
| 1818 |
msg=f"VM check networks[{position}]: specified IPv6 prefix '{network_prefix6}' is not valid!" |
| 1819 |
) |
| 1820 |
|
| 1821 |
# If any parameter is overridden at this point, update it. |
| 1822 |
if network_type6: |
| 1823 |
network_params["type6"] = network_type6 |
| 1824 |
|
| 1825 |
if network_ip6: |
| 1826 |
network_params["ip6"] = network_ip6 |
| 1827 |
|
| 1828 |
if network_prefix6: |
| 1829 |
network_params["prefix6"] = network_prefix6 |
| 1830 |
|
| 1831 |
network_gateway6 = network_params.get("gateway6") |
| 1832 |
|
| 1833 |
# Gateway can be an empty string (when removing gateway |
| 1834 |
# configuration) but if it is not, it should be validated. |
| 1835 |
if network_gateway6 and not is_valid_ip6_addr(network_gateway6): |
| 1836 |
self.module.fail_json( |
| 1837 |
msg=f"VM check networks[{position}]: specified IPv6 gateway '{network_gateway6}' is not valid!" |
| 1838 |
) |
| 1839 |
|
| 1840 |
# If this is an existing VIF. |
| 1841 |
if vm_vif_params and vm_vif_params["network"]: |
| 1842 |
network_changes = [] |
| 1843 |
|
| 1844 |
if network_name and network_name != vm_vif_params["network"]["name_label"]: |
| 1845 |
network_changes.append("name") |
| 1846 |
|
| 1847 |
if network_mac and network_mac != vm_vif_params["MAC"].lower(): |
| 1848 |
network_changes.append("mac") |
| 1849 |
|
| 1850 |
if self.vm_params["customization_agent"] == "native": |
| 1851 |
if network_type and network_type != vm_vif_params["ipv4_configuration_mode"].lower(): |
| 1852 |
network_changes.append("type") |
| 1853 |
|
| 1854 |
if network_type and network_type == "static": |
| 1855 |
if network_ip and ( |
| 1856 |
not vm_vif_params["ipv4_addresses"] |
| 1857 |
or not vm_vif_params["ipv4_addresses"][0] |
| 1858 |
or network_ip != vm_vif_params["ipv4_addresses"][0].split("/")[0] |
| 1859 |
): |
| 1860 |
network_changes.append("ip") |
| 1861 |
|
| 1862 |
if network_prefix and ( |
| 1863 |
not vm_vif_params["ipv4_addresses"] |
| 1864 |
or not vm_vif_params["ipv4_addresses"][0] |
| 1865 |
or network_prefix != vm_vif_params["ipv4_addresses"][0].split("/")[1] |
| 1866 |
): |
| 1867 |
network_changes.append("prefix") |
| 1868 |
network_changes.append("netmask") |
| 1869 |
|
| 1870 |
if network_gateway is not None and network_gateway != vm_vif_params["ipv4_gateway"]: |
| 1871 |
network_changes.append("gateway") |
| 1872 |
|
| 1873 |
if network_type6 and network_type6 != vm_vif_params["ipv6_configuration_mode"].lower(): |
| 1874 |
network_changes.append("type6") |
| 1875 |
|
| 1876 |
if network_type6 and network_type6 == "static": |
| 1877 |
if network_ip6 and ( |
| 1878 |
not vm_vif_params["ipv6_addresses"] |
| 1879 |
or not vm_vif_params["ipv6_addresses"][0] |
| 1880 |
or network_ip6 != vm_vif_params["ipv6_addresses"][0].split("/")[0] |
| 1881 |
): |
| 1882 |
network_changes.append("ip6") |
| 1883 |
|
| 1884 |
if network_prefix6 and ( |
| 1885 |
not vm_vif_params["ipv6_addresses"] |
| 1886 |
or not vm_vif_params["ipv6_addresses"][0] |
| 1887 |
or network_prefix6 != vm_vif_params["ipv6_addresses"][0].split("/")[1] |
| 1888 |
): |
| 1889 |
network_changes.append("prefix6") |
| 1890 |
|
| 1891 |
if network_gateway6 is not None and network_gateway6 != vm_vif_params["ipv6_gateway"]: |
| 1892 |
network_changes.append("gateway6") |
| 1893 |
|
| 1894 |
elif self.vm_params["customization_agent"] == "custom": |
| 1895 |
vm_xenstore_data = self.vm_params["xenstore_data"] |
| 1896 |
|
| 1897 |
if network_type and network_type != vm_xenstore_data.get( |
| 1898 |
f"vm-data/networks/{vm_vif_params['device']}/type", "none" |
| 1899 |
): |
| 1900 |
network_changes.append("type") |
| 1901 |
need_poweredoff = True |
| 1902 |
|
| 1903 |
if network_type and network_type == "static": |
| 1904 |
if network_ip and network_ip != vm_xenstore_data.get( |
| 1905 |
f"vm-data/networks/{vm_vif_params['device']}/ip", "" |
| 1906 |
): |
| 1907 |
network_changes.append("ip") |
| 1908 |
need_poweredoff = True |
| 1909 |
|
| 1910 |
if network_prefix and network_prefix != vm_xenstore_data.get( |
| 1911 |
f"vm-data/networks/{vm_vif_params['device']}/prefix", "" |
| 1912 |
): |
| 1913 |
network_changes.append("prefix") |
| 1914 |
network_changes.append("netmask") |
| 1915 |
need_poweredoff = True |
| 1916 |
|
| 1917 |
_device_gw_path = f"vm-data/networks/{vm_vif_params['device']}/gateway" |
| 1918 |
if network_gateway is not None and network_gateway != vm_xenstore_data.get( |
| 1919 |
_device_gw_path, "" |
| 1920 |
): |
| 1921 |
network_changes.append("gateway") |
| 1922 |
need_poweredoff = True |
| 1923 |
|
| 1924 |
if network_type6 and network_type6 != vm_xenstore_data.get( |
| 1925 |
f"vm-data/networks/{vm_vif_params['device']}/type6", "none" |
| 1926 |
): |
| 1927 |
network_changes.append("type6") |
| 1928 |
need_poweredoff = True |
| 1929 |
|
| 1930 |
if network_type6 and network_type6 == "static": |
| 1931 |
if network_ip6 and network_ip6 != vm_xenstore_data.get( |
| 1932 |
f"vm-data/networks/{vm_vif_params['device']}/ip6", "" |
| 1933 |
): |
| 1934 |
network_changes.append("ip6") |
| 1935 |
need_poweredoff = True |
| 1936 |
|
| 1937 |
if network_prefix6 and network_prefix6 != vm_xenstore_data.get( |
| 1938 |
f"vm-data/networks/{vm_vif_params['device']}/prefix6", "" |
| 1939 |
): |
| 1940 |
network_changes.append("prefix6") |
| 1941 |
need_poweredoff = True |
| 1942 |
|
| 1943 |
_device_gw6_path = f"vm-data/networks/{vm_vif_params['device']}/gateway6" |
| 1944 |
if network_gateway6 is not None and network_gateway6 != vm_xenstore_data.get( |
| 1945 |
_device_gw6_path, "" |
| 1946 |
): |
| 1947 |
network_changes.append("gateway6") |
| 1948 |
need_poweredoff = True |
| 1949 |
|
| 1950 |
config_changes_networks.append(network_changes) |
| 1951 |
# If this is a new VIF. |
| 1952 |
else: |
| 1953 |
if not network_name: |
| 1954 |
self.module.fail_json( |
| 1955 |
msg=f"VM check networks[{position}]: network name is required for new network interface!" |
| 1956 |
) |
| 1957 |
|
| 1958 |
if network_type and network_type == "static" and network_ip and not network_netmask: |
| 1959 |
self.module.fail_json( |
| 1960 |
msg=f"VM check networks[{position}]: IPv4 netmask or prefix is required for new network interface!" |
| 1961 |
) |
| 1962 |
|
| 1963 |
if network_type6 and network_type6 == "static" and network_ip6 and not network_prefix6: |
| 1964 |
self.module.fail_json( |
| 1965 |
msg=f"VM check networks[{position}]: IPv6 prefix is required for new network interface!" |
| 1966 |
) |
| 1967 |
|
| 1968 |
# Restart is needed if we are adding new network |
| 1969 |
# interface with IP/gateway parameters specified |
| 1970 |
# and custom agent is used. |
| 1971 |
if self.vm_params["customization_agent"] == "custom": |
| 1972 |
for parameter in ["type", "ip", "prefix", "gateway", "type6", "ip6", "prefix6", "gateway6"]: |
| 1973 |
if network_params.get(parameter): |
| 1974 |
need_poweredoff = True |
| 1975 |
break |
| 1976 |
|
| 1977 |
if not vif_devices_allowed: |
| 1978 |
self.module.fail_json( |
| 1979 |
msg=f"VM check networks[{position}]: maximum number of network interfaces reached!" |
| 1980 |
) |
| 1981 |
|
| 1982 |
# We need to place a new network interface right above the |
| 1983 |
# highest placed existing interface to maintain relative |
| 1984 |
# positions pairable with network interface specifications |
| 1985 |
# in module params. |
| 1986 |
vif_device = str(int(vif_device_highest) + 1) |
| 1987 |
|
| 1988 |
if vif_device not in vif_devices_allowed: |
| 1989 |
self.module.fail_json( |
| 1990 |
msg=f"VM check networks[{position}]: new network interface position {vif_device} is out of bounds!" |
| 1991 |
) |
| 1992 |
|
| 1993 |
vif_devices_allowed.remove(vif_device) |
| 1994 |
vif_device_highest = vif_device |
| 1995 |
|
| 1996 |
# For new VIFs we only track their position. |
| 1997 |
config_new_networks.append((position, vif_device)) |
| 1998 |
|
| 1999 |
# We should append config_changes_networks to config_changes only |
| 2000 |
# if there is at least one changed network, else skip. |
| 2001 |
for network_change in config_changes_networks: |
| 2002 |
if network_change: |
| 2003 |
config_changes.append({"networks_changed": config_changes_networks}) |
| 2004 |
break |
| 2005 |
|
| 2006 |
if config_new_networks: |
| 2007 |
config_changes.append({"networks_new": config_new_networks}) |
| 2008 |
|
| 2009 |
config_changes_custom_params = [] |
| 2010 |
|
| 2011 |
if self.module.params["custom_params"]: |
| 2012 |
for position in range(len(self.module.params["custom_params"])): |
| 2013 |
custom_param = self.module.params["custom_params"][position] |
| 2014 |
|
| 2015 |
custom_param_key = custom_param["key"] |
| 2016 |
custom_param_value = custom_param["value"] |
| 2017 |
|
| 2018 |
if custom_param_key not in self.vm_params: |
| 2019 |
self.module.fail_json( |
| 2020 |
msg=f"VM check custom_params[{position}]: unknown VM param '{custom_param_key}'!" |
| 2021 |
) |
| 2022 |
|
| 2023 |
if custom_param_value != self.vm_params[custom_param_key]: |
| 2024 |
# We only need to track custom param position. |
| 2025 |
config_changes_custom_params.append(position) |
| 2026 |
|
| 2027 |
if config_changes_custom_params: |
| 2028 |
config_changes.append({"custom_params": config_changes_custom_params}) |
| 2029 |
|
| 2030 |
if need_poweredoff: |
| 2031 |
config_changes.append("need_poweredoff") |
| 2032 |
|
| 2033 |
return config_changes |
| 2034 |
|
| 2035 |
except XenAPI.Failure as f: |
| 2036 |
self.module.fail_json(msg=f"XAPI ERROR: {f.details}") |
| 2037 |
|
| 2038 |
def get_normalized_disk_size(self, disk_params, msg_prefix=""): |
| 2039 |
"""Parses disk size parameters and returns disk size in bytes. |
| 2040 |
|
| 2041 |
This method tries to parse disk size module parameters. It fails |
| 2042 |
with an error message if size cannot be parsed. |
| 2043 |
|
| 2044 |
Args: |
| 2045 |
disk_params (dist): A dictionary with disk parameters. |
| 2046 |
msg_prefix (str): A string error messages should be prefixed |
| 2047 |
with (default: ""). |
| 2048 |
|
| 2049 |
Returns: |
| 2050 |
int: disk size in bytes if disk size is successfully parsed or |
| 2051 |
None if no disk size parameters were found. |
| 2052 |
""" |
| 2053 |
# There should be only single size spec but we make a list of all size |
| 2054 |
# specs just in case. Priority is given to 'size' but if not found, we |
| 2055 |
# check for 'size_tb', 'size_gb', 'size_mb' etc. and use first one |
| 2056 |
# found. |
| 2057 |
disk_size_spec = [ |
| 2058 |
x for x in disk_params.keys() if disk_params[x] is not None and (x.startswith("size_") or x == "size") |
| 2059 |
] |
| 2060 |
|
| 2061 |
if disk_size_spec: |
| 2062 |
try: |
| 2063 |
# size |
| 2064 |
if "size" in disk_size_spec: |
| 2065 |
size_regex = re.compile(r"(\d+(?:\.\d+)?)\s*(.*)") |
| 2066 |
disk_size_m = size_regex.match(disk_params["size"]) |
| 2067 |
|
| 2068 |
if disk_size_m: |
| 2069 |
size = disk_size_m.group(1) |
| 2070 |
unit = disk_size_m.group(2) |
| 2071 |
else: |
| 2072 |
raise ValueError |
| 2073 |
# size_tb, size_gb, size_mb, size_kb, size_b |
| 2074 |
else: |
| 2075 |
size = disk_params[disk_size_spec[0]] |
| 2076 |
unit = disk_size_spec[0].split("_")[-1] |
| 2077 |
|
| 2078 |
if not unit: |
| 2079 |
unit = "b" |
| 2080 |
else: |
| 2081 |
unit = unit.lower() |
| 2082 |
|
| 2083 |
if re.match(r"\d+\.\d+", size): |
| 2084 |
# We found float value in string, let's typecast it. |
| 2085 |
if unit == "b": |
| 2086 |
# If we found float but unit is bytes, we get the integer part only. |
| 2087 |
size = int(float(size)) |
| 2088 |
else: |
| 2089 |
size = float(size) |
| 2090 |
else: |
| 2091 |
# We found int value in string, let's typecast it. |
| 2092 |
size = int(size) |
| 2093 |
|
| 2094 |
if not size or size < 0: |
| 2095 |
raise ValueError |
| 2096 |
|
| 2097 |
except (TypeError, ValueError, NameError): |
| 2098 |
# Common failure |
| 2099 |
self.module.fail_json( |
| 2100 |
msg=f"{msg_prefix}failed to parse disk size! Please review value provided using documentation." |
| 2101 |
) |
| 2102 |
|
| 2103 |
disk_units = dict(tb=4, gb=3, mb=2, kb=1, b=0) |
| 2104 |
|
| 2105 |
if unit in disk_units: |
| 2106 |
return int(size * (1024 ** disk_units[unit])) |
| 2107 |
else: |
| 2108 |
str_supported_units = "', '".join(sorted(disk_units.keys(), key=lambda key: disk_units[key])) |
| 2109 |
self.module.fail_json( |
| 2110 |
msg=f"{msg_prefix}'{unit}' is not a supported unit for disk size! Supported units are ['{str_supported_units}']." |
| 2111 |
) |
| 2112 |
else: |
| 2113 |
return None |
| 2114 |
|
| 2115 |
@staticmethod |
| 2116 |
def get_cdrom_type(vm_cdrom_params): |
| 2117 |
"""Returns VM CD-ROM type.""" |
| 2118 |
# TODO: implement support for detecting type host. No server to test |
| 2119 |
# this on at the moment. |
| 2120 |
if vm_cdrom_params["empty"]: |
| 2121 |
return "none" |
| 2122 |
else: |
| 2123 |
return "iso" |
| 2124 |
|
| 2125 |
|
| 2126 |
def main(): |
| 2127 |
argument_spec = xenserver_common_argument_spec() |
| 2128 |
argument_spec.update( |
| 2129 |
state=dict(type="str", default="present", choices=["present", "absent", "poweredon"]), |
| 2130 |
name=dict(type="str", aliases=["name_label"]), |
| 2131 |
name_desc=dict(type="str"), |
| 2132 |
uuid=dict(type="str"), |
| 2133 |
template=dict(type="str", aliases=["template_src"]), |
| 2134 |
template_uuid=dict(type="str"), |
| 2135 |
is_template=dict(type="bool", default=False), |
| 2136 |
folder=dict(type="str"), |
| 2137 |
hardware=dict( |
| 2138 |
type="dict", |
| 2139 |
options=dict( |
| 2140 |
num_cpus=dict(type="int"), |
| 2141 |
num_cpu_cores_per_socket=dict(type="int"), |
| 2142 |
memory_mb=dict(type="int"), |
| 2143 |
), |
| 2144 |
), |
| 2145 |
disks=dict( |
| 2146 |
type="list", |
| 2147 |
elements="dict", |
| 2148 |
options=dict( |
| 2149 |
size=dict(type="str"), |
| 2150 |
size_tb=dict(type="str"), |
| 2151 |
size_gb=dict(type="str"), |
| 2152 |
size_mb=dict(type="str"), |
| 2153 |
size_kb=dict(type="str"), |
| 2154 |
size_b=dict(type="str"), |
| 2155 |
name=dict(type="str", aliases=["name_label"]), |
| 2156 |
name_desc=dict(type="str"), |
| 2157 |
sr=dict(type="str"), |
| 2158 |
sr_uuid=dict(type="str"), |
| 2159 |
), |
| 2160 |
aliases=["disk"], |
| 2161 |
mutually_exclusive=[ |
| 2162 |
["size", "size_tb", "size_gb", "size_mb", "size_kb", "size_b"], |
| 2163 |
["sr", "sr_uuid"], |
| 2164 |
], |
| 2165 |
), |
| 2166 |
cdrom=dict( |
| 2167 |
type="dict", |
| 2168 |
options=dict( |
| 2169 |
type=dict(type="str", choices=["none", "iso"]), |
| 2170 |
iso_name=dict(type="str"), |
| 2171 |
), |
| 2172 |
required_if=[ |
| 2173 |
["type", "iso", ["iso_name"]], |
| 2174 |
], |
| 2175 |
), |
| 2176 |
networks=dict( |
| 2177 |
type="list", |
| 2178 |
elements="dict", |
| 2179 |
options=dict( |
| 2180 |
name=dict(type="str", aliases=["name_label"]), |
| 2181 |
mac=dict(type="str"), |
| 2182 |
type=dict(type="str", choices=["none", "dhcp", "static"]), |
| 2183 |
ip=dict(type="str"), |
| 2184 |
netmask=dict(type="str"), |
| 2185 |
gateway=dict(type="str"), |
| 2186 |
type6=dict(type="str", choices=["none", "dhcp", "static"]), |
| 2187 |
ip6=dict(type="str"), |
| 2188 |
gateway6=dict(type="str"), |
| 2189 |
), |
| 2190 |
aliases=["network"], |
| 2191 |
required_if=[ |
| 2192 |
["type", "static", ["ip"]], |
| 2193 |
["type6", "static", ["ip6"]], |
| 2194 |
], |
| 2195 |
), |
| 2196 |
home_server=dict(type="str"), |
| 2197 |
custom_params=dict( |
| 2198 |
type="list", |
| 2199 |
elements="dict", |
| 2200 |
options=dict( |
| 2201 |
key=dict(type="str", required=True, no_log=False), |
| 2202 |
value=dict(type="raw", required=True), |
| 2203 |
), |
| 2204 |
), |
| 2205 |
wait_for_ip_address=dict(type="bool", default=False), |
| 2206 |
state_change_timeout=dict(type="int", default=0), |
| 2207 |
linked_clone=dict(type="bool", default=False), |
| 2208 |
force=dict(type="bool", default=False), |
| 2209 |
) |
| 2210 |
|
| 2211 |
module = AnsibleModule( |
| 2212 |
argument_spec=argument_spec, |
| 2213 |
supports_check_mode=True, |
| 2214 |
required_one_of=[ |
| 2215 |
["name", "uuid"], |
| 2216 |
], |
| 2217 |
mutually_exclusive=[ |
| 2218 |
["template", "template_uuid"], |
| 2219 |
], |
| 2220 |
) |
| 2221 |
|
| 2222 |
result = {"failed": False, "changed": False} |
| 2223 |
|
| 2224 |
vm = XenServerVM(module) |
| 2225 |
|
| 2226 |
# Find existing VM |
| 2227 |
if vm.exists(): |
| 2228 |
if module.params["state"] == "absent": |
| 2229 |
vm.destroy() |
| 2230 |
result["changed"] = True |
| 2231 |
elif module.params["state"] == "present": |
| 2232 |
config_changes = vm.reconfigure() |
| 2233 |
|
| 2234 |
if config_changes: |
| 2235 |
result["changed"] = True |
| 2236 |
|
| 2237 |
# Make new disk and network changes more user friendly |
| 2238 |
# and informative. |
| 2239 |
for change in config_changes: |
| 2240 |
if isinstance(change, dict): |
| 2241 |
if change.get("disks_new"): |
| 2242 |
disks_new = [] |
| 2243 |
|
| 2244 |
for position, userdevice in change["disks_new"]: |
| 2245 |
disk_new_params = {"position": position, "vbd_userdevice": userdevice} |
| 2246 |
disk_params = module.params["disks"][position] |
| 2247 |
|
| 2248 |
for k in disk_params.keys(): |
| 2249 |
if disk_params[k] is not None: |
| 2250 |
disk_new_params[k] = disk_params[k] |
| 2251 |
|
| 2252 |
disks_new.append(disk_new_params) |
| 2253 |
|
| 2254 |
if disks_new: |
| 2255 |
change["disks_new"] = disks_new |
| 2256 |
|
| 2257 |
elif change.get("networks_new"): |
| 2258 |
networks_new = [] |
| 2259 |
|
| 2260 |
for position, device in change["networks_new"]: |
| 2261 |
network_new_params = {"position": position, "vif_device": device} |
| 2262 |
network_params = module.params["networks"][position] |
| 2263 |
|
| 2264 |
for k in network_params.keys(): |
| 2265 |
if network_params[k] is not None: |
| 2266 |
network_new_params[k] = network_params[k] |
| 2267 |
|
| 2268 |
networks_new.append(network_new_params) |
| 2269 |
|
| 2270 |
if networks_new: |
| 2271 |
change["networks_new"] = networks_new |
| 2272 |
|
| 2273 |
result["changes"] = config_changes |
| 2274 |
|
| 2275 |
elif module.params["state"] in [ |
| 2276 |
"poweredon", |
| 2277 |
"poweredoff", |
| 2278 |
"restarted", |
| 2279 |
"shutdownguest", |
| 2280 |
"rebootguest", |
| 2281 |
"suspended", |
| 2282 |
]: |
| 2283 |
result["changed"] = vm.set_power_state(module.params["state"]) |
| 2284 |
elif module.params["state"] != "absent": |
| 2285 |
vm.deploy() |
| 2286 |
result["changed"] = True |
| 2287 |
|
| 2288 |
if module.params["wait_for_ip_address"] and module.params["state"] != "absent": |
| 2289 |
vm.wait_for_ip_address() |
| 2290 |
|
| 2291 |
result["instance"] = vm.gather_facts() |
| 2292 |
|
| 2293 |
if result["failed"]: |
| 2294 |
module.fail_json(**result) |
| 2295 |
else: |
| 2296 |
module.exit_json(**result) |
| 2297 |
|
| 2298 |
|
| 2299 |
if __name__ == "__main__": |
| 2300 |
main() |