Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/module_utils/_base.py

raw
1 # Copyright: (c) 2019, Hetzner Cloud GmbH <[email protected]>
2
3 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
4 # Do not use this from other collections or standalone plugins/modules!
5
6 from __future__ import annotations
7
8 import traceback
9 from copy import deepcopy
10 from typing import Any, NoReturn
11
12 from ansible.module_utils.basic import AnsibleModule as AnsibleModuleBase, env_fallback
13 from ansible.module_utils.common.text.converters import to_native
14 from ansible.module_utils.common.validation import (
15 check_missing_parameters,
16 check_required_one_of,
17 )
18
19 from ._client import (
20 ClientException,
21 client_check_required_lib,
22 client_get_by_name_or_id,
23 )
24 from ._vendor.hcloud import (
25 APIException,
26 Client,
27 HCloudException,
28 exponential_backoff_function,
29 )
30 from ._vendor.hcloud.actions import ActionException
31 from ._version import version
32
33
34 class AnsibleModule(AnsibleModuleBase):
35 params: dict
36 params_raw: dict
37
38 def _load_params(self):
39 """
40 Copy the params before validation, to keep track whether a value was defined by the user.
41
42 Validation will modify the params dict by adding missing keys.
43 """
44 # https://github.com/ansible/ansible/blob/7b4d4ed672415f31689e7f25bc0b40c0697c0c88/lib/ansible/module_utils/basic.py#L1244-L1251
45 super()._load_params()
46 self.params_raw = deepcopy(self.params)
47
48 def param_is_defined(self, key: str):
49 """
50 Check if a parameter was defined by the user.
51 """
52 return key in self.params_raw
53
54
55 class AnsibleHCloud:
56 represent: str
57
58 module: AnsibleModule
59
60 client: Client
61
62 def __init__(self, module: AnsibleModule):
63 if not self.represent:
64 raise NotImplementedError(f"represent property is not defined for {self.__class__.__name__}")
65
66 self.module = module
67 self.result = {"changed": False, self.represent: None}
68
69 try:
70 client_check_required_lib()
71 except ClientException as exception:
72 module.fail_json(msg=to_native(exception))
73
74 self._build_client()
75
76 def fail_json_hcloud(
77 self,
78 exception: HCloudException,
79 msg: str | None = None,
80 params: Any = None,
81 **kwargs,
82 ) -> NoReturn:
83 last_traceback = traceback.format_exc()
84
85 failure = {}
86
87 if params is not None:
88 failure["params"] = params
89
90 if isinstance(exception, APIException):
91 failure["message"] = exception.message
92 failure["code"] = exception.code
93 failure["details"] = exception.details
94
95 elif isinstance(exception, ActionException):
96 failure["action"] = {k: getattr(exception.action, k) for k in exception.action.__slots__}
97
98 exception_message = to_native(exception)
99 if msg is not None:
100 msg = f"{exception_message}: {msg}"
101 else:
102 msg = exception_message
103
104 self.module.fail_json(msg=msg, exception=last_traceback, failure=failure, **kwargs)
105
106 def _build_client(self) -> None:
107 self.client = Client(
108 token=self.module.params["api_token"],
109 api_endpoint=self.module.params["api_endpoint"],
110 api_endpoint_hetzner=self.module.params["api_endpoint_hetzner"],
111 application_name="ansible-module",
112 application_version=version,
113 # Total waiting time before timeout is > 117.0
114 poll_interval=exponential_backoff_function(base=1.0, multiplier=2, cap=5.0),
115 poll_max_retries=25,
116 )
117
118 def _client_get_by_name_or_id(self, resource: str, param: str | int):
119 """
120 Get a resource by name, and if not found by its ID.
121
122 :param resource: Name of the resource client that implements both `get_by_name` and `get_by_id` methods
123 :param param: Name or ID of the resource to query
124 """
125 try:
126 return client_get_by_name_or_id(self.client, resource, param)
127 except ClientException as exception:
128 self.module.fail_json(msg=to_native(exception))
129
130 def _mark_as_changed(self) -> None:
131 self.result["changed"] = True
132
133 def fail_on_invalid_params(
134 self,
135 *,
136 required: list[str] | None = None,
137 required_one_of: list[list[str]] | None = None,
138 ) -> None:
139 """
140 Run additional validation that cannot be done in the argument spec validation.
141
142 :param required_params: Check that terms exists in the module params.
143 :param required_one_of: Check each list of terms to ensure at least one exists in the module parameters.
144 """
145 try:
146 if required:
147 check_missing_parameters(self.module.params, required)
148
149 if required_one_of:
150 params_without_nones = {k: v for k, v in self.module.params.items() if v is not None}
151 check_required_one_of(required_one_of, params_without_nones)
152
153 except TypeError as e:
154 self.module.fail_json(msg=to_native(e))
155
156 @classmethod
157 def base_module_arguments(cls):
158 return {
159 "api_token": {
160 "type": "str",
161 "required": True,
162 "fallback": (env_fallback, ["HCLOUD_TOKEN"]),
163 "no_log": True,
164 },
165 "api_endpoint": {
166 "type": "str",
167 "fallback": (env_fallback, ["HCLOUD_ENDPOINT"]),
168 "default": "https://api.hetzner.cloud/v1",
169 "aliases": ["endpoint"],
170 },
171 "api_endpoint_hetzner": {
172 "type": "str",
173 "fallback": (env_fallback, ["HETZNER_ENDPOINT"]),
174 "default": "https://api.hetzner.com/v1",
175 },
176 }
177
178 def _prepare_result(self) -> dict[str, Any]:
179 """Prepare the result for every module"""
180 return {}
181
182 def get_result(self) -> dict[str, Any]:
183 if getattr(self, self.represent) is not None:
184 self.result[self.represent] = self._prepare_result()
185 return self.result