Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_scaleway.py

raw
1 # Copyright (c) Ansible Project
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 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import datetime
11 import json
12 import os
13 import re
14 import sys
15 import time
16 import traceback
17 import typing as t
18 from http import HTTPStatus
19 from urllib.parse import urlencode
20
21 from ansible.module_utils.basic import env_fallback, missing_required_lib
22 from ansible.module_utils.urls import fetch_url
23
24 from ansible_collections.community.general.plugins.module_utils._datetime import (
25 now,
26 )
27
28 if t.TYPE_CHECKING:
29 from collections.abc import Iterable
30
31 from ansible.module_utils.basic import AnsibleModule
32
33 SCALEWAY_SECRET_IMP_ERR: str | None = None
34 try:
35 from passlib.hash import argon2
36
37 HAS_SCALEWAY_SECRET_PACKAGE = True
38 except Exception:
39 SCALEWAY_SECRET_IMP_ERR = traceback.format_exc()
40 HAS_SCALEWAY_SECRET_PACKAGE = False
41
42 YAML_IMPORT_ERROR: str | None
43 try:
44 import yaml
45 except ImportError:
46 YAML_IMPORT_ERROR = traceback.format_exc()
47 else:
48 YAML_IMPORT_ERROR = None
49
50
51 def scaleway_argument_spec() -> dict[str, t.Any]:
52 return dict(
53 api_token=dict(
54 fallback=(env_fallback, ["SCW_TOKEN", "SCW_API_KEY", "SCW_OAUTH_TOKEN", "SCW_API_TOKEN"]),
55 no_log=True,
56 aliases=["oauth_token"],
57 ),
58 api_url=dict(
59 fallback=(env_fallback, ["SCW_API_URL"]), default="https://api.scaleway.com", aliases=["base_url"]
60 ),
61 profile=dict(
62 fallback=(env_fallback, ["SCW_PROFILE"]),
63 aliases=["scw_profile"],
64 ),
65 api_timeout=dict(type="int", default=30, aliases=["timeout"]),
66 query_parameters=dict(type="dict", default={}),
67 validate_certs=dict(default=True, type="bool"),
68 )
69
70
71 def scaleway_waitable_resource_argument_spec():
72 return dict(
73 wait=dict(type="bool", default=True),
74 wait_timeout=dict(type="int", default=300),
75 wait_sleep_time=dict(type="int", default=3),
76 )
77
78
79 def payload_from_object(scw_object):
80 return {k: v for k, v in scw_object.items() if k != "id" and v is not None}
81
82
83 def get_scw_config_path(scw_profile: str) -> str | None:
84 if "SCW_CONFIG_PATH" in os.environ:
85 scw_config_path = os.getenv("SCW_CONFIG_PATH", "")
86 elif "XDG_CONFIG_HOME" in os.environ:
87 scw_config_path = os.path.join(os.getenv("XDG_CONFIG_HOME", ""), "scw", "config.yaml")
88 else:
89 scw_config_path = os.path.join(os.path.expanduser("~"), ".config", "scw", "config.yaml")
90
91 if os.path.exists(scw_config_path):
92 with open(scw_config_path) as fh:
93 scw_config = yaml.safe_load(fh)
94 return scw_config["profiles"][scw_profile].get("secret_key")
95
96 return None
97
98
99 class ScalewayException(Exception):
100 def __init__(self, message: str) -> None:
101 self.message = message
102
103
104 # Specify a complete Link header, for validation purposes
105 R_LINK_HEADER = r"""<[^>]+>;\srel="(first|previous|next|last)"
106 (,<[^>]+>;\srel="(first|previous|next|last)")*"""
107 # Specify a single relation, for iteration and string extraction purposes
108 R_RELATION = r'</?(?P<target_IRI>[^>]+)>; rel="(?P<relation>first|previous|next|last)"'
109
110
111 def parse_pagination_link(header: str) -> dict[str, str]:
112 if not re.match(R_LINK_HEADER, header, re.VERBOSE):
113 raise ScalewayException("Scaleway API answered with an invalid Link pagination header")
114 else:
115 relations = header.split(",")
116 parsed_relations = {}
117 rc_relation = re.compile(R_RELATION)
118 for relation in relations:
119 match = rc_relation.match(relation)
120 if not match:
121 raise ScalewayException("Scaleway API answered with an invalid relation in the Link pagination header")
122 data = match.groupdict()
123 parsed_relations[data["relation"]] = data["target_IRI"]
124 return parsed_relations
125
126
127 def filter_sensitive_attributes(container: dict[str, t.Any], attributes: Iterable[str]) -> dict[str, t.Any]:
128 """
129 WARNING: This function is effectively private, **do not use it**!
130 It will be removed or renamed once changing its name no longer triggers a pylint bug.
131 """
132 for attr in attributes:
133 container[attr] = "SENSITIVE_VALUE"
134
135 return container
136
137
138 class SecretVariables:
139 @staticmethod
140 def ensure_scaleway_secret_package(module: AnsibleModule) -> None:
141 if not HAS_SCALEWAY_SECRET_PACKAGE:
142 module.fail_json(
143 msg=missing_required_lib("passlib[argon2]", url="https://passlib.readthedocs.io/en/stable/"),
144 exception=SCALEWAY_SECRET_IMP_ERR,
145 )
146
147 @staticmethod
148 def dict_to_list(source_dict):
149 return [dict(key=k, value=v) for k, v in source_dict.items()]
150
151 @staticmethod
152 def list_to_dict(source_list, hashed=False):
153 key_value = "hashed_value" if hashed else "value"
154 return {var["key"]: var[key_value] for var in source_list}
155
156 @classmethod
157 def decode(cls, secrets_list, values_list):
158 secrets_dict = cls.list_to_dict(secrets_list, hashed=True)
159 values_dict = cls.list_to_dict(values_list, hashed=False)
160 for key in values_dict:
161 if key in secrets_dict:
162 if argon2.verify(values_dict[key], secrets_dict[key]):
163 secrets_dict[key] = values_dict[key]
164 else:
165 secrets_dict[key] = secrets_dict[key]
166
167 return cls.dict_to_list(secrets_dict)
168
169
170 def resource_attributes_should_be_changed(target, wished, verifiable_mutable_attributes, mutable_attributes):
171 diff = dict()
172 for attr in verifiable_mutable_attributes:
173 if wished[attr] is not None and target[attr] != wished[attr]:
174 diff[attr] = wished[attr]
175
176 if diff:
177 return {attr: wished[attr] for attr in mutable_attributes}
178 else:
179 return diff
180
181
182 class Response:
183 def __init__(self, resp, info):
184 self.body = None
185 if resp:
186 self.body = resp.read()
187 self.info = info
188
189 @property
190 def json(self):
191 if not self.body:
192 if "body" in self.info:
193 return json.loads(self.info["body"])
194 return None
195 try:
196 return json.loads(self.body)
197 except ValueError:
198 return None
199
200 @property
201 def status_code(self):
202 return self.info["status"]
203
204 @property
205 def ok(self):
206 return self.status_code in (
207 HTTPStatus.OK,
208 HTTPStatus.CREATED,
209 HTTPStatus.ACCEPTED,
210 HTTPStatus.NO_CONTENT,
211 )
212
213
214 class Scaleway:
215 def __init__(self, module: AnsibleModule) -> None:
216 self.module = module
217 oauth_token = self.module.params.get("api_token")
218 scw_profile = self.module.params.get("profile")
219
220 if scw_profile:
221 if YAML_IMPORT_ERROR is not None:
222 self.module.fail_json(
223 msg=missing_required_lib("PyYAML", reason="for scw_profile"), exception=YAML_IMPORT_ERROR
224 )
225 oauth_token = get_scw_config_path(scw_profile)
226
227 if oauth_token is None:
228 self.module.fail_json(
229 msg="Either your config profile could not be loaded or you have not provided an api_token."
230 )
231
232 self.headers = {
233 "X-Auth-Token": oauth_token,
234 "User-Agent": self.get_user_agent_string(module),
235 "Content-Type": "application/json",
236 }
237 self.name = None
238
239 def get_resources(self):
240 results = self.get(f"/{self.name}")
241
242 if not results.ok:
243 api_response = results.json if results.json is not None else results.body
244 message = api_response.get("message") if isinstance(api_response, dict) else api_response
245 raise ScalewayException(
246 f"Error fetching {self.name} ({self.module.params.get('api_url')}/{self.name}) [{results.status_code}: {message}]"
247 )
248
249 if results.json is None:
250 raise ScalewayException(f"Scaleway API returned an empty or non-JSON response for {self.name}")
251
252 return results.json.get(self.name)
253
254 def _url_builder(self, path, params):
255 d = self.module.params.get("query_parameters")
256 if params is not None:
257 d.update(params)
258 query_string = urlencode(d, doseq=True)
259
260 if path[0] == "/":
261 path = path[1:]
262 return f"{self.module.params.get('api_url')}/{path}?{query_string}"
263
264 def send(self, method, path, data=None, headers=None, params=None):
265 url = self._url_builder(path=path, params=params)
266 self.warn(url)
267
268 if headers is not None:
269 self.headers.update(headers)
270
271 if self.headers["Content-Type"] == "application/json":
272 data = self.module.jsonify(data)
273
274 resp, info = fetch_url(
275 self.module,
276 url,
277 data=data,
278 headers=self.headers,
279 method=method,
280 timeout=self.module.params.get("api_timeout"),
281 )
282
283 # Exceptions in fetch_url may result in a status -1, the ensures a proper error to the user in all cases
284 if info["status"] == -1:
285 self.module.fail_json(msg=info["msg"])
286
287 return Response(resp, info)
288
289 @staticmethod
290 def get_user_agent_string(module: AnsibleModule) -> str:
291 ansible_version = module.ansible_version # type: ignore # For some reason this isn't documented in AnsibleModule
292 return f"ansible {ansible_version} Python {sys.version.split(' ', 1)[0]}"
293
294 def get(self, path, data=None, headers=None, params=None):
295 return self.send(method="GET", path=path, data=data, headers=headers, params=params)
296
297 def put(self, path, data=None, headers=None, params=None):
298 return self.send(method="PUT", path=path, data=data, headers=headers, params=params)
299
300 def post(self, path, data=None, headers=None, params=None):
301 return self.send(method="POST", path=path, data=data, headers=headers, params=params)
302
303 def delete(self, path, data=None, headers=None, params=None):
304 return self.send(method="DELETE", path=path, data=data, headers=headers, params=params)
305
306 def patch(self, path, data=None, headers=None, params=None):
307 return self.send(method="PATCH", path=path, data=data, headers=headers, params=params)
308
309 def update(self, path, data=None, headers=None, params=None):
310 return self.send(method="UPDATE", path=path, data=data, headers=headers, params=params)
311
312 def warn(self, x) -> None:
313 self.module.warn(str(x))
314
315 def fetch_state(self, resource):
316 self.module.debug(f"fetch_state of resource: {resource['id']}")
317 response = self.get(path=f"{self.api_path}/{resource['id']}")
318
319 if response.status_code == HTTPStatus.NOT_FOUND:
320 return "absent"
321
322 if not response.ok:
323 msg = f"Error during state fetching: ({response.status_code}) {response.json}"
324 self.module.fail_json(msg=msg)
325
326 try:
327 self.module.debug(f"Resource {resource['id']} in state: {response.json['status']}")
328 return response.json["status"]
329 except KeyError:
330 self.module.fail_json(msg=f"Could not fetch state in {response.json}")
331
332 def fetch_paginated_resources(self, resource_key, **pagination_kwargs):
333 response = self.get(path=self.api_path, params=pagination_kwargs)
334
335 if not response.ok:
336 self.module.fail_json(
337 msg=f"Error getting {resource_key} [{response.status_code}: {response.json['message']}]"
338 )
339
340 return response.json[resource_key]
341
342 def fetch_all_resources(self, resource_key, **pagination_kwargs):
343 resources = []
344
345 result = [None]
346 while len(result) != 0:
347 result = self.fetch_paginated_resources(resource_key, **pagination_kwargs)
348 resources += result
349 if "page" in pagination_kwargs:
350 pagination_kwargs["page"] += 1
351 else:
352 pagination_kwargs["page"] = 2
353
354 return resources
355
356 def wait_to_complete_state_transition(self, resource, stable_states, force_wait=False):
357 wait = self.module.params["wait"]
358
359 if not (wait or force_wait):
360 return
361
362 wait_timeout = self.module.params["wait_timeout"]
363 wait_sleep_time = self.module.params["wait_sleep_time"]
364
365 # Prevent requesting the resource status too soon
366 time.sleep(wait_sleep_time)
367
368 start = now()
369 end = start + datetime.timedelta(seconds=wait_timeout)
370
371 while now() < end:
372 self.module.debug("We are going to wait for the resource to finish its transition")
373
374 state = self.fetch_state(resource)
375 if state in stable_states:
376 self.module.debug("It seems that the resource is not in transition anymore.")
377 self.module.debug(f"load-balancer in state: {self.fetch_state(resource)}")
378 break
379
380 time.sleep(wait_sleep_time)
381 else:
382 self.module.fail_json(msg="Server takes too long to finish its transition")
383
384
385 SCALEWAY_LOCATION = {
386 "par1": {
387 "name": "Paris 1",
388 "country": "FR",
389 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/fr-par-1",
390 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/fr-par-1",
391 },
392 "EMEA-FR-PAR1": {
393 "name": "Paris 1",
394 "country": "FR",
395 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/fr-par-1",
396 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/fr-par-1",
397 },
398 "par2": {
399 "name": "Paris 2",
400 "country": "FR",
401 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/fr-par-2",
402 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/fr-par-2",
403 },
404 "EMEA-FR-PAR2": {
405 "name": "Paris 2",
406 "country": "FR",
407 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/fr-par-2",
408 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/fr-par-2",
409 },
410 "par3": {
411 "name": "Paris 3",
412 "country": "FR",
413 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/fr-par-3",
414 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/fr-par-3",
415 },
416 "ams1": {
417 "name": "Amsterdam 1",
418 "country": "NL",
419 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/nl-ams-1",
420 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/nl-ams-1",
421 },
422 "EMEA-NL-EVS": {
423 "name": "Amsterdam 1",
424 "country": "NL",
425 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/nl-ams-1",
426 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/nl-ams-1",
427 },
428 "ams2": {
429 "name": "Amsterdam 2",
430 "country": "NL",
431 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/nl-ams-2",
432 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/nl-ams-2",
433 },
434 "ams3": {
435 "name": "Amsterdam 3",
436 "country": "NL",
437 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/nl-ams-3",
438 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/nl-ams-3",
439 },
440 "waw1": {
441 "name": "Warsaw 1",
442 "country": "PL",
443 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/pl-waw-1",
444 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/pl-waw-1",
445 },
446 "EMEA-PL-WAW1": {
447 "name": "Warsaw 1",
448 "country": "PL",
449 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/pl-waw-1",
450 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/pl-waw-1",
451 },
452 "waw2": {
453 "name": "Warsaw 2",
454 "country": "PL",
455 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/pl-waw-2",
456 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/pl-waw-2",
457 },
458 "waw3": {
459 "name": "Warsaw 3",
460 "country": "PL",
461 "api_endpoint": "https://api.scaleway.com/instance/v1/zones/pl-waw-3",
462 "api_endpoint_vpc": "https://api.scaleway.com/vpc/v1/zones/pl-waw-3",
463 },
464 }
465
466 SCALEWAY_ENDPOINT = "https://api.scaleway.com"
467
468 SCALEWAY_REGIONS = [
469 "fr-par",
470 "nl-ams",
471 "pl-waw",
472 ]
473
474 SCALEWAY_ZONES = [
475 "fr-par-1",
476 "fr-par-2",
477 "fr-par-3",
478 "nl-ams-1",
479 "nl-ams-2",
480 "nl-ams-3",
481 "pl-waw-1",
482 "pl-waw-2",
483 "pl-waw-3",
484 ]