Debian Codegraph @

ansible_collections/community/general/plugins/modules/lxd_storage_pool_info.py

raw
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_pool_info
10 short_description: Retrieve information about LXD storage pools
11 version_added: 12.1.0
12 description:
13 - Retrieve information about LXD storage pools.
14 - This module returns details about all storage pools or a specific storage 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 name:
26 description:
27 - Name of a specific storage pool to retrieve information about.
28 - If not specified, information about all storage pools are returned.
29 type: str
30 type:
31 description:
32 - Filter storage pools by driver/type (for example V(dir), V(zfs), V(btrfs), V(lvm), or V(ceph)).
33 - If not specified, all storage pool types are returned.
34 - Can be a single type or a list of types.
35 type: list
36 elements: str
37 default: []
38 project:
39 description:
40 - 'Project of the storage pool.
41 See U(https://documentation.ubuntu.com/lxd/en/latest/projects/).'
42 type: str
43 url:
44 description:
45 - The Unix domain socket path or the https URL for the LXD server.
46 default: unix:/var/lib/lxd/unix.socket
47 type: str
48 snap_url:
49 description:
50 - The Unix domain socket path when LXD is installed by snap package manager.
51 default: unix:/var/snap/lxd/common/lxd/unix.socket
52 type: str
53 client_key:
54 description:
55 - The client certificate key file path.
56 - If not specified, it defaults to C($HOME/.config/lxc/client.key).
57 aliases: [key_file]
58 type: path
59 client_cert:
60 description:
61 - The client certificate file path.
62 - If not specified, it defaults to C($HOME/.config/lxc/client.crt).
63 aliases: [cert_file]
64 type: path
65 trust_password:
66 description:
67 - The client trusted password.
68 - 'You need to set this password on the LXD server before
69 running this module using the following command:
70 C(lxc config set core.trust_password <some random password>)
71 See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/).'
72 - If O(trust_password) is set, this module sends a request for
73 authentication before sending any requests.
74 type: str
75 """
76
77 EXAMPLES = """
78 - name: Get information about all storage pools
79 community.general.lxd_storage_pool_info:
80 register: result
81
82 - name: Get information about a specific storage pool
83 community.general.lxd_storage_pool_info:
84 name: default
85 register: result
86
87 - name: Get information about all ZFS storage pools
88 community.general.lxd_storage_pool_info:
89 type:
90 - zfs
91 - ceph
92 register: result
93
94 - name: Get information about ZFS and BTRFS storage pools
95 community.general.lxd_storage_pool_info:
96 type:
97 - zfs
98 - btrfs
99 register: result
100
101 - name: Get storage pool information via HTTPS connection
102 community.general.lxd_storage_pool_info:
103 url: https://127.0.0.1:8443
104 trust_password: mypassword
105 name: default
106 register: result
107
108 - name: Get storage pool information for a specific project
109 community.general.lxd_storage_pool_info:
110 project: myproject
111 register: result
112 """
113
114 RETURN = """
115 storage_pools:
116 description: List of LXD storage pools.
117 returned: success
118 type: list
119 elements: dict
120 sample: [
121 {
122 "name": "default",
123 "driver": "dir",
124 "used_by": ["/1.0/instances/container1"],
125 "config": {
126 "source": "/var/lib/lxd/storage-pools/default"
127 },
128 "description": "Default storage pool",
129 "status": "Created",
130 "locations": ["none"]
131 }
132 ]
133 contains:
134 name:
135 description: The name of the storage pool.
136 type: str
137 returned: success
138 driver:
139 description: The storage pool driver/type.
140 type: str
141 returned: success
142 used_by:
143 description: List of resources using this storage pool.
144 type: list
145 elements: str
146 returned: success
147 config:
148 description: Configuration of the storage pool.
149 type: dict
150 returned: success
151 description:
152 description: Description of the storage pool.
153 type: str
154 returned: success
155 status:
156 description: Current status of the storage pool.
157 type: str
158 returned: success
159 locations:
160 description: Cluster member locations for the pool.
161 type: list
162 elements: str
163 returned: success
164 logs:
165 description: The logs of requests and responses.
166 returned: when ansible-playbook is invoked with -vvvv.
167 type: list
168 elements: dict
169 sample: [
170 {
171 "type": "sent request",
172 "request": {
173 "method": "GET",
174 "url": "/1.0/storage-pools",
175 "json": null,
176 "timeout": null
177 },
178 "response": {
179 "json": {"type": "sync", "status": "Success"}
180 }
181 }
182 ]
183 """
184
185 import os
186 import typing as t
187 from urllib.parse import urlencode
188
189 from ansible.module_utils.basic import AnsibleModule
190
191 from ansible_collections.community.general.plugins.module_utils._lxd import (
192 LXDClient,
193 LXDClientException,
194 default_cert_file,
195 default_key_file,
196 )
197
198 # ANSIBLE_LXD_DEFAULT_URL is a default value of the lxd endpoint
199 ANSIBLE_LXD_DEFAULT_URL = "unix:/var/lib/lxd/unix.socket"
200 ANSIBLE_LXD_DEFAULT_SNAP_URL = "unix:/var/snap/lxd/common/lxd/unix.socket"
201
202 # API endpoints
203 LXD_API_VERSION = "1.0"
204 LXD_API_STORAGE_POOLS_ENDPOINT = f"/{LXD_API_VERSION}/storage-pools"
205
206
207 class LXDStoragePoolInfo:
208 def __init__(self, module: AnsibleModule) -> None:
209 """Gather information about LXD storage pools.
210
211 :param module: Processed Ansible Module.
212 :type module: AnsibleModule
213 """
214 self.module = module
215 self.name = self.module.params["name"]
216 # pool_type is guaranteed to be a list (may be empty) due to default=[]
217 self.pool_type = self.module.params["type"]
218 self.project = self.module.params["project"]
219
220 self.key_file = self.module.params["client_key"]
221 if self.key_file is None:
222 self.key_file = default_key_file()
223 self.cert_file = self.module.params["client_cert"]
224 if self.cert_file is None:
225 self.cert_file = default_cert_file()
226 self.debug = self.module._verbosity >= 4
227
228 snap_socket_path = self.module.params["snap_url"]
229 if snap_socket_path.startswith("unix:"):
230 snap_socket_path = snap_socket_path[5:]
231
232 if self.module.params["url"] != ANSIBLE_LXD_DEFAULT_URL:
233 self.url = self.module.params["url"]
234 elif os.path.exists(snap_socket_path):
235 self.url = self.module.params["snap_url"]
236 else:
237 self.url = self.module.params["url"]
238
239 try:
240 self.client = LXDClient(
241 self.url,
242 key_file=self.key_file,
243 cert_file=self.cert_file,
244 debug=self.debug,
245 )
246 except LXDClientException as e:
247 self._fail_from_lxd_exception(e)
248
249 self.trust_password = self.module.params["trust_password"]
250
251 def _fail_from_lxd_exception(self, exception: LXDClientException) -> t.NoReturn:
252 """Build failure parameters from LXDClientException and fail.
253
254 :param exception: The LXDClientException instance
255 :type exception: LXDClientException
256 """
257 fail_params = {}
258 if self.client.debug and "logs" in exception.kwargs:
259 fail_params["logs"] = exception.kwargs["logs"]
260 self.module.fail_json(msg=exception.msg, changed=False, **fail_params)
261
262 def _build_url(self, endpoint: str) -> str:
263 """Build URL with project parameter if specified."""
264 if self.project:
265 return f"{endpoint}?{urlencode({'project': self.project})}"
266 return endpoint
267
268 def _get_storage_pool_list(self, recursion: int = 0) -> list:
269 """Get list of all storage pools.
270
271 :param recursion: API recursion level (0 for URLs only, 1 for full objects)
272 :type recursion: int
273 :return: List of pool names (recursion=0) or pool objects (recursion=1)
274 :rtype: list
275 """
276 endpoint = LXD_API_STORAGE_POOLS_ENDPOINT
277 if recursion > 0:
278 endpoint = f"{endpoint}?recursion={recursion}"
279 url = self._build_url(endpoint)
280 resp_json = self.client.do("GET", url, ok_error_codes=[])
281
282 if resp_json["type"] == "error":
283 self.module.fail_json(
284 msg=f"Failed to retrieve storage pools: {resp_json.get('error', 'Unknown error')}",
285 error_code=resp_json.get("error_code"),
286 )
287
288 metadata = resp_json.get("metadata", [])
289
290 if recursion == 0:
291 # With recursion=0: list of pool URLs like ['/1.0/storage-pools/default']
292 # Extract the pool names from URLs
293 return [url.split("/")[-1] for url in metadata]
294 else:
295 # With recursion=1: list of pool objects with full metadata
296 return metadata
297
298 def _get_storage_pool_info(self, pool_name: str) -> dict:
299 """Get detailed information about a specific storage pool."""
300 url = self._build_url(f"{LXD_API_STORAGE_POOLS_ENDPOINT}/{pool_name}")
301 resp_json = self.client.do("GET", url, ok_error_codes=[404])
302
303 if resp_json["type"] == "error":
304 if resp_json.get("error_code") == 404:
305 self.module.fail_json(msg=f'Storage pool "{pool_name}" not found')
306 else:
307 self.module.fail_json(
308 msg=f'Failed to retrieve storage pool "{pool_name}": {resp_json.get("error", "Unknown error")}',
309 error_code=resp_json.get("error_code"),
310 )
311
312 return resp_json.get("metadata", {})
313
314 def get_storage_pools(self) -> list[dict]:
315 """Retrieve storage pool information based on module parameters."""
316 storage_pools = []
317
318 if self.name:
319 # Get information about a specific storage pool
320 pool_info = self._get_storage_pool_info(self.name)
321 storage_pools.append(pool_info)
322 else:
323 # Get information about all storage pools using recursion
324 # This retrieves all pool details in a single API call instead of one call per pool
325 storage_pools = self._get_storage_pool_list(recursion=1)
326
327 # Filter by type if specified
328 if self.pool_type:
329 storage_pools = [pool for pool in storage_pools if pool.get("driver") in self.pool_type]
330
331 return storage_pools
332
333 def run(self) -> None:
334 """Run the main method."""
335 try:
336 if self.trust_password is not None:
337 self.client.authenticate(self.trust_password)
338
339 storage_pools = self.get_storage_pools()
340
341 result_json = {"storage_pools": storage_pools}
342 if self.client.debug:
343 result_json["logs"] = self.client.logs
344 self.module.exit_json(**result_json)
345 except LXDClientException as e:
346 self._fail_from_lxd_exception(e)
347
348
349 def main() -> None:
350 """Ansible Main module."""
351 module = AnsibleModule(
352 argument_spec=dict(
353 name=dict(type="str"),
354 type=dict(type="list", elements="str", default=[]),
355 project=dict(type="str"),
356 url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_URL),
357 snap_url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_SNAP_URL),
358 client_key=dict(type="path", aliases=["key_file"]),
359 client_cert=dict(type="path", aliases=["cert_file"]),
360 trust_password=dict(type="str", no_log=True),
361 ),
362 supports_check_mode=True,
363 )
364
365 lxd_info = LXDStoragePoolInfo(module=module)
366 lxd_info.run()
367
368
369 if __name__ == "__main__":
370 main()