| 1 |
# Copyright (c) 2025, Sean McAvoy (@smcavoy) <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = """ |
| 8 |
--- |
| 9 |
module: lxd_storage_volume_info |
| 10 |
short_description: Retrieve information about LXD storage volumes |
| 11 |
version_added: 12.1.0 |
| 12 |
description: |
| 13 |
- Retrieve information about LXD storage volumes in a specific storage pool. |
| 14 |
- This module returns details about all volumes or a specific volume in a pool. |
| 15 |
author: "Sean McAvoy (@smcavoy)" |
| 16 |
extends_documentation_fragment: |
| 17 |
- community.general._attributes |
| 18 |
- community.general._attributes.info_module |
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: full |
| 22 |
diff_mode: |
| 23 |
support: none |
| 24 |
options: |
| 25 |
pool: |
| 26 |
description: |
| 27 |
- Name of the storage pool to query for volumes. |
| 28 |
- This parameter is required. |
| 29 |
required: true |
| 30 |
type: str |
| 31 |
name: |
| 32 |
description: |
| 33 |
- Name of a specific storage volume to retrieve information about. |
| 34 |
- If not specified, information about all volumes in the pool are returned. |
| 35 |
type: str |
| 36 |
type: |
| 37 |
description: |
| 38 |
- Filter volumes by type. |
| 39 |
- Common types include V(container), V(virtual-machine), V(image), and V(custom). |
| 40 |
- If not specified, all volume types are returned. |
| 41 |
type: str |
| 42 |
project: |
| 43 |
description: |
| 44 |
- 'Project of the storage volume. |
| 45 |
See U(https://documentation.ubuntu.com/lxd/en/latest/projects/).' |
| 46 |
type: str |
| 47 |
url: |
| 48 |
description: |
| 49 |
- The Unix domain socket path or the https URL for the LXD server. |
| 50 |
default: unix:/var/lib/lxd/unix.socket |
| 51 |
type: str |
| 52 |
snap_url: |
| 53 |
description: |
| 54 |
- The Unix domain socket path when LXD is installed by snap package manager. |
| 55 |
default: unix:/var/snap/lxd/common/lxd/unix.socket |
| 56 |
type: str |
| 57 |
client_key: |
| 58 |
description: |
| 59 |
- The client certificate key file path. |
| 60 |
- If not specified, it defaults to C($HOME/.config/lxc/client.key). |
| 61 |
aliases: [key_file] |
| 62 |
type: path |
| 63 |
client_cert: |
| 64 |
description: |
| 65 |
- The client certificate file path. |
| 66 |
- If not specified, it defaults to C($HOME/.config/lxc/client.crt). |
| 67 |
aliases: [cert_file] |
| 68 |
type: path |
| 69 |
trust_password: |
| 70 |
description: |
| 71 |
- The client trusted password. |
| 72 |
- 'You need to set this password on the LXD server before |
| 73 |
running this module using the following command: |
| 74 |
C(lxc config set core.trust_password <some random password>) |
| 75 |
See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/).' |
| 76 |
- If O(trust_password) is set, this module sends a request for |
| 77 |
authentication before sending any requests. |
| 78 |
type: str |
| 79 |
""" |
| 80 |
|
| 81 |
EXAMPLES = """ |
| 82 |
- name: Get information about all volumes in the default storage pool |
| 83 |
community.general.lxd_storage_volume_info: |
| 84 |
pool: default |
| 85 |
register: result |
| 86 |
|
| 87 |
- name: Get information about a specific volume |
| 88 |
community.general.lxd_storage_volume_info: |
| 89 |
pool: default |
| 90 |
name: my-volume |
| 91 |
register: result |
| 92 |
|
| 93 |
- name: Get information about all custom volumes in a pool |
| 94 |
community.general.lxd_storage_volume_info: |
| 95 |
pool: default |
| 96 |
type: custom |
| 97 |
register: result |
| 98 |
|
| 99 |
- name: Get volume information via HTTPS connection |
| 100 |
community.general.lxd_storage_volume_info: |
| 101 |
url: https://127.0.0.1:8443 |
| 102 |
trust_password: mypassword |
| 103 |
pool: default |
| 104 |
name: my-volume |
| 105 |
register: result |
| 106 |
|
| 107 |
- name: Get volume information for a specific project |
| 108 |
community.general.lxd_storage_volume_info: |
| 109 |
project: myproject |
| 110 |
pool: default |
| 111 |
register: result |
| 112 |
|
| 113 |
- name: Get container volumes only |
| 114 |
community.general.lxd_storage_volume_info: |
| 115 |
pool: default |
| 116 |
type: container |
| 117 |
register: result |
| 118 |
""" |
| 119 |
|
| 120 |
RETURN = """ |
| 121 |
storage_volumes: |
| 122 |
description: List of LXD storage volumes. |
| 123 |
returned: success |
| 124 |
type: list |
| 125 |
elements: dict |
| 126 |
sample: [ |
| 127 |
{ |
| 128 |
"name": "my-volume", |
| 129 |
"type": "custom", |
| 130 |
"used_by": [], |
| 131 |
"config": { |
| 132 |
"size": "10GiB" |
| 133 |
}, |
| 134 |
"description": "My custom volume", |
| 135 |
"content_type": "filesystem", |
| 136 |
"location": "none" |
| 137 |
} |
| 138 |
] |
| 139 |
contains: |
| 140 |
name: |
| 141 |
description: The name of the storage volume. |
| 142 |
type: str |
| 143 |
returned: success |
| 144 |
type: |
| 145 |
description: The type of the storage volume. |
| 146 |
type: str |
| 147 |
returned: success |
| 148 |
used_by: |
| 149 |
description: List of resources using this storage volume. |
| 150 |
type: list |
| 151 |
elements: str |
| 152 |
returned: success |
| 153 |
config: |
| 154 |
description: Configuration of the storage volume. |
| 155 |
type: dict |
| 156 |
returned: success |
| 157 |
description: |
| 158 |
description: Description of the storage volume. |
| 159 |
type: str |
| 160 |
returned: success |
| 161 |
content_type: |
| 162 |
description: Content type of the volume (filesystem or block). |
| 163 |
type: str |
| 164 |
returned: success |
| 165 |
location: |
| 166 |
description: Cluster member location for the volume. |
| 167 |
type: str |
| 168 |
returned: success |
| 169 |
logs: |
| 170 |
description: The logs of requests and responses. |
| 171 |
returned: when ansible-playbook is invoked with -vvvv. |
| 172 |
type: list |
| 173 |
elements: dict |
| 174 |
sample: [ |
| 175 |
{ |
| 176 |
"type": "sent request", |
| 177 |
"request": { |
| 178 |
"method": "GET", |
| 179 |
"url": "/1.0/storage-pools/default/volumes", |
| 180 |
"json": null, |
| 181 |
"timeout": null |
| 182 |
}, |
| 183 |
"response": { |
| 184 |
"json": {"type": "sync", "status": "Success"} |
| 185 |
} |
| 186 |
} |
| 187 |
] |
| 188 |
""" |
| 189 |
|
| 190 |
import os |
| 191 |
import typing as t |
| 192 |
from urllib.parse import quote, urlencode |
| 193 |
|
| 194 |
from ansible.module_utils.basic import AnsibleModule |
| 195 |
|
| 196 |
from ansible_collections.community.general.plugins.module_utils._lxd import ( |
| 197 |
LXDClient, |
| 198 |
LXDClientException, |
| 199 |
default_cert_file, |
| 200 |
default_key_file, |
| 201 |
) |
| 202 |
|
| 203 |
# ANSIBLE_LXD_DEFAULT_URL is a default value of the lxd endpoint |
| 204 |
ANSIBLE_LXD_DEFAULT_URL = "unix:/var/lib/lxd/unix.socket" |
| 205 |
ANSIBLE_LXD_DEFAULT_SNAP_URL = "unix:/var/snap/lxd/common/lxd/unix.socket" |
| 206 |
|
| 207 |
# API endpoints |
| 208 |
LXD_API_VERSION = "1.0" |
| 209 |
LXD_API_STORAGE_POOLS_ENDPOINT = f"/{LXD_API_VERSION}/storage-pools" |
| 210 |
|
| 211 |
|
| 212 |
class LXDStorageVolumeInfo: |
| 213 |
def __init__(self, module: AnsibleModule) -> None: |
| 214 |
"""Gather information about LXD storage volumes. |
| 215 |
|
| 216 |
:param module: Processed Ansible Module. |
| 217 |
:type module: AnsibleModule |
| 218 |
""" |
| 219 |
self.module = module |
| 220 |
self.pool = self.module.params["pool"] |
| 221 |
self.name = self.module.params["name"] |
| 222 |
self.volume_type = self.module.params["type"] |
| 223 |
self.project = self.module.params["project"] |
| 224 |
|
| 225 |
self.key_file = self.module.params["client_key"] |
| 226 |
if self.key_file is None: |
| 227 |
self.key_file = default_key_file() |
| 228 |
self.cert_file = self.module.params["client_cert"] |
| 229 |
if self.cert_file is None: |
| 230 |
self.cert_file = default_cert_file() |
| 231 |
self.debug = self.module._verbosity >= 4 |
| 232 |
|
| 233 |
# check if domain socket to be used |
| 234 |
snap_socket_path = self.module.params["snap_url"] |
| 235 |
if snap_socket_path.startswith("unix:"): |
| 236 |
snap_socket_path = snap_socket_path[5:] |
| 237 |
|
| 238 |
if self.module.params["url"] != ANSIBLE_LXD_DEFAULT_URL: |
| 239 |
self.url = self.module.params["url"] |
| 240 |
elif os.path.exists(snap_socket_path): |
| 241 |
self.url = self.module.params["snap_url"] |
| 242 |
else: |
| 243 |
self.url = self.module.params["url"] |
| 244 |
|
| 245 |
try: |
| 246 |
self.client = LXDClient( |
| 247 |
self.url, |
| 248 |
key_file=self.key_file, |
| 249 |
cert_file=self.cert_file, |
| 250 |
debug=self.debug, |
| 251 |
) |
| 252 |
except LXDClientException as e: |
| 253 |
self._fail_from_lxd_exception(e) |
| 254 |
|
| 255 |
self.trust_password = self.module.params["trust_password"] |
| 256 |
|
| 257 |
def _fail_from_lxd_exception(self, exception: LXDClientException) -> t.NoReturn: |
| 258 |
"""Build failure parameters from LXDClientException and fail. |
| 259 |
|
| 260 |
:param exception: The LXDClientException instance |
| 261 |
:type exception: LXDClientException |
| 262 |
""" |
| 263 |
fail_params = {} |
| 264 |
if self.client.debug and "logs" in exception.kwargs: |
| 265 |
fail_params["logs"] = exception.kwargs["logs"] |
| 266 |
self.module.fail_json(msg=exception.msg, changed=False, **fail_params) |
| 267 |
|
| 268 |
def _build_url(self, endpoint: str) -> str: |
| 269 |
"""Build URL with project parameter if specified.""" |
| 270 |
if self.project: |
| 271 |
return f"{endpoint}?{urlencode({'project': self.project})}" |
| 272 |
return endpoint |
| 273 |
|
| 274 |
def _check_pool_exists(self) -> None: |
| 275 |
"""Verify that the storage pool exists.""" |
| 276 |
url = self._build_url(f"{LXD_API_STORAGE_POOLS_ENDPOINT}/{quote(self.pool, safe='')}") |
| 277 |
resp_json = self.client.do("GET", url, ok_error_codes=[404]) |
| 278 |
|
| 279 |
if resp_json["type"] == "error": |
| 280 |
if resp_json.get("error_code") == 404: |
| 281 |
self.module.fail_json(msg=f'Storage pool "{self.pool}" not found') |
| 282 |
else: |
| 283 |
self.module.fail_json( |
| 284 |
msg=f'Failed to retrieve storage pool "{self.pool}": {resp_json.get("error", "Unknown error")}' |
| 285 |
) |
| 286 |
|
| 287 |
def _get_volume_list(self, recursion: int = 0) -> list: |
| 288 |
"""Get list of all volumes in the storage pool. |
| 289 |
|
| 290 |
:param recursion: API recursion level (0 for URLs only, 1 for full objects) |
| 291 |
:type recursion: int |
| 292 |
:return: List of volume URLs (recursion=0) or volume objects (recursion=1) |
| 293 |
:rtype: list |
| 294 |
""" |
| 295 |
endpoint = f"{LXD_API_STORAGE_POOLS_ENDPOINT}/{quote(self.pool, safe='')}/volumes" |
| 296 |
if recursion > 0: |
| 297 |
endpoint = f"{endpoint}?recursion={recursion}" |
| 298 |
url = self._build_url(endpoint) |
| 299 |
resp_json = self.client.do("GET", url, ok_error_codes=[]) |
| 300 |
|
| 301 |
if resp_json["type"] == "error": |
| 302 |
self.module.fail_json( |
| 303 |
msg=f'Failed to retrieve volumes from pool "{self.pool}": {resp_json.get("error", "Unknown error")}', |
| 304 |
error_code=resp_json.get("error_code"), |
| 305 |
) |
| 306 |
|
| 307 |
# With recursion=0: list of volume URLs like ['/1.0/storage-pools/default/volumes/custom/my-volume'] |
| 308 |
# With recursion=1: list of volume objects with full metadata |
| 309 |
return resp_json.get("metadata", []) |
| 310 |
|
| 311 |
def _get_volume_info(self, volume_type: str, volume_name: str) -> dict: |
| 312 |
"""Get detailed information about a specific storage volume.""" |
| 313 |
url = self._build_url( |
| 314 |
f"{LXD_API_STORAGE_POOLS_ENDPOINT}/{quote(self.pool, safe='')}/volumes/{quote(volume_type, safe='')}/{quote(volume_name, safe='')}" |
| 315 |
) |
| 316 |
resp_json = self.client.do("GET", url, ok_error_codes=[404]) |
| 317 |
|
| 318 |
if resp_json["type"] == "error": |
| 319 |
if resp_json.get("error_code") == 404: |
| 320 |
self.module.fail_json( |
| 321 |
msg=f'Storage volume "{volume_name}" of type "{volume_type}" not found in pool "{self.pool}"' |
| 322 |
) |
| 323 |
else: |
| 324 |
self.module.fail_json( |
| 325 |
msg=f'Failed to retrieve volume "{volume_name}" of type "{volume_type}": {resp_json.get("error", "Unknown error")}' |
| 326 |
) |
| 327 |
|
| 328 |
return resp_json.get("metadata", {}) |
| 329 |
|
| 330 |
def get_storage_volumes(self) -> list[dict]: |
| 331 |
"""Retrieve storage volume information based on module parameters.""" |
| 332 |
# First check if the pool exists |
| 333 |
self._check_pool_exists() |
| 334 |
|
| 335 |
storage_volumes = [] |
| 336 |
|
| 337 |
if self.name: |
| 338 |
# Get information about a specific volume |
| 339 |
# We need to determine the type if not specified |
| 340 |
if self.volume_type: |
| 341 |
volume_info = self._get_volume_info(self.volume_type, self.name) |
| 342 |
storage_volumes.append(volume_info) |
| 343 |
else: |
| 344 |
# Try to find the volume by name using recursion for efficiency |
| 345 |
# This gets all volume objects in a single API call |
| 346 |
volumes = self._get_volume_list(recursion=1) |
| 347 |
found = False |
| 348 |
for volume in volumes: |
| 349 |
if volume.get("name") == self.name: |
| 350 |
storage_volumes.append(volume) |
| 351 |
found = True |
| 352 |
break |
| 353 |
|
| 354 |
if not found: |
| 355 |
self.module.fail_json(msg=f'Storage volume "{self.name}" not found in pool "{self.pool}"') |
| 356 |
else: |
| 357 |
# Get information about all volumes in the pool using recursion |
| 358 |
# This retrieves all volume details in a single API call instead of one call per volume |
| 359 |
volumes = self._get_volume_list(recursion=1) |
| 360 |
for volume in volumes: |
| 361 |
# Apply type filter if specified |
| 362 |
if self.volume_type and volume.get("type") != self.volume_type: |
| 363 |
continue |
| 364 |
storage_volumes.append(volume) |
| 365 |
|
| 366 |
return storage_volumes |
| 367 |
|
| 368 |
def run(self) -> None: |
| 369 |
"""Run the main method.""" |
| 370 |
try: |
| 371 |
if self.trust_password is not None: |
| 372 |
self.client.authenticate(self.trust_password) |
| 373 |
|
| 374 |
storage_volumes = self.get_storage_volumes() |
| 375 |
|
| 376 |
result_json = {"storage_volumes": storage_volumes} |
| 377 |
if self.client.debug: |
| 378 |
result_json["logs"] = self.client.logs |
| 379 |
self.module.exit_json(**result_json) |
| 380 |
except LXDClientException as e: |
| 381 |
self._fail_from_lxd_exception(e) |
| 382 |
|
| 383 |
|
| 384 |
def main() -> None: |
| 385 |
"""Ansible Main module.""" |
| 386 |
module = AnsibleModule( |
| 387 |
argument_spec=dict( |
| 388 |
pool=dict(type="str", required=True), |
| 389 |
name=dict(type="str"), |
| 390 |
type=dict(type="str"), |
| 391 |
project=dict(type="str"), |
| 392 |
url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_URL), |
| 393 |
snap_url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_SNAP_URL), |
| 394 |
client_key=dict(type="path", aliases=["key_file"]), |
| 395 |
client_cert=dict(type="path", aliases=["cert_file"]), |
| 396 |
trust_password=dict(type="str", no_log=True), |
| 397 |
), |
| 398 |
supports_check_mode=True, |
| 399 |
) |
| 400 |
|
| 401 |
lxd_info = LXDStorageVolumeInfo(module=module) |
| 402 |
lxd_info.run() |
| 403 |
|
| 404 |
|
| 405 |
if __name__ == "__main__": |
| 406 |
main() |