Debian Codegraph @

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

raw
1 # Copyright (c) 2018 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: online
9 author:
10 - Remy Leone (@remyleone)
11 short_description: Scaleway (previously Online SAS or Online.net) inventory source
12 description:
13 - Get inventory hosts from Scaleway (previously Online SAS or Online.net).
14 options:
15 plugin:
16 description: Token that ensures this is a source file for the P(community.general.online#inventory) plugin.
17 type: string
18 required: true
19 choices: ['online', 'community.general.online']
20 oauth_token:
21 required: true
22 description: Online OAuth token.
23 type: string
24 env:
25 # in order of precedence
26 - name: ONLINE_TOKEN
27 - name: ONLINE_API_KEY
28 - name: ONLINE_OAUTH_TOKEN
29 hostnames:
30 description: List of preference about what to use as an hostname.
31 type: list
32 elements: string
33 default:
34 - public_ipv4
35 choices:
36 - public_ipv4
37 - private_ipv4
38 - hostname
39 groups:
40 description: List of groups.
41 type: list
42 elements: string
43 choices:
44 - location
45 - offer
46 - rpn
47 """
48
49 EXAMPLES = r"""
50 # online_inventory.yml file in YAML format
51 # Example command line: ansible-inventory --list -i online_inventory.yml
52
53 plugin: community.general.online
54 hostnames:
55 - public_ipv4
56 groups:
57 - location
58 - offer
59 - rpn
60 """
61
62 import json
63 from sys import version as python_version
64 from urllib.parse import urljoin
65
66 from ansible.errors import AnsibleError
67 from ansible.module_utils.ansible_release import __version__ as ansible_version
68 from ansible.module_utils.common.text.converters import to_text
69 from ansible.module_utils.urls import open_url
70 from ansible.plugins.inventory import BaseInventoryPlugin
71
72 from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe
73
74
75 class InventoryModule(BaseInventoryPlugin):
76 NAME = "community.general.online"
77 API_ENDPOINT = "https://api.online.net"
78
79 def extract_public_ipv4(self, host_infos):
80 try:
81 return host_infos["network"]["ip"][0]
82 except (KeyError, TypeError, IndexError):
83 self.display.warning("An error happened while extracting public IPv4 address. Information skipped.")
84 return None
85
86 def extract_private_ipv4(self, host_infos):
87 try:
88 return host_infos["network"]["private"][0]
89 except (KeyError, TypeError, IndexError):
90 self.display.warning("An error happened while extracting private IPv4 address. Information skipped.")
91 return None
92
93 def extract_os_name(self, host_infos):
94 try:
95 return host_infos["os"]["name"]
96 except (KeyError, TypeError):
97 self.display.warning("An error happened while extracting OS name. Information skipped.")
98 return None
99
100 def extract_os_version(self, host_infos):
101 try:
102 return host_infos["os"]["version"]
103 except (KeyError, TypeError):
104 self.display.warning("An error happened while extracting OS version. Information skipped.")
105 return None
106
107 def extract_hostname(self, host_infos):
108 try:
109 return host_infos["hostname"]
110 except (KeyError, TypeError):
111 self.display.warning("An error happened while extracting hostname. Information skipped.")
112 return None
113
114 def extract_location(self, host_infos):
115 try:
116 return host_infos["location"]["datacenter"]
117 except (KeyError, TypeError):
118 self.display.warning("An error happened while extracting datacenter location. Information skipped.")
119 return None
120
121 def extract_offer(self, host_infos):
122 try:
123 return host_infos["offer"]
124 except (KeyError, TypeError):
125 self.display.warning("An error happened while extracting commercial offer. Information skipped.")
126 return None
127
128 def extract_rpn(self, host_infos):
129 try:
130 return self.rpn_lookup_cache[host_infos["id"]]
131 except (KeyError, TypeError):
132 self.display.warning("An error happened while extracting RPN information. Information skipped.")
133 return None
134
135 def _fetch_information(self, url):
136 try:
137 response = open_url(url, headers=self.headers)
138 except Exception:
139 self.display.warning(f"An error happened while fetching: {url}")
140 return None
141
142 try:
143 raw_data = to_text(response.read(), errors="surrogate_or_strict")
144 except UnicodeError as e:
145 raise AnsibleError("Incorrect encoding of fetched payload from Online servers") from e
146
147 try:
148 return json.loads(raw_data)
149 except ValueError as e:
150 raise AnsibleError("Incorrect JSON payload") from e
151
152 @staticmethod
153 def extract_rpn_lookup_cache(rpn_list):
154 lookup = {}
155 for rpn in rpn_list:
156 for member in rpn["members"]:
157 lookup[member["id"]] = rpn["name"]
158 return lookup
159
160 def _fill_host_variables(self, hostname, host_infos):
161 targeted_attributes = (
162 "offer",
163 "id",
164 "hostname",
165 "location",
166 "boot_mode",
167 "power",
168 "last_reboot",
169 "anti_ddos",
170 "hardware_watch",
171 "support",
172 )
173 for attribute in targeted_attributes:
174 self.inventory.set_variable(hostname, attribute, make_unsafe(host_infos[attribute]))
175
176 if self.extract_public_ipv4(host_infos=host_infos):
177 self.inventory.set_variable(
178 hostname, "public_ipv4", make_unsafe(self.extract_public_ipv4(host_infos=host_infos))
179 )
180 self.inventory.set_variable(
181 hostname, "ansible_host", make_unsafe(self.extract_public_ipv4(host_infos=host_infos))
182 )
183
184 if self.extract_private_ipv4(host_infos=host_infos):
185 self.inventory.set_variable(
186 hostname, "public_ipv4", make_unsafe(self.extract_private_ipv4(host_infos=host_infos))
187 )
188
189 if self.extract_os_name(host_infos=host_infos):
190 self.inventory.set_variable(hostname, "os_name", make_unsafe(self.extract_os_name(host_infos=host_infos)))
191
192 if self.extract_os_version(host_infos=host_infos):
193 self.inventory.set_variable(
194 hostname, "os_version", make_unsafe(self.extract_os_name(host_infos=host_infos))
195 )
196
197 def _filter_host(self, host_infos, hostname_preferences):
198 for pref in hostname_preferences:
199 if self.extractors[pref](host_infos):
200 return self.extractors[pref](host_infos)
201
202 return None
203
204 def do_server_inventory(self, host_infos, hostname_preferences, group_preferences):
205 hostname = self._filter_host(host_infos=host_infos, hostname_preferences=hostname_preferences)
206
207 # No suitable hostname were found in the attributes and the host won't be in the inventory
208 if not hostname:
209 return
210
211 hostname = make_unsafe(hostname)
212
213 self.inventory.add_host(host=hostname)
214 self._fill_host_variables(hostname=hostname, host_infos=host_infos)
215
216 for g in group_preferences:
217 group = self.group_extractors[g](host_infos)
218
219 if not group:
220 return
221
222 group = make_unsafe(group)
223
224 self.inventory.add_group(group=group)
225 self.inventory.add_host(group=group, host=hostname)
226
227 def parse(self, inventory, loader, path, cache=True):
228 super().parse(inventory, loader, path)
229 self._read_config_data(path=path)
230
231 token = self.get_option("oauth_token")
232 hostname_preferences = self.get_option("hostnames")
233
234 group_preferences = self.get_option("groups")
235 if group_preferences is None:
236 group_preferences = []
237
238 self.extractors = {
239 "public_ipv4": self.extract_public_ipv4,
240 "private_ipv4": self.extract_private_ipv4,
241 "hostname": self.extract_hostname,
242 }
243
244 self.group_extractors = {
245 "location": self.extract_location,
246 "offer": self.extract_offer,
247 "rpn": self.extract_rpn,
248 }
249
250 self.headers = {
251 "Authorization": f"Bearer {token}",
252 "User-Agent": f"ansible {ansible_version} Python {python_version.split(' ', 1)[0]}",
253 "Content-type": "application/json",
254 }
255
256 servers_url = urljoin(InventoryModule.API_ENDPOINT, "api/v1/server")
257 servers_api_path = self._fetch_information(url=servers_url)
258
259 if "rpn" in group_preferences:
260 rpn_groups_url = urljoin(InventoryModule.API_ENDPOINT, "api/v1/rpn/group")
261 rpn_list = self._fetch_information(url=rpn_groups_url)
262 self.rpn_lookup_cache = self.extract_rpn_lookup_cache(rpn_list)
263
264 for server_api_path in servers_api_path:
265 server_url = urljoin(InventoryModule.API_ENDPOINT, server_api_path)
266 raw_server_info = self._fetch_information(url=server_url)
267
268 if raw_server_info is None:
269 continue
270
271 self.do_server_inventory(
272 host_infos=raw_server_info,
273 hostname_preferences=hostname_preferences,
274 group_preferences=group_preferences,
275 )