Debian Codegraph @

ansible_collections/community/general/plugins/inventory/scaleway.py

raw
1 # Copyright (c) 2017 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 from __future__ import annotations
6
7 DOCUMENTATION = r"""
8 name: scaleway
9 author:
10 - Remy Leone (@remyleone)
11 short_description: Scaleway inventory source
12 description:
13 - Get inventory hosts from Scaleway.
14 requirements:
15 - PyYAML
16 options:
17 plugin:
18 description: Token that ensures this is a source file for the 'scaleway' plugin.
19 required: true
20 type: string
21 choices: ['scaleway', 'community.general.scaleway']
22 regions:
23 description: Filter results on a specific Scaleway region.
24 type: list
25 elements: string
26 default:
27 - ams1
28 - ams2
29 - ams3
30 - par1
31 - par2
32 - par3
33 - waw1
34 - waw2
35 - waw3
36 tags:
37 description: Filter results on a specific tag.
38 type: list
39 elements: string
40 scw_profile:
41 description:
42 - The config profile to use in config file.
43 - By default uses the one specified as C(active_profile) in the config file, or falls back to V(default) if that is
44 not defined.
45 type: string
46 version_added: 4.4.0
47 env:
48 - name: SCW_PROFILE
49 version_added: 12.2.0
50 oauth_token:
51 description:
52 - Scaleway OAuth token.
53 - If not explicitly defined or in environment variables, it tries to lookup in the C(scaleway-cli) configuration file
54 (C($SCW_CONFIG_PATH), C($XDG_CONFIG_HOME/scw/config.yaml), or C(~/.config/scw/config.yaml)).
55 - More details on L(how to generate token, https://www.scaleway.com/en/docs/generate-api-keys/).
56 type: string
57 env:
58 # in order of precedence
59 - name: SCW_TOKEN
60 - name: SCW_API_KEY
61 - name: SCW_OAUTH_TOKEN
62 hostnames:
63 description: List of preference about what to use as an hostname.
64 type: list
65 elements: string
66 default:
67 - public_ipv4
68 choices:
69 - public_ipv4
70 - private_ipv4
71 - public_ipv6
72 - hostname
73 - id
74 variables:
75 description: 'Set individual variables: keys are variable names and values are templates. Any value returned by the L(Scaleway
76 API, https://developer.scaleway.com/#servers-server-get) can be used.'
77 type: dict
78 """
79
80 EXAMPLES = r"""
81 # scaleway_inventory.yml file in YAML format
82 # Example command line: ansible-inventory --list -i scaleway_inventory.yml
83
84 ---
85 # use hostname as inventory_hostname
86 # use the private IP address to connect to the host
87 plugin: community.general.scaleway
88 regions:
89 - ams1
90 - par1
91 tags:
92 - foobar
93 hostnames:
94 - hostname
95 variables:
96 ansible_host: private_ip
97 state: state
98
99 ---
100 # use hostname as inventory_hostname and public IP address to connect to the host
101 plugin: community.general.scaleway
102 hostnames:
103 - hostname
104 regions:
105 - par1
106 variables:
107 ansible_host: public_ip.address
108
109 ---
110 # Using static strings as variables
111 plugin: community.general.scaleway
112 hostnames:
113 - hostname
114 variables:
115 ansible_host: public_ip.address
116 ansible_connection: "'ssh'"
117 ansible_user: "'admin'"
118 """
119
120 import json
121 import os
122
123 YAML_IMPORT_ERROR: ImportError | None
124 try:
125 import yaml
126 except ImportError as exc:
127 YAML_IMPORT_ERROR = exc
128 else:
129 YAML_IMPORT_ERROR = None
130
131 import urllib.parse as urllib_parse
132
133 from ansible.errors import AnsibleError
134 from ansible.module_utils.common.text.converters import to_text
135 from ansible.module_utils.urls import open_url
136 from ansible.plugins.inventory import BaseInventoryPlugin, Constructable
137
138 from ansible_collections.community.general.plugins.module_utils._scaleway import (
139 SCALEWAY_LOCATION,
140 parse_pagination_link,
141 )
142 from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe
143
144
145 def _fetch_information(token, url):
146 results = []
147 paginated_url = url
148 while True:
149 try:
150 response = open_url(paginated_url, headers={"X-Auth-Token": token, "Content-type": "application/json"})
151 except Exception as e:
152 raise AnsibleError(f"Error while fetching {url}: {e}") from e
153 try:
154 raw_json = json.loads(to_text(response.read()))
155 except ValueError as e:
156 raise AnsibleError("Incorrect JSON payload") from e
157
158 try:
159 results.extend(raw_json["servers"])
160 except KeyError as e:
161 raise AnsibleError("Incorrect format from the Scaleway API response") from e
162
163 link = response.headers["Link"]
164 if not link:
165 return results
166 relations = parse_pagination_link(link)
167 if "next" not in relations:
168 return results
169 paginated_url = urllib_parse.urljoin(paginated_url, relations["next"])
170
171
172 def _build_server_url(api_endpoint):
173 return f"{api_endpoint}/servers"
174
175
176 def extract_public_ipv4(server_info):
177 try:
178 return server_info["public_ip"]["address"]
179 except (KeyError, TypeError):
180 return None
181
182
183 def extract_private_ipv4(server_info):
184 try:
185 return server_info["private_ip"]
186 except (KeyError, TypeError):
187 return None
188
189
190 def extract_hostname(server_info):
191 try:
192 return server_info["hostname"]
193 except (KeyError, TypeError):
194 return None
195
196
197 def extract_server_id(server_info):
198 try:
199 return server_info["id"]
200 except (KeyError, TypeError):
201 return None
202
203
204 def extract_public_ipv6(server_info):
205 try:
206 return server_info["ipv6"]["address"]
207 except (KeyError, TypeError):
208 return None
209
210
211 def extract_tags(server_info):
212 try:
213 return server_info["tags"]
214 except (KeyError, TypeError):
215 return None
216
217
218 def extract_zone(server_info):
219 try:
220 return server_info["location"]["zone_id"]
221 except (KeyError, TypeError):
222 return None
223
224
225 extractors = {
226 "public_ipv4": extract_public_ipv4,
227 "private_ipv4": extract_private_ipv4,
228 "public_ipv6": extract_public_ipv6,
229 "hostname": extract_hostname,
230 "id": extract_server_id,
231 }
232
233
234 class InventoryModule(BaseInventoryPlugin, Constructable):
235 NAME = "community.general.scaleway"
236
237 def _fill_host_variables(self, host, server_info):
238 targeted_attributes = (
239 "arch",
240 "commercial_type",
241 "id",
242 "organization",
243 "state",
244 "hostname",
245 )
246 for attribute in targeted_attributes:
247 self.inventory.set_variable(host, attribute, server_info[attribute])
248
249 self.inventory.set_variable(host, "tags", server_info["tags"])
250
251 if extract_public_ipv6(server_info=server_info):
252 self.inventory.set_variable(host, "public_ipv6", extract_public_ipv6(server_info=server_info))
253
254 if extract_public_ipv4(server_info=server_info):
255 self.inventory.set_variable(host, "public_ipv4", extract_public_ipv4(server_info=server_info))
256
257 if extract_private_ipv4(server_info=server_info):
258 self.inventory.set_variable(host, "private_ipv4", extract_private_ipv4(server_info=server_info))
259
260 def _get_zones(self, config_zones):
261 return set(SCALEWAY_LOCATION.keys()).intersection(config_zones)
262
263 def match_groups(self, server_info, tags):
264 server_zone = extract_zone(server_info=server_info)
265 server_tags = extract_tags(server_info=server_info)
266
267 # If a server does not have a zone, it means it is archived
268 if server_zone is None:
269 return set()
270
271 # If no filtering is defined, all tags are valid groups
272 if tags is None:
273 return set(server_tags).union((server_zone,))
274
275 matching_tags = set(server_tags).intersection(tags)
276
277 if not matching_tags:
278 return set()
279 return matching_tags.union((server_zone,))
280
281 def _filter_host(self, host_infos, hostname_preferences):
282 for pref in hostname_preferences:
283 if extractors[pref](host_infos):
284 return extractors[pref](host_infos)
285
286 return None
287
288 def do_zone_inventory(self, zone, token, tags, hostname_preferences):
289 self.inventory.add_group(zone)
290 zone_info = SCALEWAY_LOCATION[zone]
291
292 url = _build_server_url(zone_info["api_endpoint"])
293 raw_zone_hosts_infos = make_unsafe(_fetch_information(url=url, token=token))
294
295 for host_infos in raw_zone_hosts_infos:
296 hostname = self._filter_host(host_infos=host_infos, hostname_preferences=hostname_preferences)
297
298 # No suitable hostname were found in the attributes and the host won't be in the inventory
299 if not hostname:
300 continue
301
302 groups = self.match_groups(host_infos, tags)
303
304 for group in groups:
305 self.inventory.add_group(group=group)
306 self.inventory.add_host(group=group, host=hostname)
307 self._fill_host_variables(host=hostname, server_info=host_infos)
308
309 # Composed variables
310 self._set_composite_vars(self.get_option("variables"), host_infos, hostname, strict=False)
311
312 def get_oauth_token(self):
313 oauth_token = self.get_option("oauth_token")
314
315 if "SCW_CONFIG_PATH" in os.environ:
316 scw_config_path = os.getenv("SCW_CONFIG_PATH")
317 elif "XDG_CONFIG_HOME" in os.environ:
318 scw_config_path = os.path.join(os.getenv("XDG_CONFIG_HOME"), "scw", "config.yaml")
319 else:
320 scw_config_path = os.path.join(os.path.expanduser("~"), ".config", "scw", "config.yaml")
321
322 if not oauth_token and os.path.exists(scw_config_path):
323 with open(scw_config_path) as fh:
324 scw_config = yaml.safe_load(fh)
325 ansible_profile = self.get_option("scw_profile")
326
327 if ansible_profile:
328 active_profile = ansible_profile
329 else:
330 active_profile = scw_config.get("active_profile", "default")
331
332 if active_profile == "default":
333 oauth_token = scw_config.get("secret_key")
334 else:
335 oauth_token = scw_config["profiles"][active_profile].get("secret_key")
336
337 return oauth_token
338
339 def parse(self, inventory, loader, path, cache=True):
340 if YAML_IMPORT_ERROR:
341 raise AnsibleError("PyYAML is probably missing") from YAML_IMPORT_ERROR
342 super().parse(inventory, loader, path)
343 self._read_config_data(path=path)
344
345 config_zones = self.get_option("regions")
346 tags = self.get_option("tags")
347 token = self.get_oauth_token()
348 if not token:
349 raise AnsibleError(
350 "'oauth_token' value is null, you must configure it either in inventory, envvars or scaleway-cli config."
351 )
352 hostname_preference = self.get_option("hostnames")
353
354 for zone in self._get_zones(config_zones):
355 self.do_zone_inventory(
356 zone=make_unsafe(zone), token=token, tags=tags, hostname_preferences=hostname_preference
357 )