Debian Codegraph @

ansible_collections/community/hrobot/plugins/modules/v_switch.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2022 Alexander Gil Casas <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r"""
14 module: v_switch
15 short_description: Manage Hetzner's vSwitch
16 version_added: 1.7.0
17 author:
18 - Alexander Gil Casas (@pando85)
19 description:
20 - Manage Hetzner's vSwitch.
21 seealso:
22 - name: vSwitch documentation
23 description: Hetzner's documentation on vSwitch for connecting dedicated servers.
24 link: https://docs.hetzner.com/robot/dedicated-server/network/vswitch
25 extends_documentation_fragment:
26 - community.hrobot.robot
27 - community.hrobot.attributes
28 - community.hrobot.attributes.actiongroup_robot
29
30 attributes:
31 check_mode:
32 support: full
33 diff_mode:
34 support: none
35 idempotent:
36 support: full
37 action_group:
38 version_added: 2.1.0
39
40 options:
41 vlan:
42 description:
43 - The vSwitch's VLAN ID.
44 - Range can be from 4000 to 4091.
45 - In order to identify a vSwitch both name and VLAN must match. If not, a new vSwitch will be created.
46 type: int
47 required: true
48 name:
49 description:
50 - The vSwitch's name.
51 - In order to identify a vSwitch both name and VLAN must match. If not, a new vSwitch will be created.
52 type: str
53 required: true
54 state:
55 description:
56 - State of the vSwitch.
57 - VSwitch is created if state is V(present), and deleted if state is V(absent).
58 - V(absent) just cancels the vSwitch at the end of the current day.
59 - When cancelling, you have to specify O(servers=[]) if you want to actively remove the servers in the vSwitch.
60 type: str
61 default: present
62 choices: [present, absent]
63 servers:
64 description:
65 - List of server identifiers (server's numeric ID or server's main IPv4 or IPv6).
66 - If servers is not specified, servers are not going to be deleted.
67 type: list
68 elements: str
69 wait:
70 description:
71 - Whether to wait until the vSwitch has been successfully configured before determining what to do, and before returning
72 from the module.
73 - The API returns status C(in process) when the vSwitch is currently being set up in the servers. If this happens, the
74 module will try again until the status changes to C(ready) or server has been removed from vSwitch.
75 - Please note that if you disable wait while deleting and removing servers module will fail with C(VSWITCH_IN_PROCESS)
76 error.
77 type: bool
78 default: true
79 wait_delay:
80 description:
81 - Delay to wait (in seconds) before checking again whether the vSwitch servers has been configured.
82 type: int
83 default: 10
84 timeout:
85 description:
86 - Timeout (in seconds) for waiting for vSwitch servers to be configured.
87 type: int
88 default: 180
89 """
90
91 EXAMPLES = r"""
92 ---
93 - name: Create vSwitch with VLAN 4010 and name foo
94 community.hrobot.v_switch:
95 hetzner_user: foo
96 hetzner_password: bar
97 vlan: 4010
98 name: foo
99
100 - name: Create vSwitch with VLAN 4020 and name foo with two servers
101 community.hrobot.v_switch:
102 hetzner_user: foo
103 hetzner_password: bar
104 vlan: 4010
105 name: foo
106 servers:
107 - 123.123.123.123
108 - 154323
109 """
110
111 RETURN = r"""
112 v_switch:
113 description:
114 - Information on the vSwitch.
115 returned: success
116 type: dict
117 contains:
118 id:
119 description:
120 - The vSwitch's ID.
121 type: int
122 sample: 4321
123 returned: success
124 name:
125 description:
126 - The vSwitch's name.
127 type: str
128 sample: 'my vSwitch'
129 returned: success
130 vlan:
131 description:
132 - The vSwitch's VLAN ID.
133 type: int
134 sample: 4000
135 returned: success
136 cancelled:
137 description:
138 - Cancellation status.
139 type: bool
140 sample: false
141 returned: success
142 server:
143 description:
144 - The vSwitch's VLAN.
145 type: list
146 elements: dict
147 sample:
148 - server_ip: '123.123.123.123'
149 server_ipv6_net: '2a01:4f8:111:4221::'
150 server_number: 321
151 status: 'ready'
152 contains:
153 server_ip:
154 description:
155 - The server's main IP address.
156 type: str
157 sample: '123.123.123.123'
158 server_ipv6_net:
159 description:
160 - The server's main IPv6 network address.
161 type: str
162 sample: '2a01:f48:111:4221::'
163 server_number:
164 description:
165 - The server's numeric ID.
166 type: int
167 sample: 321
168 status:
169 description:
170 - Status of vSwitch for this server.
171 type: str
172 choices:
173 - ready
174 - in process
175 - failed
176 sample: 'ready'
177 returned: success
178 subnet:
179 description:
180 - List of assigned IP addresses.
181 type: list
182 elements: dict
183 sample:
184 - ip: '213.239.252.48'
185 mask: 29
186 gateway: '213.239.252.49'
187 contains:
188 ip:
189 description:
190 - IP address.
191 type: str
192 sample: '213.239.252.48'
193 mask:
194 description:
195 - Subnet mask in CIDR notation.
196 type: int
197 sample: 29
198 gateway:
199 description:
200 - Gateway of the subnet.
201 type: str
202 sample: '213.239.252.49'
203 returned: success
204 cloud_network:
205 description:
206 - List of assigned Cloud networks.
207 type: list
208 elements: dict
209 sample:
210 - id: 123
211 ip: '10.0.2.0'
212 mask: 24
213 gateway: '10.0.2.1'
214 contains:
215 id:
216 description:
217 - Cloud network ID.
218 type: int
219 sample: 123
220 ip:
221 description:
222 - IP address.
223 type: str
224 sample: '10.0.2.0'
225 mask:
226 description:
227 - Subnet mask in CIDR notation.
228 type: int
229 sample: 24
230 gateway:
231 description:
232 - Gateway.
233 type: str
234 sample: '10.0.2.1'
235 returned: success
236 """
237
238
239 from datetime import datetime
240
241 from ansible.module_utils.basic import AnsibleModule
242 from ansible.module_utils.common.text.converters import to_native
243
244 from ansible_collections.community.hrobot.plugins.module_utils.common import (
245 CheckDoneTimeoutException,
246 )
247 from ansible_collections.community.hrobot.plugins.module_utils.robot import (
248 BASE_URL,
249 ROBOT_DEFAULT_ARGUMENT_SPEC,
250 get_x_www_form_urlenconded_dict_from_list,
251 fetch_url_json,
252 fetch_url_json_with_retries,
253 )
254
255 try:
256 from urllib.parse import urlencode
257 except ImportError:
258 # Python 2.x fallback:
259 from urllib import urlencode
260
261 V_SWITCH_BASE_URL = '{0}/vswitch'.format(BASE_URL)
262
263
264 def get_v_switch(module, id_, wait_condition=None):
265 url = '{0}/{1}'.format(V_SWITCH_BASE_URL, id_)
266 accept_errors = ['NOT_FOUND']
267 if wait_condition:
268 try:
269 result, error = fetch_url_json_with_retries(
270 module,
271 url,
272 check_done_callback=wait_condition,
273 check_done_delay=module.params['wait_delay'],
274 check_done_timeout=module.params['timeout'],
275 accept_errors=accept_errors,
276 )
277 except CheckDoneTimeoutException as dummy:
278 module.fail_json(msg='Timeout waiting vSwitch operation to finish')
279 else:
280 result, error = fetch_url_json(
281 module,
282 url,
283 accept_errors=accept_errors,
284 )
285
286 if error == 'NOT_FOUND':
287 module.fail_json(msg='vSwitch not found.')
288
289 return result
290
291
292 def print_list(possible_list):
293 if isinstance(possible_list, list):
294 return ', '.join([to_native(x) for x in possible_list])
295 return repr(possible_list)
296
297
298 def create_v_switch(module):
299 headers = {'Content-type': 'application/x-www-form-urlencoded'}
300 data = {'name': module.params['name'], 'vlan': module.params['vlan']}
301 result, error = fetch_url_json(
302 module,
303 V_SWITCH_BASE_URL,
304 data=urlencode(data),
305 headers=headers,
306 method='POST',
307 accept_errors=['INVALID_INPUT', 'VSWITCH_LIMIT_REACHED'],
308 )
309 if error == 'INVALID_INPUT':
310 invalid_parameters = print_list(result['error']['invalid'])
311 module.fail_json(msg='vSwitch invalid parameter ({0})'.format(invalid_parameters))
312 elif error == 'VSWITCH_LIMIT_REACHED':
313 module.fail_json(msg='The maximum count of vSwitches is reached')
314
315 return result
316
317
318 def delete_v_switch(module, id_):
319 url = '{0}/{1}'.format(V_SWITCH_BASE_URL, id_)
320 headers = {'Content-type': 'application/x-www-form-urlencoded'}
321 data = {'cancellation_date': datetime.now().strftime('%y-%m-%d')}
322 result, error = fetch_url_json(
323 module,
324 url,
325 data=urlencode(data),
326 headers=headers,
327 method='DELETE',
328 accept_errors=['INVALID_INPUT', 'NOT_FOUND', 'CONFLICT'],
329 allow_empty_result=True,
330 )
331 if error == 'INVALID_INPUT':
332 invalid_parameters = print_list(result['error']['invalid'])
333 module.fail_json(msg='vSwitch invalid parameter ({0})'.format(invalid_parameters))
334 elif error == 'NOT_FOUND':
335 module.fail_json(msg='vSwitch not found to delete')
336 elif error == 'CONFLICT':
337 module.fail_json(msg='The vSwitch is already cancelled')
338
339 return result
340
341
342 def is_all_servers_ready(result, dummy):
343 return all(server['status'] == 'ready' for server in result['server'])
344
345
346 def add_servers(module, id_, servers):
347 url = '{0}/{1}/server'.format(V_SWITCH_BASE_URL, id_)
348 headers = {'Content-type': 'application/x-www-form-urlencoded'}
349 data = get_x_www_form_urlenconded_dict_from_list('server', servers)
350 result, error = fetch_url_json(
351 module,
352 url,
353 data=urlencode(data),
354 headers=headers,
355 method='POST',
356 # TODO: missing NOT_FOUND, VSWITCH_NOT_AVAILABLE, VSWITCH_PER_SERVER_LIMIT_REACHED
357 accept_errors=[
358 'INVALID_INPUT',
359 'SERVER_NOT_FOUND',
360 'VSWITCH_VLAN_NOT_UNIQUE',
361 'VSWITCH_IN_PROCESS',
362 'VSWITCH_SERVER_LIMIT_REACHED',
363 ],
364 allow_empty_result=True,
365 allowed_empty_result_status_codes=(201,),
366 )
367 if error == 'INVALID_INPUT':
368 invalid_parameters = print_list(result['error']['invalid'])
369 module.fail_json(msg='Invalid parameter adding server ({0})'.format(invalid_parameters))
370 elif error == 'SERVER_NOT_FOUND':
371 # information about which servers are failing is only there
372 module.fail_json(msg=result['error']['message'])
373 elif error == 'VSWITCH_VLAN_NOT_UNIQUE':
374 # information about which servers are failing is only there
375 module.fail_json(msg=result['error']['message'])
376 elif error == 'VSWITCH_IN_PROCESS':
377 module.fail_json(msg='There is a update running, therefore the vswitch can not be updated')
378 elif error == 'VSWITCH_SERVER_LIMIT_REACHED':
379 module.fail_json(msg='The maximum number of servers is reached for this vSwitch')
380
381 # TODO: add and delete with `wait=false`
382 wait_condition = is_all_servers_ready if module.params['wait'] else None
383 return get_v_switch(module, id_, wait_condition)
384
385
386 def delete_servers(module, id_, servers):
387 url = '{0}/{1}/server'.format(V_SWITCH_BASE_URL, id_)
388 headers = {'Content-type': 'application/x-www-form-urlencoded'}
389 data = get_x_www_form_urlenconded_dict_from_list('server', servers)
390 result, error = fetch_url_json(
391 module,
392 url,
393 data=urlencode(data),
394 headers=headers,
395 method='DELETE',
396 # TODO: missing INVALID_INPUT, NOT_FOUND
397 accept_errors=['SERVER_NOT_FOUND', 'VSWITCH_IN_PROCESS'],
398 allow_empty_result=True,
399 )
400 if error == 'SERVER_NOT_FOUND':
401 # information about which servers are failing is only there
402 module.fail_json(msg=result['error']['message'])
403 elif error == 'VSWITCH_IN_PROCESS':
404 module.fail_json(msg='There is a update running, therefore the vswitch can not be updated')
405
406 wait_condition = is_all_servers_ready if module.params['wait'] else None
407 return get_v_switch(module, id_, wait_condition)
408
409
410 def get_servers_to_delete(current_servers, desired_servers):
411 return [
412 server['server_ip']
413 for server in current_servers
414 if server['server_ip'] not in desired_servers
415 and server['server_ipv6_net'] not in desired_servers
416 and str(server['server_number']) not in desired_servers
417 ]
418
419
420 def get_servers_to_add(current_servers, desired_servers):
421 current_ids = [str(server['server_number']) for server in current_servers]
422 current_ips = [server['server_ip'] for server in current_servers]
423 current_ipv6s = [server['server_ipv6_net'] for server in current_servers]
424
425 return [
426 server
427 for server in desired_servers
428 if server not in current_ips and server not in current_ids and server not in current_ipv6s
429 ]
430
431
432 def set_desired_servers(module, id_):
433 v_switch = get_v_switch(module, id_)
434 changed = False
435
436 if module.params['servers'] is None:
437 return (v_switch, changed)
438
439 servers_to_delete = get_servers_to_delete(v_switch['server'], module.params['servers'])
440 if servers_to_delete:
441 if not module.check_mode:
442 v_switch = delete_servers(module, id_, servers_to_delete)
443 changed = True
444 servers_to_add = get_servers_to_add(v_switch['server'], module.params['servers'])
445 if servers_to_add:
446 if not module.check_mode:
447 v_switch = add_servers(module, id_, servers_to_add)
448 changed = True
449 return (v_switch, changed)
450
451
452 def main():
453 argument_spec = dict(
454 vlan=dict(type='int', required=True),
455 name=dict(type='str', required=True),
456 state=dict(type='str', default='present', choices=['present', 'absent']),
457 servers=dict(type='list', elements='str'),
458 wait=dict(type='bool', default=True),
459 wait_delay=dict(type='int', default=10),
460 timeout=dict(type='int', default=180),
461 )
462 argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC)
463 module = AnsibleModule(
464 argument_spec=argument_spec,
465 supports_check_mode=True,
466 )
467
468 v_switches, error = fetch_url_json(module, V_SWITCH_BASE_URL, accept_errors=['UNAUTHORIZED'])
469
470 if error:
471 module.fail_json(msg='Please check your current user and password configuration')
472
473 matched_v_switches = [
474 v
475 for v in v_switches
476 if v['name'] == module.params['name'] and v['vlan'] == module.params['vlan']
477 ]
478 non_cancelled_v_switches = [m for m in matched_v_switches if m['cancelled'] is False]
479 result = {'changed': False}
480
481 if len(non_cancelled_v_switches) > 1:
482 module.fail_json(
483 msg='Multiple vSwitches with same name and VLAN ID in non cancelled status. Clean it.'
484 )
485
486 elif len(non_cancelled_v_switches) == 1:
487 id_ = non_cancelled_v_switches[0]['id']
488 v_switch, changed = set_desired_servers(module, id_)
489 if changed:
490 result['changed'] = True
491
492 if module.params['state'] == 'present':
493 result['v_switch'] = v_switch
494 elif module.params['state'] == 'absent':
495 if not module.check_mode:
496 delete_v_switch(module, id_)
497 result['changed'] = True
498 else: # pragma: no cover
499 raise NotImplementedError("not reachable") # pragma: no cover
500 else:
501 if module.params['state'] == 'present':
502 result['changed'] = True
503 if not module.check_mode:
504 v_switch = create_v_switch(module)
505 if module.params['servers']:
506 result['v_switch'] = add_servers(module, v_switch['id'], module.params['servers'])
507 else:
508 result['v_switch'] = v_switch
509
510 module.exit_json(**result)
511
512
513 if __name__ == '__main__': # pragma: no cover
514 main() # pragma: no cover