Debian Codegraph @

ansible_collections/community/proxmox/plugins/module_utils/proxmox.py

raw
1 #
2 # Copyright (c) 2020, Tristan Le Guern <tleguern at bouledef.eu>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6
7 import traceback
8 from time import sleep
9
10 PROXMOXER_IMP_ERR = None
11 try:
12 from proxmoxer import ProxmoxAPI
13 from proxmoxer import __version__ as proxmoxer_version
14
15 HAS_PROXMOXER = True
16 except ImportError:
17 HAS_PROXMOXER = False
18 PROXMOXER_IMP_ERR = traceback.format_exc()
19
20
21 from ansible.module_utils.basic import AnsibleModule, env_fallback, missing_required_lib
22 from ansible.module_utils.common.text.converters import to_native
23
24 from ansible_collections.community.proxmox.plugins.module_utils.version import LooseVersion
25
26
27 def proxmox_auth_argument_spec():
28 """
29 Returns the authentication argument specification for Proxmox API modules.
30
31 Returns:
32 dict[str, dict]: Parameter names mapped to their configuration dictionaries.
33 """
34 return dict(
35 api_host=dict(type="str", required=True, fallback=(env_fallback, ["PROXMOX_HOST"])),
36 api_port=dict(type="int", fallback=(env_fallback, ["PROXMOX_PORT"])),
37 api_user=dict(type="str", required=True, fallback=(env_fallback, ["PROXMOX_USER"])),
38 api_password=dict(type="str", no_log=True, fallback=(env_fallback, ["PROXMOX_PASSWORD"])),
39 api_otp=dict(type="str", no_log=True, fallback=(env_fallback, ["PROXMOX_OTP"])),
40 api_token_id=dict(type="str", no_log=False, fallback=(env_fallback, ["PROXMOX_TOKEN_ID"])),
41 api_token_secret=dict(type="str", no_log=True, fallback=(env_fallback, ["PROXMOX_TOKEN_SECRET"])),
42 ca_path=dict(type="path", fallback=(env_fallback, ["PROXMOX_CA_PATH"])),
43 validate_certs=dict(type="bool", default=True, fallback=(env_fallback, ["PROXMOX_VALIDATE_CERTS"])),
44 api_timeout=dict(type="int", default=5, fallback=(env_fallback, ["PROXMOX_API_TIMEOUT"])),
45 )
46
47
48 def create_proxmox_module(argument_spec, **kwargs):
49 """
50 Create an AnsibleModule with Proxmox auth arguments and constraints merged in.
51
52 Args:
53 argument_spec: Module-specific argument specification.
54 **kwargs: Additional AnsibleModule options (e.g. supports_check_mode, mutually_exclusive, required_if).
55
56 Returns:
57 AnsibleModule: The configured module instance.
58 """
59 spec = {**proxmox_auth_argument_spec(), **argument_spec}
60 supports_check_mode = kwargs.pop("supports_check_mode", True)
61
62 for key, default in (
63 ("required_one_of", ("api_password", "api_token_id")),
64 ("required_together", ("api_token_id", "api_token_secret")),
65 ):
66 kwargs[key] = [default] + list(kwargs.get(key, []))
67
68 return AnsibleModule(argument_spec=spec, supports_check_mode=supports_check_mode, **kwargs)
69
70
71 def proxmox_to_ansible_bool(value): # noqa: SIM210
72 """Convert Proxmox representation of a boolean to be ansible-friendly.
73
74 Args:
75 value(int): The value which needs to be converted to a boolean.
76
77 Returns:
78 bool: True if value = `1`, False for everything else including non-integers.
79 """
80 return bool(isinstance(value, int) and value == 1)
81
82
83 def ansible_to_proxmox_bool(value):
84 """
85 Convert Ansible representation of a boolean to be proxmox-friendly.
86
87 Returns:
88 `None` when value is`None`, `1` for `True` and `0` for `False`
89 """
90 if value is None:
91 return None
92
93 if not isinstance(value, bool):
94 raise ValueError(f"{value} must be of type bool not {type(value)}")
95
96 return 1 if value else 0
97
98
99 def compare_list_of_dicts(existing_list, new_list, uid, params_to_ignore=None):
100 """Compare 2 list of dicts.
101
102 Use case - for firewall rules we will be getting a list of rules from user.
103 We want to filter out which rules needs to be updated and which rules are completely new and needs to be created
104
105 :param existing_list: Existing values example - list of existing rules
106 :param new_list: New values example - list of rules passed to module
107 :param uid: unique identifier in dict. It should always be present in both lists - in case of firewall rules it's pos
108 :param params_to_ignore: list of params we want to ignore which are present in existing_list's dict.
109 In case of firewall rules we want to ignore ['digest', 'ipversion']
110
111 Use case - for firewall rules we will be getting a list of rules from user.
112 We want to filter out which rules needs to be updated and which rules are completely new and needs to be created.
113
114 Args:
115 existing_list(list): Existing values example - list of existing rules
116 new_list(list): New values example - list of rules passed to module
117 uid(str): unique identifier in dict.
118 It should always be present in both lists - in case of firewall rules it's `pos`.
119 params_to_ignore(list): list of params we want to ignore, which are present in existing_list's dict.
120 In case of firewall rules we want to ignore `['digest', 'ipversion']`.
121
122 Returns:
123 tuple[list, list]: 2 lists: 1st is the list of items which are completely new and needs to be created
124 2nd is a list of items which needs to be updated.
125 """
126 if params_to_ignore is None:
127 params_to_ignore = list()
128 items_to_update = []
129 new_list = [{k: v for k, v in item.items() if v is not None and k not in params_to_ignore} for item in new_list]
130
131 if existing_list is None:
132 items_to_create = new_list
133 items_to_update = list()
134 return items_to_create, items_to_update
135
136 existing_list = {x[uid]: x for x in existing_list}
137 new_list = {x[uid]: x for x in new_list}
138
139 common_uids = set(existing_list.keys()).intersection(set(new_list.keys()))
140 missing_uids = set(new_list.keys()) - set(existing_list.keys())
141 items_to_create = [new_list[uid] for uid in missing_uids]
142
143 for c_uid in common_uids:
144 # If new rule has a parameter that is not present in existing rule we need to update
145 if set(new_list[c_uid].keys()) - set(existing_list[c_uid].keys()) != set():
146 items_to_update.append(new_list[c_uid])
147 continue
148
149 # If existing rule param value doesn't match new rule param OR
150 # If existing rule has a param that is not present in new rule except for params in params_to_ignore
151 for existing_rule_param, existing_parm_value in existing_list[c_uid].items():
152 if (
153 existing_rule_param not in params_to_ignore
154 and new_list[c_uid].get(existing_rule_param) != existing_parm_value
155 ):
156 items_to_update.append(new_list[c_uid])
157
158 return items_to_create, items_to_update
159
160
161 def is_not_found_error(exception: Exception) -> bool:
162 """Check if the exception is a not found error."""
163 error_str = str(exception).lower()
164 return (
165 "does not exist" in error_str
166 or "not found" in error_str
167 or "no such" in error_str
168 or "not defined" in error_str
169 )
170
171
172 class ProxmoxAnsible:
173 """Base class for Proxmox modules."""
174
175 TASK_TIMED_OUT = "timeout expired"
176
177 def __init__(self, module):
178 if not HAS_PROXMOXER:
179 module.fail_json(msg=missing_required_lib("proxmoxer"), exception=PROXMOXER_IMP_ERR)
180 if proxmoxer_version < LooseVersion("2.3"):
181 module.fail_json(f"Requires proxmoxer 2.3 or newer; found version {proxmoxer_version}")
182
183 self.module = module
184 self.proxmoxer_version = proxmoxer_version
185 self.proxmox_api = self._connect()
186 # Test token validity
187 try:
188 self.proxmox_api.version.get()
189 except Exception as e:
190 module.fail_json(msg=f"{e}", exception=traceback.format_exc())
191
192 def _connect(self):
193 api_host = self.module.params["api_host"]
194 api_port = self.module.params["api_port"]
195 api_user = self.module.params["api_user"]
196 api_password = self.module.params["api_password"]
197 api_otp = self.module.params["api_otp"]
198 api_token_id = self.module.params["api_token_id"]
199 api_token_secret = self.module.params["api_token_secret"]
200 # Only push the cert path as a string to proxmoxer, if validation is required
201 # verify_ssl supports True, False or Path as values
202 if self.module.params["ca_path"] and self.module.params["validate_certs"]:
203 validate_certs = self.module.params["ca_path"]
204 else:
205 validate_certs = self.module.params["validate_certs"]
206 api_timeout = self.module.params["api_timeout"]
207 auth_args = {"user": api_user}
208
209 if api_port:
210 auth_args["port"] = api_port
211
212 if api_password:
213 auth_args["password"] = api_password
214 else:
215 auth_args["token_name"] = api_token_id
216 auth_args["token_value"] = api_token_secret
217
218 if api_otp:
219 auth_args["otp"] = api_otp
220 try:
221 return ProxmoxAPI(api_host, timeout=api_timeout, verify_ssl=validate_certs, **auth_args)
222 except Exception as e:
223 self.module.fail_json(msg=f"{e}", exception=traceback.format_exc())
224
225 def version(self):
226 """
227 Queries the proxmox api for its current version.
228
229 Returns:
230 int: Major release of the Proxmox VE host.
231 """
232 try:
233 apiversion = self.proxmox_api.version.get()
234 return LooseVersion(apiversion["version"])
235 except Exception as e:
236 self.module.fail_json(msg=f"Unable to retrieve Proxmox VE version: {e}")
237
238 def get_node(self, node, strict=False):
239 """
240 Filters all known PVE nodes for the given node name.
241
242 Args:
243 node(str): The name of the node.
244 strict(bool): Fail if the node does not exist.
245
246 Returns:
247 dict | None: The node information provided by the api path GET /nodes.
248 """
249 try:
250 nodes = [n for n in self.proxmox_api.nodes.get() if n["node"] == node]
251 except Exception as e:
252 self.module.fail_json(msg=f"Unable to retrieve Proxmox VE node: {e}")
253 if not nodes and strict:
254 self.module.fail_json(msg=f"Node {node} does not exist")
255 return nodes[0] if nodes else None
256
257 def get_nextvmid(self):
258 """
259 Queries the PVE api for the next vmid.
260
261 Returns:
262 int: The next vmid.
263 """
264 try:
265 return self.proxmox_api.cluster.nextid.get()
266 except Exception as e:
267 self.module.fail_json(msg=f"Unable to retrieve next free vmid: {e}")
268
269 def get_vmid(self, name, ignore_missing=False, choose_first_if_multiple=False):
270 """
271 Searches the PVE VMs for a VM with the given name.
272
273 Args:
274 name(str): The name to filter the api output to.
275 ignore_missing (bool): Don't fail the task if no vm could be found.
276 choose_first_if_multiple (bool): Don't fail the task if several names match.
277
278 Returns:
279 int | None : The matching vmid or None, when no name matched.
280 """
281 try:
282 vms = [vm["vmid"] for vm in self.proxmox_api.cluster.resources.get(type="vm") if vm.get("name") == name]
283 except Exception as e:
284 self.module.fail_json(msg=f"Unable to retrieve list of VMs filtered by name {name}: {e}")
285
286 if not vms:
287 if ignore_missing:
288 return None
289
290 self.module.fail_json(msg=f"No VM with name {name} found")
291 elif len(vms) > 1 and not choose_first_if_multiple:
292 self.module.fail_json(msg=f"Multiple VMs with name {name} found, provide vmid instead")
293
294 return vms[0]
295
296 def get_vm(self, vmid, ignore_missing=False):
297 """
298 Retrieve VM information based on the given VMID.
299
300 Args:
301 vmid(int): VMID to query.
302 ignore_missing: Skip failing the task if no VM was found.
303
304 Returns:
305 dict | None: VM attributes or None, if no VM was found.
306
307 """
308 try:
309 vms = [vm for vm in self.proxmox_api.cluster.resources.get(type="vm") if vm["vmid"] == int(vmid)]
310 except Exception as e:
311 self.module.fail_json(msg=f"Unable to retrieve list of VMs filtered by vmid {vmid}: {e}")
312
313 if vms:
314 return vms[0]
315 else:
316 if ignore_missing:
317 return None
318
319 self.module.fail_json(msg=f"VM with vmid {vmid} does not exist in cluster")
320
321 def api_task_ok(self, node, taskid):
322 """
323 Verify the success of a finished task.
324
325 Args:
326 node(str): Node, which task log should be queried.
327 taskid(str): Unique task identifier.
328
329 Returns:
330 bool: Task status.
331
332 """
333 try:
334 status = self.proxmox_api.nodes(node).tasks(taskid).status.get()
335 exitstatus = to_native(status.get("exitstatus") or "")
336 return status["status"] == "stopped" and (exitstatus == "OK" or exitstatus.startswith("WARN"))
337 except Exception as e:
338 self.module.fail_json(msg=f"Unable to retrieve API task ID from node {node}: {e}")
339
340 def api_task_failed(self, node, taskid):
341 """
342 Verify the failure of a finished task.
343
344 Args:
345 node(str): Node, which task log should be queried.
346 taskid(str): Unique task identifier.
347
348 Returns:
349 bool: Task status.
350
351 """
352 try:
353 status = self.proxmox_api.nodes(node).tasks(taskid).status.get()
354 return status["status"] == "stopped" and status["exitstatus"] != "OK"
355 except Exception as e:
356 self.module.fail_json(msg=f"Unable to retrieve API task ID from node {node}: {e}")
357
358 def api_task_complete(self, node_name, task_id, timeout):
359 """
360 Wait until the task stops or times out.
361
362 Args:
363 node_name(str): Proxmox node name where the task is running.
364 task_id(str): ID of the running task.
365 timeout(int): Timeout in seconds to wait for the task to complete.
366
367 Returns:
368 tuple[bool, str]: Task completion status and `exitstatus` message when status=False.
369 """
370 status = {}
371 while timeout:
372 try:
373 status = self.proxmox_api.nodes(node_name).tasks(task_id).status.get()
374 except Exception as e:
375 self.module.fail_json(msg=f"Unable to retrieve API task ID from node {node_name}: {e}")
376
377 if status["status"] == "stopped":
378 if status["exitstatus"] == "OK":
379 return True, None
380 else:
381 return False, status["exitstatus"]
382 else:
383 timeout -= 1
384 if timeout <= 0:
385 return False, ProxmoxAnsible.TASK_TIMED_OUT
386 sleep(1)
387
388 def upid_to_node(self, upid):
389 """
390 Extract the node name from a UPID.
391
392 Args:
393 upid(str): The UPID to convert to a node name.
394
395 Returns:
396 str: The node name.
397 """
398 parts = to_native(upid).split(":")
399 if len(parts) >= 2 and parts[0] == "UPID": # noqa: PLR2004
400 return parts[1]
401
402 self.module.fail_json(msg=f"Unexpected task id from Proxmox API: {upid}")
403
404 def get_pool(self, poolid):
405 """
406 Retrieve pool information.
407
408 Args:
409 poolid(str): Name of the pool.
410
411 Returns:
412 dict: Pool information.
413 """
414 try:
415 return self.proxmox_api.pools.get(poolid=poolid)[0]
416 except Exception as e:
417 self.module.fail_json(msg=f"Unable to retrieve pool {poolid} information: {e}")
418
419 def get_storages(self, storagetype):
420 """
421 Retrieve storages information.
422
423 Args:
424 storagetype(str): Type of storages to filter to.
425
426 Returns:
427 list[dict]: List of configured storages.
428 """
429 try:
430 return self.proxmox_api.storage.get(type=storagetype)
431 except Exception as e:
432 self.module.fail_json(msg=f"Unable to retrieve storages information with type {storagetype}: {e}")
433
434 def get_storage_content(self, node, storage, content=None, vmid=None):
435 """
436 Retrieve a list of storage contents.
437
438 Args:
439 storage(str): Storage to check.
440 node(str): Node to query.
441 content(str): Limit the file list to the following content type.
442 vmid(int): Limit the file list to this vmid.
443
444 Returns:
445 list[dict]: List of configured files.
446 """
447 try:
448 return self.proxmox_api.nodes(node).storage(storage).content().get(content=content, vmid=vmid)
449 except Exception as e:
450 self.module.fail_json(msg=f"Unable to list content on {node}, {storage} for {content} and {vmid}: {e}")