| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# (c) 2025, Joey Zhang <[email protected]> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
|
| 8 |
from __future__ import absolute_import, division, print_function |
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
|
| 12 |
DOCUMENTATION = """ |
| 13 |
--- |
| 14 |
module: virt_cloud_instance |
| 15 |
version_added: 2.1.0 |
| 16 |
author: "Joey Zhang (@thinkdoggie)" |
| 17 |
short_description: Provision new virtual machines from cloud images via libvirt |
| 18 |
description: |
| 19 |
- Create and customize virtual machines using pre-built cloud images with cloud-init support. |
| 20 |
- Cloud images can be retrieved from local files and remote URLs. |
| 21 |
- Supports automatic conversion and resizing of disk images. |
| 22 |
options: |
| 23 |
name: |
| 24 |
type: str |
| 25 |
description: |
| 26 |
- Name of the new guest virtual machine instance. |
| 27 |
required: true |
| 28 |
state: |
| 29 |
choices: [ present, absent ] |
| 30 |
type: str |
| 31 |
description: |
| 32 |
- If set to V(present), create the VM if it does not exist. |
| 33 |
default: present |
| 34 |
recreate: |
| 35 |
type: bool |
| 36 |
description: |
| 37 |
- Use with present to force the re-creation of an existing VM. |
| 38 |
default: false |
| 39 |
base_image: |
| 40 |
type: str |
| 41 |
description: |
| 42 |
- Path or URL to the cloud image. |
| 43 |
- Can be a local file path or a remote URL (http, https, ftp). |
| 44 |
- The image will be automatically downloaded if a URL is provided. |
| 45 |
required: true |
| 46 |
image_cache_dir: |
| 47 |
type: path |
| 48 |
description: |
| 49 |
- Directory where downloaded cloud images will be cached. |
| 50 |
- Only used when O(base_image) is a URL. |
| 51 |
- If not specified, the base image will be downloaded to the temporary directory and not be cached. |
| 52 |
force_pull: |
| 53 |
type: bool |
| 54 |
description: |
| 55 |
- Force pull of the cloud image even if it already exists in the cache. |
| 56 |
- Only used when O(base_image) is a URL. |
| 57 |
- Useful for updating cached images to their latest versions. |
| 58 |
default: false |
| 59 |
force_disk: |
| 60 |
type: bool |
| 61 |
description: |
| 62 |
- Force deletion and recreation of existing disk files. |
| 63 |
- When set to V(true), any existing disk files specified in O(disks) will be removed and recreated. |
| 64 |
- When set to V(false), the module will fail if any disk file already exists. |
| 65 |
- This parameter only affects disk file creation, not VM definition. |
| 66 |
- Use with O(recreate=true) to recreate both the VM and its disk files. |
| 67 |
default: false |
| 68 |
image_checksum: |
| 69 |
type: str |
| 70 |
description: |
| 71 |
- If specified, the digest of the downloaded image will be calculated to verify the integrity of the downloaded image. |
| 72 |
- "Format: <algorithm>:<checksum|url>, e.g. I(sha256:D98291AC[...]B6DC7B97), I(sha256:http://example.com/path/sha256sum.txt)." |
| 73 |
- Only used when O(base_image) is a URL. |
| 74 |
- If you worry about portability, only the sha1 algorithm is available on all platforms and python versions. |
| 75 |
url_timeout: |
| 76 |
type: int |
| 77 |
default: 60 |
| 78 |
description: |
| 79 |
- The timeout in seconds for downloading the base image from a URL. |
| 80 |
- Only used when O(base_image) is a URL. |
| 81 |
url_username: |
| 82 |
type: str |
| 83 |
description: |
| 84 |
- The username for HTTP basic authentication. |
| 85 |
- Only used when O(base_image) is a URL. |
| 86 |
url_password: |
| 87 |
type: str |
| 88 |
description: |
| 89 |
- The password for HTTP basic authentication. |
| 90 |
- Only used when O(base_image) is a URL. |
| 91 |
wait_for_cloud_init_reboot: |
| 92 |
type: bool |
| 93 |
default: true |
| 94 |
description: |
| 95 |
- If set to V(true), wait for cloud-init to trigger a reboot and for the VM to come back online. |
| 96 |
- This requires that your cloud-init user-data includes a reboot action, or I(cloud_init_auto_reboot=true). |
| 97 |
- Only applicable when O(cloud_init) configuration is provided. |
| 98 |
cloud_init_auto_reboot: |
| 99 |
type: bool |
| 100 |
default: true |
| 101 |
description: |
| 102 |
- When I(wait_for_cloud_init_reboot=true), automatically inject a reboot instruction into the cloud-init user-data. |
| 103 |
- If set to V(false), the reboot instructions should be included in the cloud-init user-data manually. |
| 104 |
- Only applies when I(wait_for_cloud_init_reboot=true). |
| 105 |
cloud_init_reboot_timeout: |
| 106 |
type: int |
| 107 |
default: 600 |
| 108 |
description: |
| 109 |
- Maximum time in seconds to wait for the cloud-init reboot cycle to complete. |
| 110 |
- The timeout is checked at minute intervals, so the actual timeout may be up to 60 seconds longer. |
| 111 |
- Only applies when I(wait_for_cloud_init_reboot=true). |
| 112 |
- If the timeout is exceeded, the task will fail. |
| 113 |
extends_documentation_fragment: |
| 114 |
- community.libvirt.virt.options_uri |
| 115 |
- community.libvirt.virt_install.options_cloud_init |
| 116 |
- community.libvirt.virt_install.options_memory |
| 117 |
- community.libvirt.virt_install.options_memorybacking |
| 118 |
- community.libvirt.virt_install.options_arch |
| 119 |
- community.libvirt.virt_install.options_machine |
| 120 |
- community.libvirt.virt_install.options_metadata |
| 121 |
- community.libvirt.virt_install.options_events |
| 122 |
- community.libvirt.virt_install.options_resource |
| 123 |
- community.libvirt.virt_install.options_sysinfo |
| 124 |
- community.libvirt.virt_install.options_qemu_commandline |
| 125 |
- community.libvirt.virt_install.options_vcpus |
| 126 |
- community.libvirt.virt_install.options_numatune |
| 127 |
- community.libvirt.virt_install.options_memtune |
| 128 |
- community.libvirt.virt_install.options_blkiotune |
| 129 |
- community.libvirt.virt_install.options_cpu |
| 130 |
- community.libvirt.virt_install.options_cputune |
| 131 |
- community.libvirt.virt_install.options_security |
| 132 |
- community.libvirt.virt_install.options_keywrap |
| 133 |
- community.libvirt.virt_install.options_iothreads |
| 134 |
- community.libvirt.virt_install.options_features |
| 135 |
- community.libvirt.virt_install.options_clock |
| 136 |
- community.libvirt.virt_install.options_pm |
| 137 |
- community.libvirt.virt_install.options_launch_security |
| 138 |
- community.libvirt.virt_install.options_boot |
| 139 |
- community.libvirt.virt_install.options_osinfo |
| 140 |
- community.libvirt.virt_install.options_disks |
| 141 |
- community.libvirt.virt_install.options_filesystems |
| 142 |
- community.libvirt.virt_install.options_networks |
| 143 |
- community.libvirt.virt_install.options_graphics_devices |
| 144 |
- community.libvirt.virt_install.options_virt_type |
| 145 |
- community.libvirt.virt_install.options_hvm |
| 146 |
- community.libvirt.virt_install.options_paravirt |
| 147 |
- community.libvirt.virt_install.options_controller_devices |
| 148 |
- community.libvirt.virt_install.options_input_devices |
| 149 |
- community.libvirt.virt_install.options_host_devices |
| 150 |
- community.libvirt.virt_install.options_sound_devices |
| 151 |
- community.libvirt.virt_install.options_audio_devices |
| 152 |
- community.libvirt.virt_install.options_watchdog_devices |
| 153 |
- community.libvirt.virt_install.options_serial_devices |
| 154 |
- community.libvirt.virt_install.options_parallel_devices |
| 155 |
- community.libvirt.virt_install.options_channel_devices |
| 156 |
- community.libvirt.virt_install.options_console_devices |
| 157 |
- community.libvirt.virt_install.options_video_devices |
| 158 |
- community.libvirt.virt_install.options_smartcard_devices |
| 159 |
- community.libvirt.virt_install.options_redirected_devices |
| 160 |
- community.libvirt.virt_install.options_memballoon_devices |
| 161 |
- community.libvirt.virt_install.options_tpm_devices |
| 162 |
- community.libvirt.virt_install.options_rng_devices |
| 163 |
- community.libvirt.virt_install.options_panic_devices |
| 164 |
- community.libvirt.virt_install.options_shmem_devices |
| 165 |
- community.libvirt.virt_install.options_vsock_devices |
| 166 |
- community.libvirt.virt_install.options_iommu_devices |
| 167 |
- community.libvirt.virt_install.options_autostart |
| 168 |
- community.libvirt.requirements |
| 169 |
attributes: |
| 170 |
check_mode: |
| 171 |
description: Supports check_mode. |
| 172 |
support: full |
| 173 |
requirements: |
| 174 |
- "virt-install" |
| 175 |
- "qemu-img" |
| 176 |
notes: |
| 177 |
- The C(virt-install) command is provided by different packages on different distributions. |
| 178 |
- On Debian/Ubuntu, install the C(virtinst) package. |
| 179 |
- On RHEL/CentOS/Fedora and openSUSE, install the C(virt-install) package. |
| 180 |
- When O(wait_for_cloud_init_reboot=true), ensure your cloud-init user-data includes appropriate reboot commands or set O(cloud_init_auto_reboot=true). |
| 181 |
- The O(cloud_init_auto_reboot) parameter automatically injects I(power_state.mode=reboot) at the end of user-data when enabled. |
| 182 |
- The module waits through the complete cloud-init process including any reboots specified in the user-data. |
| 183 |
- Use O(cloud_init_reboot_timeout) to control the maximum wait time for complex cloud-init configurations. |
| 184 |
seealso: |
| 185 |
- module: community.libvirt.virt_install |
| 186 |
description: More general VM installation module. |
| 187 |
- name: virt-install Man Page |
| 188 |
description: Ubuntu manpage of virt-install tool. |
| 189 |
link: https://manpages.ubuntu.com/manpages/focal/man1/virt-install.1.html |
| 190 |
""" |
| 191 |
|
| 192 |
|
| 193 |
EXAMPLES = """ |
| 194 |
# Basic example: Create a VM from a local cloud image |
| 195 |
- name: Create Ubuntu VM from local cloud image |
| 196 |
community.libvirt.virt_cloud_instance: |
| 197 |
name: ubuntu-vm-01 |
| 198 |
base_image: /srv/images/ubuntu-22.04-server-cloudimg-amd64.img |
| 199 |
disks: |
| 200 |
- path: /var/lib/libvirt/images/ubuntu-vm-01.qcow2 |
| 201 |
size: 20 |
| 202 |
format: qcow2 |
| 203 |
memory: 2048 |
| 204 |
vcpus: 2 |
| 205 |
networks: |
| 206 |
- network: default |
| 207 |
|
| 208 |
# Download cloud image from URL with checksum validation |
| 209 |
- name: Create VM from remote Ubuntu cloud image |
| 210 |
community.libvirt.virt_cloud_instance: |
| 211 |
name: ubuntu-vm-02 |
| 212 |
base_image: https://cloud-images.ubuntu.com/releases/22.04/release/ubuntu-22.04-server-cloudimg-amd64.img |
| 213 |
image_cache_dir: /srv/cloud-images |
| 214 |
image_checksum: sha256:https://cloud-images.ubuntu.com/releases/22.04/release/SHA256SUMS |
| 215 |
disks: |
| 216 |
- path: /var/lib/libvirt/images/ubuntu-vm-02.qcow2 |
| 217 |
size: 30 |
| 218 |
format: qcow2 |
| 219 |
memory: 4096 |
| 220 |
vcpus: 4 |
| 221 |
networks: |
| 222 |
- network: default |
| 223 |
|
| 224 |
# Advanced example with cloud-init configuration |
| 225 |
- name: Create VM with cloud-init user data |
| 226 |
community.libvirt.virt_cloud_instance: |
| 227 |
name: web-server-01 |
| 228 |
base_image: /srv/images/ubuntu-22.04-server-cloudimg-amd64.img |
| 229 |
disks: |
| 230 |
- path: /var/lib/libvirt/images/web-server-01.qcow2 |
| 231 |
size: 50 |
| 232 |
format: qcow2 |
| 233 |
memory: 8192 |
| 234 |
vcpus: 4 |
| 235 |
networks: |
| 236 |
- network: default |
| 237 |
mac: 52:54:00:12:34:56 |
| 238 |
cloud_init: |
| 239 |
user_data: | |
| 240 |
#cloud-config |
| 241 |
users: |
| 242 |
- name: ansible |
| 243 |
groups: sudo |
| 244 |
shell: /bin/bash |
| 245 |
sudo: 'ALL=(ALL) NOPASSWD:ALL' |
| 246 |
ssh_authorized_keys: |
| 247 |
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAB... user@host |
| 248 |
packages: |
| 249 |
- nginx |
| 250 |
- htop |
| 251 |
- vim |
| 252 |
runcmd: |
| 253 |
- systemctl enable nginx |
| 254 |
- systemctl start nginx |
| 255 |
meta_data: |
| 256 |
instance-id: web-server-01 |
| 257 |
local-hostname: web-server-01 |
| 258 |
|
| 259 |
# Force overwrite existing disk files |
| 260 |
- name: Create VM and force overwrite existing disk |
| 261 |
community.libvirt.virt_cloud_instance: |
| 262 |
name: test-vm |
| 263 |
base_image: /srv/images/ubuntu-22.04-server-cloudimg-amd64.img |
| 264 |
force_disk: true |
| 265 |
disks: |
| 266 |
- path: /var/lib/libvirt/images/test-vm.qcow2 |
| 267 |
size: 20 |
| 268 |
format: qcow2 |
| 269 |
memory: 2048 |
| 270 |
vcpus: 2 |
| 271 |
networks: |
| 272 |
- network: default |
| 273 |
""" |
| 274 |
|
| 275 |
RETURN = r""" |
| 276 |
base_image_path: |
| 277 |
description: |
| 278 |
- Path to the base cloud image file. |
| 279 |
- This is the local path where the image was downloaded to (if URL was provided) or the original local path. |
| 280 |
type: str |
| 281 |
returned: success |
| 282 |
sample: "/srv/cloud-images/ubuntu-20.04-server-cloudimg-amd64.img" |
| 283 |
commands: |
| 284 |
description: |
| 285 |
- List of commands executed by this module during VM provisioning. |
| 286 |
- Includes qemu-img commands for disk preparation and the virt-install command to create the VM. |
| 287 |
- Only populated when a VM is created or recreated (V(state=present) and VM did not already exist, or V(recreate=true)). |
| 288 |
- In check mode, the virt-install command includes the C(--dry-run) flag. |
| 289 |
type: list |
| 290 |
elements: str |
| 291 |
returned: when a VM was created or recreated |
| 292 |
version_added: "2.2.0" |
| 293 |
sample: |
| 294 |
- "qemu-img resize /var/lib/libvirt/images/test.qcow2 20G" |
| 295 |
- "virt-install --name test-vm --memory 2048 --vcpus 2 --import --disk path=/var/lib/libvirt/images/test.qcow2" |
| 296 |
""" |
| 297 |
|
| 298 |
|
| 299 |
import os |
| 300 |
import re |
| 301 |
from urllib.parse import urlparse |
| 302 |
from ansible_collections.community.libvirt.plugins.module_utils import virt_install as virtinst_util |
| 303 |
from ansible_collections.community.libvirt.plugins.module_utils.virt_install import ( |
| 304 |
LibvirtWrapper, VirtInstallTool |
| 305 |
) |
| 306 |
from ansible_collections.community.libvirt.plugins.module_utils.libvirt import ( |
| 307 |
HAS_VIRT, HAS_XML, VMNotFound, VIRT_SUCCESS |
| 308 |
) |
| 309 |
from ansible_collections.community.libvirt.plugins.module_utils.qemu import QemuImgTool |
| 310 |
from ansible.module_utils.basic import AnsibleModule |
| 311 |
from ansible.module_utils.urls import fetch_file, fetch_url |
| 312 |
|
| 313 |
|
| 314 |
class BaseImageOperator(object): |
| 315 |
def __init__(self, module, base_image, image_cache_dir=None, image_checksum=None): |
| 316 |
self.module = module |
| 317 |
self.base_image = base_image |
| 318 |
self.image_cache_dir = image_cache_dir |
| 319 |
self.image_checksum = image_checksum |
| 320 |
self.base_image_path = None |
| 321 |
self.system_disk_path = None |
| 322 |
self._executed_commands = [] |
| 323 |
|
| 324 |
def get_commands(self): |
| 325 |
"""Return list of commands that have been executed.""" |
| 326 |
return self._executed_commands |
| 327 |
|
| 328 |
def fetch_image(self, force_pull, timeout=None): |
| 329 |
""" |
| 330 |
Fetch cloud image from URL or use local file. |
| 331 |
|
| 332 |
This operation may download and create files, so it respects check_mode. |
| 333 |
In check_mode, image download is skipped but local files are still validated. |
| 334 |
""" |
| 335 |
parsed_url = urlparse(self.base_image) |
| 336 |
|
| 337 |
if parsed_url.scheme not in ('http', 'https', 'ftp'): |
| 338 |
# The base image is a local file path |
| 339 |
if not os.path.exists(self.base_image): |
| 340 |
self.module.fail_json( |
| 341 |
msg="Base image file does not exist: %s" % self.base_image) |
| 342 |
self.base_image_path = self.base_image |
| 343 |
return self.base_image_path |
| 344 |
|
| 345 |
filename = os.path.basename(parsed_url.path) |
| 346 |
if not filename: |
| 347 |
self.module.fail_json( |
| 348 |
msg="Failed to determine filename from base image URL: %s" % self.base_image) |
| 349 |
|
| 350 |
if self.image_cache_dir: |
| 351 |
image_path = os.path.join(self.image_cache_dir, filename) |
| 352 |
if os.path.exists(image_path) and not force_pull: |
| 353 |
self.base_image_path = image_path |
| 354 |
return self.base_image_path |
| 355 |
else: |
| 356 |
image_path = os.path.join(self.module.tmpdir, filename) |
| 357 |
|
| 358 |
# Check if we're in check mode |
| 359 |
if self.module.check_mode: |
| 360 |
# In check mode, don't download but set the expected path |
| 361 |
self.base_image_path = image_path |
| 362 |
return self.base_image_path |
| 363 |
|
| 364 |
temp_file = fetch_file(self.module, self.base_image, timeout=timeout) |
| 365 |
self.module.atomic_move(temp_file, image_path) |
| 366 |
|
| 367 |
self.base_image_path = image_path |
| 368 |
return self.base_image_path |
| 369 |
|
| 370 |
def _resolve_system_disk(self, disk_param): |
| 371 |
# TODO: Support specifying the system disk as a pool volume |
| 372 |
|
| 373 |
if not disk_param.get('path'): |
| 374 |
raise ValueError( |
| 375 |
"The first disk must have a path to import the cloud image") |
| 376 |
|
| 377 |
self.system_disk_path = disk_param.get('path') |
| 378 |
|
| 379 |
return disk_param |
| 380 |
|
| 381 |
def validate_checksum(self): |
| 382 |
""" |
| 383 |
Validate the checksum of the base image. |
| 384 |
|
| 385 |
This operation is read-only but depends on the actual file. |
| 386 |
In check_mode, validation is skipped if the file doesn't exist locally. |
| 387 |
""" |
| 388 |
if not self.image_checksum: |
| 389 |
return True |
| 390 |
|
| 391 |
# In check_mode, skip validation if file doesn't exist |
| 392 |
# (e.g., when base_image is a URL that wasn't downloaded) |
| 393 |
if self.module.check_mode and (not self.base_image_path or not os.path.exists(self.base_image_path)): |
| 394 |
return True # Assume validation would pass in check_mode |
| 395 |
|
| 396 |
if not self.base_image_path or not os.path.exists(self.base_image_path): |
| 397 |
self.module.fail_json( |
| 398 |
msg="Base image path not found for checksum validation") |
| 399 |
|
| 400 |
# Parse checksum format: <algorithm>:<checksum|url> |
| 401 |
try: |
| 402 |
algorithm, checksum_expr = self.image_checksum.split(':', 1) |
| 403 |
except ValueError: |
| 404 |
self.module.fail_json( |
| 405 |
msg="The image_checksum parameter has to be in format <algorithm>:<checksum>") |
| 406 |
|
| 407 |
# Check if checksum is a URL |
| 408 |
parsed_url = urlparse(checksum_expr) |
| 409 |
if parsed_url.scheme in ('http', 'https', 'ftp'): |
| 410 |
checksum = self._fetch_checksum_from_url(checksum_expr, algorithm) |
| 411 |
else: |
| 412 |
checksum = checksum_expr |
| 413 |
|
| 414 |
# Remove any non-alphanumeric characters and convert to lowercase |
| 415 |
checksum = re.sub(r'\W+', '', checksum).lower() |
| 416 |
|
| 417 |
# Ensure the checksum portion is a hexdigest |
| 418 |
try: |
| 419 |
int(checksum, 16) |
| 420 |
except ValueError: |
| 421 |
self.module.fail_json(msg='The checksum format is invalid') |
| 422 |
|
| 423 |
# Calculate the actual checksum of the file |
| 424 |
actual_checksum = None |
| 425 |
try: |
| 426 |
actual_checksum = self.module.digest_from_file( |
| 427 |
self.base_image_path, algorithm) |
| 428 |
except ValueError as e: |
| 429 |
self.module.fail_json( |
| 430 |
msg="Failed to calculate the actual checksum of the file: %s" % str(e)) |
| 431 |
|
| 432 |
# Compare checksums |
| 433 |
return checksum == actual_checksum |
| 434 |
|
| 435 |
def _fetch_checksum_from_url(self, checksum_url, algorithm): |
| 436 |
# Download checksum file |
| 437 |
response, info = fetch_url(self.module, checksum_url, timeout=60) |
| 438 |
if response is None: |
| 439 |
self.module.fail_json(msg="Failed to download checksum from %s: %s" % ( |
| 440 |
checksum_url, info.get('msg', 'Unknown error'))) |
| 441 |
|
| 442 |
try: |
| 443 |
checksum_content = response.read().decode('utf-8') |
| 444 |
finally: |
| 445 |
response.close() |
| 446 |
|
| 447 |
lines = [line.rstrip('\n') for line in checksum_content.splitlines()] |
| 448 |
checksum_map = [] |
| 449 |
|
| 450 |
# Get the filename from the base image URL for matching |
| 451 |
filename = os.path.basename(urlparse(self.base_image).path) |
| 452 |
|
| 453 |
if len(lines) == 1 and len(lines[0].split()) == 1: |
| 454 |
# Only a single line with a single string - treat it as a checksum only file |
| 455 |
checksum_map.append((lines[0], filename)) |
| 456 |
else: |
| 457 |
# The file is in the format of "checksum filename" |
| 458 |
for line in lines: |
| 459 |
# Split by one whitespace to keep the leading type char ' ' (whitespace) for text and '*' for binary |
| 460 |
parts = line.split(" ", 1) |
| 461 |
if len(parts) == 2: |
| 462 |
# Remove the leading type char if present |
| 463 |
if parts[1].startswith((" ", "*")): |
| 464 |
parts[1] = parts[1][1:] |
| 465 |
|
| 466 |
# Append checksum and path without potential leading './' |
| 467 |
checksum_map.append((parts[0], parts[1].lstrip("./"))) |
| 468 |
|
| 469 |
# Look through each line in the checksum file for a hash corresponding to |
| 470 |
# the filename in the url, returning the first hash that is found. |
| 471 |
for cksum in (s for (s, f) in checksum_map if f == filename): |
| 472 |
return cksum |
| 473 |
|
| 474 |
self.module.fail_json( |
| 475 |
msg="Unable to find a checksum for file '%s' in '%s'" % (filename, checksum_url)) |
| 476 |
|
| 477 |
def build_system_disk(self, disk_param, force_disk=False): |
| 478 |
""" |
| 479 |
Build system disk from base image. |
| 480 |
|
| 481 |
This operation creates and modifies disk files, so it respects check_mode. |
| 482 |
In check_mode, validation is performed but no files are created or modified. |
| 483 |
|
| 484 |
Args: |
| 485 |
disk_param: Disk configuration dictionary |
| 486 |
force_disk: If True, remove existing disk file before creating new one |
| 487 |
|
| 488 |
Returns: |
| 489 |
dict: The system disk configuration |
| 490 |
""" |
| 491 |
system_disk = self._resolve_system_disk(disk_param) |
| 492 |
disk_path = self.system_disk_path |
| 493 |
base_image_path = self.base_image_path |
| 494 |
|
| 495 |
if os.path.exists(disk_path): |
| 496 |
if force_disk: |
| 497 |
# In check_mode, don't actually delete the file |
| 498 |
if not self.module.check_mode: |
| 499 |
os.remove(disk_path) |
| 500 |
self.module.log("Removed existing disk file: %s" % disk_path) |
| 501 |
else: |
| 502 |
self.module.fail_json( |
| 503 |
msg="The system disk file already exists: %s" % disk_path) |
| 504 |
|
| 505 |
qemuImgTool = QemuImgTool(self.module) |
| 506 |
|
| 507 |
# Get base image info - this is read-only and should work in check_mode |
| 508 |
# However, if we're in check_mode and the base image doesn't exist locally, |
| 509 |
# we may need to skip this check |
| 510 |
if self.module.check_mode and not os.path.exists(base_image_path): |
| 511 |
# In check mode with non-existent base image, create mock info for validation |
| 512 |
base_image_format = "qcow2" # Assume common format |
| 513 |
base_image_raw_size = 1 * 1024 * 1024 * 1024 # Assume 1GB minimum |
| 514 |
else: |
| 515 |
rc, image_info, stderr = qemuImgTool.info(base_image_path) |
| 516 |
if rc != 0: |
| 517 |
self.module.fail_json( |
| 518 |
msg="Failed to get base image info: %s" % stderr) |
| 519 |
base_image_format = image_info.get('format') |
| 520 |
base_image_raw_size = image_info.get('virtual-size') |
| 521 |
|
| 522 |
system_disk_format = system_disk.get('format', "qcow2") |
| 523 |
system_disk_size = system_disk.get('size') |
| 524 |
if not base_image_format: |
| 525 |
self.module.fail_json( |
| 526 |
msg="No valid format found for the base image: %s" % base_image_path) |
| 527 |
if not system_disk_size or not isinstance(system_disk_size, int): |
| 528 |
self.module.fail_json( |
| 529 |
msg="The system disk size must be an integer") |
| 530 |
system_disk_raw_size = system_disk_size * 1024 * 1024 * 1024 |
| 531 |
if system_disk_raw_size < base_image_raw_size: |
| 532 |
self.module.fail_json(msg="The system disk size is too small to import the base image: %s < %s" % ( |
| 533 |
system_disk_raw_size, base_image_raw_size)) |
| 534 |
|
| 535 |
# Check if we're in check mode |
| 536 |
if self.module.check_mode: |
| 537 |
# In check mode, don't create files but return the disk configuration |
| 538 |
return system_disk |
| 539 |
|
| 540 |
if base_image_format != system_disk_format: |
| 541 |
rc, stdout, stderr = qemuImgTool.convert( |
| 542 |
base_image_path, disk_path, source_format=base_image_format, output_format=system_disk_format) |
| 543 |
if rc != 0: |
| 544 |
self.module.fail_json( |
| 545 |
msg="Failed to convert base image to system disk: %s" % stderr) |
| 546 |
else: |
| 547 |
self.module.preserved_copy(base_image_path, disk_path) |
| 548 |
|
| 549 |
rc, stdout, stderr = qemuImgTool.resize( |
| 550 |
disk_path, "%dG" % system_disk_size) |
| 551 |
if rc != 0: |
| 552 |
self.module.fail_json( |
| 553 |
msg="Failed to resize system disk: %s" % stderr) |
| 554 |
|
| 555 |
# Collect executed commands from qemuImgTool |
| 556 |
self._executed_commands.extend(qemuImgTool.get_commands()) |
| 557 |
|
| 558 |
for key in ['format', 'size']: |
| 559 |
if key in system_disk: |
| 560 |
del system_disk[key] |
| 561 |
|
| 562 |
return system_disk |
| 563 |
|
| 564 |
|
| 565 |
def validate_disks(disks): |
| 566 |
if not isinstance(disks, list) \ |
| 567 |
or len(disks) < 1: |
| 568 |
raise ValueError("At least one disk is required") |
| 569 |
|
| 570 |
system_disk = disks[0] |
| 571 |
|
| 572 |
if not (system_disk.get('path') or system_disk.get('pool')): |
| 573 |
raise ValueError( |
| 574 |
"The first disk must have either 'path' or 'pool' to import the cloud image") |
| 575 |
|
| 576 |
if not system_disk.get('size'): |
| 577 |
raise ValueError("The first disk must have a size") |
| 578 |
|
| 579 |
|
| 580 |
def update_virtinst_params(module, virtInstall, system_disk, extra_user_data=None): |
| 581 |
disks = virtInstall.params.get('disks') |
| 582 |
|
| 583 |
if not isinstance(disks, list) \ |
| 584 |
or len(disks) < 1: |
| 585 |
raise ValueError("At least one disk is required") |
| 586 |
|
| 587 |
virtInstall.params['disks'][0] = system_disk |
| 588 |
virtInstall.params['import'] = True |
| 589 |
|
| 590 |
if extra_user_data: |
| 591 |
if virtInstall.params.get('cloud_init') is None: |
| 592 |
virtInstall.params['cloud_init'] = {} |
| 593 |
|
| 594 |
orignal_user_data = virtInstall.params['cloud_init'].get('user_data', "") |
| 595 |
|
| 596 |
if isinstance(orignal_user_data, dict): |
| 597 |
try: |
| 598 |
import yaml |
| 599 |
orignal_user_data = yaml.safe_dump(orignal_user_data, default_flow_style=False, allow_unicode=True) |
| 600 |
except ImportError: |
| 601 |
module.fail_json( |
| 602 |
msg="PyYAML is required to process dictionary cloud-init parameters") |
| 603 |
|
| 604 |
modified_user_data = orignal_user_data + extra_user_data |
| 605 |
virtInstall.params['cloud_init']['user_data'] = modified_user_data |
| 606 |
|
| 607 |
|
| 608 |
def get_autoreboot_user_data(): |
| 609 |
return """ |
| 610 |
# appended by virt_cloud_instance module |
| 611 |
power_state: |
| 612 |
delay: 1 |
| 613 |
mode: reboot |
| 614 |
message: Rebooting for cloud instance provisioning |
| 615 |
""" |
| 616 |
|
| 617 |
|
| 618 |
def core(module): |
| 619 |
state = module.params.get('state') |
| 620 |
name = module.params.get('name') |
| 621 |
recreate = module.params.get('recreate', False) |
| 622 |
base_image = module.params.get('base_image') |
| 623 |
image_cache_dir = module.params.get('image_cache_dir') |
| 624 |
force_pull = module.params.get('force_pull', False) |
| 625 |
force_disk = module.params.get('force_disk', False) |
| 626 |
disks = module.params.get('disks', []) |
| 627 |
image_checksum = module.params.get('image_checksum') |
| 628 |
url_timeout = module.params.get('url_timeout') |
| 629 |
wait_for_cloud_init_reboot = module.params.get('wait_for_cloud_init_reboot', True) |
| 630 |
cloud_init_auto_reboot = module.params.get('cloud_init_auto_reboot', True) |
| 631 |
cloud_init_reboot_timeout = module.params.get('cloud_init_reboot_timeout') |
| 632 |
|
| 633 |
validate_disks(disks) |
| 634 |
|
| 635 |
result = dict( |
| 636 |
changed=False, |
| 637 |
original_message="", # TODO: Remove this unused return field in v3.0.0 |
| 638 |
message="", |
| 639 |
base_image_path="", |
| 640 |
commands=[], |
| 641 |
) |
| 642 |
|
| 643 |
virtConn = LibvirtWrapper(module) |
| 644 |
virtInstall = VirtInstallTool(module) |
| 645 |
|
| 646 |
if not name: |
| 647 |
module.fail_json(msg="virtual machine name is missing") |
| 648 |
|
| 649 |
if not base_image: |
| 650 |
module.fail_json(msg="base_image parameter is required") |
| 651 |
|
| 652 |
vm_exists = False |
| 653 |
try: |
| 654 |
vm = virtConn.find_vm(name) |
| 655 |
vm_exists = True |
| 656 |
except VMNotFound: |
| 657 |
vm_exists = False |
| 658 |
|
| 659 |
if state == 'present': |
| 660 |
if vm_exists and not recreate: |
| 661 |
result['message'] = "virtual machine '%s' already exists" % name |
| 662 |
return VIRT_SUCCESS, result |
| 663 |
elif vm_exists and recreate: |
| 664 |
# In check_mode, skip VM destruction but continue with validation |
| 665 |
if not module.check_mode: |
| 666 |
if vm.isActive(): |
| 667 |
virtConn.destroy(name) |
| 668 |
virtConn.undefine(name) |
| 669 |
|
| 670 |
# Create image operator only when we need to process the image |
| 671 |
image_operator = BaseImageOperator(module, base_image, |
| 672 |
image_cache_dir=image_cache_dir, |
| 673 |
image_checksum=image_checksum) |
| 674 |
image_operator.fetch_image(force_pull, timeout=url_timeout) |
| 675 |
if not image_operator.validate_checksum(): |
| 676 |
module.fail_json( |
| 677 |
msg="The checksum of the base image does not match the expected value") |
| 678 |
system_disk = image_operator.build_system_disk(disks[0], force_disk=force_disk) |
| 679 |
|
| 680 |
# Add base_image_path to result |
| 681 |
result['base_image_path'] = image_operator.base_image_path |
| 682 |
result['commands'].extend(image_operator.get_commands()) |
| 683 |
|
| 684 |
extra_user_data = None |
| 685 |
if wait_for_cloud_init_reboot and cloud_init_auto_reboot: |
| 686 |
extra_user_data = get_autoreboot_user_data() |
| 687 |
|
| 688 |
wait_timeout = None |
| 689 |
if wait_for_cloud_init_reboot: |
| 690 |
wait_timeout = cloud_init_reboot_timeout |
| 691 |
|
| 692 |
# run virt-install to create new vm |
| 693 |
update_virtinst_params(module, virtInstall, system_disk, extra_user_data) |
| 694 |
changed, rc, extra_res = virtInstall.execute(dryrun=module.check_mode, wait_timeout=wait_timeout) |
| 695 |
result['commands'].extend(virtInstall.get_commands()) |
| 696 |
result['changed'] = changed |
| 697 |
result.update(extra_res) |
| 698 |
|
| 699 |
if wait_for_cloud_init_reboot and rc == 0: |
| 700 |
virtConn.create(name) |
| 701 |
|
| 702 |
return rc, result |
| 703 |
elif state == 'absent': |
| 704 |
if not vm_exists: |
| 705 |
result['message'] = "virtual machine '%s' is already absent" % name |
| 706 |
return VIRT_SUCCESS, result |
| 707 |
|
| 708 |
if not module.check_mode: |
| 709 |
if vm.isActive(): |
| 710 |
virtConn.destroy(name) |
| 711 |
virtConn.undefine(name) |
| 712 |
|
| 713 |
result["changed"] = True |
| 714 |
return VIRT_SUCCESS, result |
| 715 |
|
| 716 |
module.fail_json(msg="unsupported state '%s'" % state) |
| 717 |
|
| 718 |
|
| 719 |
def main(): |
| 720 |
"""Main module entry point""" |
| 721 |
|
| 722 |
# Define argument specification |
| 723 |
argument_spec = dict( |
| 724 |
# Connection options |
| 725 |
uri=dict(type='str', default="qemu:///system"), |
| 726 |
# Basic VM options |
| 727 |
name=dict(type='str', required=True), |
| 728 |
state=dict( |
| 729 |
type='str', |
| 730 |
choices=['present', 'absent'], |
| 731 |
default='present'), |
| 732 |
recreate=dict(type='bool', default=False), |
| 733 |
# Cloud image specific options |
| 734 |
base_image=dict(type='str', required=True), |
| 735 |
image_cache_dir=dict(type='path'), |
| 736 |
force_pull=dict(type='bool', default=False), |
| 737 |
force_disk=dict(type='bool', default=False), |
| 738 |
image_checksum=dict(type='str'), |
| 739 |
url_timeout=dict(type='int', default=60), |
| 740 |
url_username=dict(type='str'), |
| 741 |
url_password=dict(type='str', no_log=True), |
| 742 |
wait_for_cloud_init_reboot=dict(type='bool', default=True), |
| 743 |
cloud_init_auto_reboot=dict(type='bool', default=True), |
| 744 |
cloud_init_reboot_timeout=dict(type='int', default=600), |
| 745 |
) |
| 746 |
|
| 747 |
# Cloud-init options |
| 748 |
argument_spec.update(virtinst_util.get_cloud_init_args()) |
| 749 |
# General options |
| 750 |
argument_spec.update(virtinst_util.get_memory_args()) |
| 751 |
argument_spec.update(virtinst_util.get_memorybacking_args()) |
| 752 |
argument_spec.update(virtinst_util.get_arch_args()) |
| 753 |
argument_spec.update(virtinst_util.get_machine_args()) |
| 754 |
argument_spec.update(virtinst_util.get_metadata_args()) |
| 755 |
argument_spec.update(virtinst_util.get_events_args()) |
| 756 |
argument_spec.update(virtinst_util.get_resource_args()) |
| 757 |
argument_spec.update(virtinst_util.get_sysinfo_args()) |
| 758 |
argument_spec.update(virtinst_util.get_qmeu_commandline_args()) |
| 759 |
argument_spec.update(virtinst_util.get_vcpu_args()) |
| 760 |
argument_spec.update(virtinst_util.get_numatune_args()) |
| 761 |
argument_spec.update(virtinst_util.get_memtune_args()) |
| 762 |
argument_spec.update(virtinst_util.get_blkiotune_args()) |
| 763 |
argument_spec.update(virtinst_util.get_cpu_args()) |
| 764 |
argument_spec.update(virtinst_util.get_cputune_args()) |
| 765 |
argument_spec.update(virtinst_util.get_security_args()) |
| 766 |
argument_spec.update(virtinst_util.get_keywrap_args()) |
| 767 |
argument_spec.update(virtinst_util.get_iothreads_args()) |
| 768 |
argument_spec.update(virtinst_util.get_features_args()) |
| 769 |
argument_spec.update(virtinst_util.get_clock_args()) |
| 770 |
argument_spec.update(virtinst_util.get_pm_args()) |
| 771 |
argument_spec.update(virtinst_util.get_launch_security_args()) |
| 772 |
# Boot options |
| 773 |
argument_spec.update(virtinst_util.get_boot_args()) |
| 774 |
# Guest OS options |
| 775 |
argument_spec.update(virtinst_util.get_osinfo_args()) |
| 776 |
# Storage options |
| 777 |
argument_spec.update(virtinst_util.get_disks_args()) |
| 778 |
argument_spec.update(virtinst_util.get_filesystems_args()) |
| 779 |
# Network options |
| 780 |
argument_spec.update(virtinst_util.get_networks_args()) |
| 781 |
# Graphics options |
| 782 |
argument_spec.update(virtinst_util.get_graphics_args()) |
| 783 |
# Virtualization options |
| 784 |
argument_spec.update(virtinst_util.get_virt_type_args()) |
| 785 |
argument_spec.update(virtinst_util.get_hvm_args()) |
| 786 |
argument_spec.update(virtinst_util.get_paravirt_args()) |
| 787 |
# Device options |
| 788 |
argument_spec.update(virtinst_util.get_controller_args()) |
| 789 |
argument_spec.update(virtinst_util.get_input_args()) |
| 790 |
argument_spec.update(virtinst_util.get_hostdev_args()) |
| 791 |
argument_spec.update(virtinst_util.get_sound_args()) |
| 792 |
argument_spec.update(virtinst_util.get_audio_args()) |
| 793 |
argument_spec.update(virtinst_util.get_watchdog_args()) |
| 794 |
argument_spec.update(virtinst_util.get_serial_args()) |
| 795 |
argument_spec.update(virtinst_util.get_parallel_args()) |
| 796 |
argument_spec.update(virtinst_util.get_channel_args()) |
| 797 |
argument_spec.update(virtinst_util.get_console_args()) |
| 798 |
argument_spec.update(virtinst_util.get_video_args()) |
| 799 |
argument_spec.update(virtinst_util.get_smartcard_args()) |
| 800 |
argument_spec.update(virtinst_util.get_redirdev_args()) |
| 801 |
argument_spec.update(virtinst_util.get_memballoon_args()) |
| 802 |
argument_spec.update(virtinst_util.get_tpm_args()) |
| 803 |
argument_spec.update(virtinst_util.get_rng_args()) |
| 804 |
argument_spec.update(virtinst_util.get_panic_args()) |
| 805 |
argument_spec.update(virtinst_util.get_shmem_args()) |
| 806 |
argument_spec.update(virtinst_util.get_vsock_args()) |
| 807 |
argument_spec.update(virtinst_util.get_iommu_args()) |
| 808 |
# Miscellaneous options |
| 809 |
argument_spec.update(virtinst_util.get_autostart_args()) |
| 810 |
|
| 811 |
# Create module |
| 812 |
module = AnsibleModule( |
| 813 |
argument_spec=argument_spec, |
| 814 |
supports_check_mode=True) |
| 815 |
|
| 816 |
if not HAS_VIRT: |
| 817 |
module.fail_json( |
| 818 |
msg="The `libvirt` module is not importable. Check the requirements.") |
| 819 |
|
| 820 |
if not HAS_XML: |
| 821 |
module.fail_json( |
| 822 |
msg='The `lxml` module is not importable. Check the requirements.' |
| 823 |
) |
| 824 |
|
| 825 |
rc = VIRT_SUCCESS |
| 826 |
try: |
| 827 |
rc, result = core(module) |
| 828 |
except Exception as e: |
| 829 |
module.fail_json(msg=str(e)) |
| 830 |
|
| 831 |
if rc != 0: # something went wrong emit the msg |
| 832 |
module.fail_json(rc=rc, msg=result) |
| 833 |
else: |
| 834 |
module.exit_json(**result) |
| 835 |
|
| 836 |
|
| 837 |
if __name__ == "__main__": |
| 838 |
main() |