Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2025 Victor LEFEBVRE <[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: storagebox_subaccount
15 short_description: Create, update, or delete a subaccount for a storage box
16 version_added: 2.4.0
17 author:
18 - Victor LEFEBVRE (@vic1707)
19 description:
20 - Create, update, or delete a subaccount for a storage box.
21 extends_documentation_fragment:
22 - community.hrobot.api._robot_compat_shim_deprecation # must come before api and robot
23 - community.hrobot.api
24 - community.hrobot.robot
25 - community.hrobot.attributes
26 - community.hrobot.attributes._actiongroup_robot_and_api_deprecation # must come before the other two!
27 - community.hrobot.attributes.actiongroup_api
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: partial
37 details:
38 - The Hetzner API does not allow to create subaccounts with specific usernames.
39 You can instead use O(comment) to identify accounts by setting O(idempotence=comment),
40 that way creation is idempotent.
41 - The module is never idempotent if O(password_mode=set-to-random), or if O(password_mode=update-if-provided) and O(password) is specified.
42 Set O(password_mode=ignore-if-exists) if you want to provide O(password) on every invocation
43 and do not want the module to always change it. Due to how Hetzner's API works, it is not possible
44 to query the current password for a subaccount, or check whether a given password is set.
45
46 options:
47 hetzner_token:
48 version_added: 2.5.0
49 storagebox_id:
50 description:
51 - The ID of the storage box to query.
52 type: int
53 required: true
54 password_mode:
55 description:
56 - Controls how password updates are handled.
57 - If C(update-if-provided), the password always updated if provided (default).
58 - If C(ignore-if-exists), password is only used during creation.
59 - If C(set-to-random), password is reset to a randomly generated one.
60 Note that this is not supported by the new API (when O(hetzner_token) is set).
61 The value has been deprecated in community.hrobot 2.7.0 and will be removed from community.hrobot 3.0.0.
62 - When a new subaccount is created, the password is set to the specified one if O(password) is provided,
63 and a random password is set if O(password) is not provided.
64 type: str
65 choices: [update-if-provided, ignore-if-exists, set-to-random]
66 default: update-if-provided
67 required: false
68
69 state:
70 description:
71 - Desired state of this subaccount.
72 choices: [present, absent]
73 type: str
74 default: present
75
76 username:
77 description:
78 - Username of the subaccount.
79 - Required when using O(idempotence=username) for updates or deletion of a subaccount.
80 - If O(idempotence=username) and this is not specified, a new subaccount will always be created.
81 If O(idempotence=comment), this option is ignored, as the Hetzner API does not allow to chose or modify the username.
82 type: str
83 required: false
84
85 password:
86 description:
87 - Password to use or change.
88 - See O(password_mode) for how and when this is used.
89 - Will be ignored if O(password_mode=set-to-random).
90 type: str
91 required: false
92
93 homedirectory:
94 description:
95 - Home directory of the subaccount.
96 - Required only when creating a subaccount (O(state=present)).
97 type: str
98 required: false
99
100 samba:
101 description:
102 - Enable or disable Samba.
103 type: bool
104 required: false
105
106 ssh:
107 description:
108 - Enable or disable SSH access.
109 type: bool
110 required: false
111
112 external_reachability:
113 description:
114 - Enable or disable external reachability (from outside Hetzner's networks).
115 type: bool
116 required: false
117
118 webdav:
119 description:
120 - Enable or disable WebDAV.
121 type: bool
122 required: false
123
124 readonly:
125 description:
126 - Enable or disable read-only mode.
127 type: bool
128 required: false
129
130 comment:
131 description:
132 - A custom comment for the subaccount.
133 - Is required when using O(idempotence=comment) for updates or deletion of a subaccount.
134 type: str
135 required: false
136
137 idempotence:
138 description:
139 - Select which attribute to use to check subaccount existence.
140 - If set to C(username), then subaccounts are identified by their username.
141 Note that usernames cannot be specified on creation, so you need to use different
142 module arguments for creation and updating.
143 - If set to C(comment), then subaccounts are identified by their comment.
144 If there already exist more than one subaccount with the given comment, the module will fail.
145 type: str
146 choices: [username, comment]
147 default: username
148 required: false
149
150 notes:
151 - When passwords are autogenerated by the API (by omitting the O(password) field), the resulting password is returned.
152 """
153
154 EXAMPLES = r"""
155 ---
156 - name: Create a new subaccount with random password
157 community.hrobot.storagebox_subaccount:
158 storagebox_id: 123456
159 homedirectory: "/backups/project1"
160 samba: true
161 ssh: true
162 webdav: false
163 comment: "Backup for Project 1"
164
165 - name: Create a subaccount with custom password
166 community.hrobot.storagebox_subaccount:
167 storagebox_id: 123456
168 username: "backup1"
169 password: "s3cretPass123"
170 homedirectory: "/data/backup1"
171 readonly: false
172 samba: true
173 ssh: false
174
175 - name: Update an existing subaccount
176 community.hrobot.storagebox_subaccount:
177 storagebox_id: 123456
178 state: present
179 username: "backup1"
180 homedirectory: "/data/backup1-updated"
181 readonly: true
182 comment: "Updated path and readonly mode"
183
184 - name: Delete a subaccount
185 community.hrobot.storagebox_subaccount:
186 storagebox_id: 123456
187 state: absent
188 username: "backup1"
189
190 - name: Change password for a subaccount
191 community.hrobot.storagebox_subaccount:
192 storagebox_id: 123456
193 state: present
194 username: "backup1"
195 password: "n3wSecur3Pass"
196
197 - name: Create subaccount using comment for idempotence
198 community.hrobot.storagebox_subaccount:
199 storagebox_id: 123456
200 homedirectory: "/projects/backup1"
201 samba: true
202 ssh: true
203 webdav: false
204 readonly: false
205 comment: "Backup1 - Project Foo"
206 idempotence: comment
207
208 - name: Update subaccount identified by comment
209 community.hrobot.storagebox_subaccount:
210 storagebox_id: 123456
211 homedirectory: "/projects/backup1-updated"
212 readonly: true
213 comment: "Backup1 - Project Foo"
214 idempotence: comment
215
216 - name: Update password for subaccount using comment idempotence
217 community.hrobot.storagebox_subaccount:
218 storagebox_id: 123456
219 password: "Sup3rSecur3!"
220 comment: "Backup1 - Project Foo"
221 idempotence: comment
222 password_mode: update-if-provided
223
224 - name: Delete subaccount identified by comment
225 community.hrobot.storagebox_subaccount:
226 storagebox_id: 123456
227 state: absent
228 comment: "Backup1 - Project Foo"
229 idempotence: comment
230
231 - name: Use password only during creation
232 community.hrobot.storagebox_subaccount:
233 storagebox_id: 123456
234 password: "InitPass$42"
235 homedirectory: "/mnt/init"
236 samba: true
237 ssh: false
238 comment: "Init Subaccount"
239 idempotence: comment
240 password_mode: ignore-if-exists
241
242 - name: Always reset to a random password
243 community.hrobot.storagebox_subaccount:
244 storagebox_id: 123456
245 comment: "Temp Access - CI/CD"
246 idempotence: comment
247 password_mode: set-to-random
248 """
249
250 RETURN = r"""
251 created:
252 description: Whether a new subaccount was created.
253 type: bool
254 returned: success
255
256 deleted:
257 description: Whether the subaccount was deleted.
258 type: bool
259 returned: success
260
261 updated:
262 description: Whether the subaccount's configuration was updated (excluding password changes).
263 type: bool
264 returned: success
265
266 password_updated:
267 description: Whether the subaccount's password was updated.
268 type: bool
269 returned: success
270
271 subaccount:
272 description:
273 - The subaccount object returned by the API.
274 - If O(hetzner_token) is provided, some extra fields are added to make this more compatible with the format returned by O(hetzner_user).
275 - B(This extra return values are deprecated and will be removed from community.hrobot 3.0.0.)
276 If you are using ansible-core 2.19 or newer, you will see a deprecation message when using these return values.
277 These return values are RV(ignore:homedirectory), RV(ignore:samba), RV(ignore:ssh), RV(ignore:webdav), RV(ignore:external_reachability),
278 RV(ignore:readonly), RV(ignore:createtime), and RV(ignore:comment).
279 type: dict
280 returned: if O(state=present)
281 """
282
283 from copy import deepcopy
284 from ansible.module_utils.basic import AnsibleModule
285
286 from ansible_collections.community.hrobot.plugins.module_utils.robot import (
287 BASE_URL,
288 ROBOT_DEFAULT_ARGUMENT_SPEC,
289 _ROBOT_DEFAULT_ARGUMENT_SPEC_COMPAT_DEPRECATED,
290 fetch_url_json,
291 )
292
293 from ansible_collections.community.hrobot.plugins.module_utils.api import (
294 API_BASE_URL,
295 API_DEFAULT_ARGUMENT_SPEC,
296 _API_DEFAULT_ARGUMENT_SPEC_COMPAT,
297 ApplyActionError,
298 api_apply_action,
299 api_fetch_url_json,
300 )
301
302 from ansible_collections.community.hrobot.plugins.module_utils._tagging import (
303 deprecate_value,
304 )
305
306 try:
307 from urllib.parse import urlencode
308 except ImportError:
309 # Python 2.x fallback:
310 from urllib import urlencode
311
312
313 def legacy_encode_data(data):
314 """Converts booleans to lowercase strings and filters out None values."""
315 return urlencode(
316 {
317 key: str(value).lower() if isinstance(value, bool) else value
318 for key, value in data.items()
319 if value is not None
320 }
321 )
322
323
324 def legacy_create_subaccount(module, storagebox_id, subaccount):
325 url = "{0}/storagebox/{1}/subaccount".format(BASE_URL, storagebox_id)
326 res, error = fetch_url_json(
327 module,
328 url,
329 method="POST",
330 data=legacy_encode_data(subaccount),
331 headers={"Content-type": "application/x-www-form-urlencoded"},
332 accept_errors=[
333 "STORAGEBOX_SUBACCOUNT_LIMIT_EXCEEDED",
334 "STORAGEBOX_INVALID_PASSWORD",
335 ],
336 timeout=30000, # this endpoint is stupidly slow
337 )
338
339 if error == "STORAGEBOX_INVALID_PASSWORD":
340 module.fail_json(msg="Invalid password (says Hetzner)")
341 if error == "STORAGEBOX_SUBACCOUNT_LIMIT_EXCEEDED":
342 module.fail_json(msg="Subaccount limit exceeded")
343
344 # Contains all subaccount informations
345 # { "subaccount": <data> }
346 return res["subaccount"]
347
348
349 def legacy_merge_subaccounts_infos(original, updates):
350 # None values aren't updated
351 result = original.copy()
352 for key, value in updates.items():
353 if value is not None:
354 result[key] = value
355 return result
356
357
358 def legacy_is_subaccount_updated(before, after):
359 for key, value in after.items():
360 # Means user didn't provide a value
361 # we assume we don't want to update that field
362 if value is None:
363 continue
364 # password aren't considered part of update check
365 # due to being a different API call
366 if key == "password":
367 continue
368 if before.get(key) != value:
369 return True
370 return False
371
372
373 def legacy_delete_subaccount(module, storagebox_id, subaccount):
374 empty, error = fetch_url_json(
375 module,
376 "{0}/storagebox/{1}/subaccount/{2}".format(
377 BASE_URL, storagebox_id, subaccount["username"]
378 ),
379 method="DELETE",
380 allow_empty_result=True,
381 headers={"Content-type": "application/x-www-form-urlencoded"},
382 )
383
384
385 def legacy_update_subaccount(module, storagebox_id, subaccount):
386 empty, error = fetch_url_json(
387 module,
388 "{0}/storagebox/{1}/subaccount/{2}".format(
389 BASE_URL, storagebox_id, subaccount["username"]
390 ),
391 method="PUT",
392 data=legacy_encode_data({key: value for key, value in subaccount.items() if key != "password"}),
393 headers={"Content-type": "application/x-www-form-urlencoded"},
394 allow_empty_result=True,
395 timeout=30000, # this endpoint is stupidly slow
396 )
397
398
399 def legacy_update_subaccount_password(module, storagebox_id, subaccount):
400 new_password, error = fetch_url_json(
401 module,
402 "{0}/storagebox/{1}/subaccount/{2}/password".format(
403 BASE_URL, storagebox_id, subaccount["username"]
404 ),
405 method="POST",
406 data=legacy_encode_data({"password": subaccount["password"]}),
407 headers={"Content-type": "application/x-www-form-urlencoded"},
408 accept_errors=[
409 "STORAGEBOX_INVALID_PASSWORD",
410 ],
411 timeout=30000, # this endpoint is stupidly slow
412 )
413 if error == "STORAGEBOX_INVALID_PASSWORD":
414 module.fail_json(msg="Invalid password (says Hetzner)")
415
416 # { "password": <password> }
417 return new_password["password"]
418
419
420 def legacy_get_subaccounts(module, storagebox_id):
421 url = "{0}/storagebox/{1}/subaccount".format(BASE_URL, storagebox_id)
422 result, error = fetch_url_json(module, url, accept_errors=["STORAGEBOX_NOT_FOUND"])
423 if error:
424 module.fail_json(
425 msg="Storagebox with ID {0} does not exist".format(storagebox_id)
426 )
427 # Hetzner's response [ { "subaccount": <data> }, ... ]
428 return [item["subaccount"] for item in result]
429
430
431 # -----------------------------------------
432
433
434 def create_subaccount(module, storagebox_id, subaccount):
435 action_url = "{0}/v1/storage_boxes/{1}/subaccounts".format(API_BASE_URL, storagebox_id)
436 access_settings = {
437 'samba_enabled': subaccount['samba'],
438 'ssh_enabled': subaccount['ssh'],
439 'webdav_enabled': subaccount['webdav'],
440 'readonly': subaccount['readonly'],
441 'reachable_externally': subaccount['external_reachability'],
442 }
443 action = {
444 'password': subaccount['password'],
445 # For some reason, the home directory must **not** start with a slash, despite being returned that way...
446 'home_directory': subaccount['homedirectory'].lstrip('/') if subaccount['homedirectory'] else subaccount['homedirectory'],
447 'description': subaccount['comment'],
448 'access_settings': {k: v for k, v in access_settings.items() if v is not None},
449 }
450 try:
451 extracted_ids, dummy = api_apply_action(
452 module,
453 action_url,
454 {k: v for k, v in action.items() if v is not None},
455 lambda action_id: "{0}/v1/storage_boxes/actions/{1}".format(API_BASE_URL, action_id),
456 method='POST',
457 check_done_delay=1,
458 check_done_timeout=120,
459 )
460 return extracted_ids["storage_box_subaccount"]
461 except ApplyActionError as exc:
462 module.fail_json(msg='Error while creating subaccount: {0}'.format(exc))
463
464
465 FIELDS = {
466 "username": (["username"], None, None),
467 "samba": (["access_settings", "samba_enabled"], None, "samba_enabled"),
468 "ssh": (["access_settings", "ssh_enabled"], None, "ssh_enabled"),
469 "external_reachability": (["access_settings", "reachable_externally"], None, "reachable_externally"),
470 "webdav": (["access_settings", "webdav_enabled"], None, "webdav_enabled"),
471 "readonly": (["access_settings", "readonly"], None, "readonly"),
472 "comment": (["description"], "description", None),
473 }
474
475
476 def set_value(dictionary, path, value):
477 for key in path[:-1]:
478 if key not in dictionary:
479 dictionary[key] = {}
480 dictionary = dictionary[key]
481 dictionary[path[-1]] = value
482
483
484 def merge_subaccounts_infos(original, updates):
485 # None values aren't updated
486 result = deepcopy(original)
487 for key, value in updates.items():
488 if value is not None:
489 if key == 'password':
490 result[key] = value
491 elif key == 'homedirectory':
492 result["home_directory"] = value
493 else:
494 set_value(result, FIELDS[key][0], value)
495 return result
496
497
498 def get_value(dictionary, path):
499 for key in path[:-1]:
500 dictionary = dictionary[key]
501 return dictionary.get(path[-1])
502
503
504 def get_subaccount_updates(before, after):
505 update = {}
506 access_settings = {}
507 for key, value in after.items():
508 # Means user didn't provide a value
509 # we assume we don't want to update that field
510 if value is None:
511 continue
512 # password and home directory aren't considered part of update check
513 # due to being a different API call
514 if key == "password" or key == "homedirectory":
515 continue
516 path, update_key, access_settings_key = FIELDS[key]
517 current_value = get_value(before, path)
518 if current_value != value:
519 if update_key is not None:
520 update[update_key] = value
521 if access_settings_key is not None:
522 access_settings[access_settings_key] = value
523 return update, access_settings
524
525
526 def delete_subaccount(module, storagebox_id, subaccount):
527 action_url = "{0}/v1/storage_boxes/{1}/subaccounts/{2}".format(API_BASE_URL, storagebox_id, subaccount['id'])
528 try:
529 api_apply_action(
530 module,
531 action_url,
532 None,
533 lambda action_id: "{0}/v1/storage_boxes/actions/{1}".format(API_BASE_URL, action_id),
534 method='DELETE',
535 check_done_delay=1,
536 check_done_timeout=120,
537 )
538 except ApplyActionError as exc:
539 module.fail_json(msg='Error while deleting subaccount: {0}'.format(exc))
540
541
542 def update_subaccount(module, storagebox_id, subaccount, update):
543 url = "{0}/v1/storage_boxes/{1}/subaccounts/{2}".format(API_BASE_URL, storagebox_id, subaccount['id'])
544 headers = {"Content-type": "application/json"}
545 result, dummy, dummy2 = api_fetch_url_json(
546 module,
547 url,
548 method='PUT',
549 data=module.jsonify(update),
550 headers=headers,
551 )
552 return result['subaccount']
553
554
555 def update_access_settings(module, storagebox_id, subaccount, access_settings):
556 action_url = "{0}/v1/storage_boxes/{1}/subaccounts/{2}/actions/update_access_settings".format(API_BASE_URL, storagebox_id, subaccount['id'])
557 try:
558 api_apply_action(
559 module,
560 action_url,
561 access_settings,
562 lambda action_id: "{0}/v1/storage_boxes/actions/{1}".format(API_BASE_URL, action_id),
563 check_done_delay=1,
564 check_done_timeout=120,
565 )
566 except ApplyActionError as exc:
567 module.fail_json(msg='Error while updating access settings: {0}'.format(exc))
568
569
570 def update_subaccount_password(module, storagebox_id, subaccount, new_password):
571 action_url = "{0}/v1/storage_boxes/{1}/subaccounts/{2}/actions/reset_subaccount_password".format(API_BASE_URL, storagebox_id, subaccount['id'])
572 action = {
573 'password': new_password,
574 }
575 try:
576 api_apply_action(
577 module,
578 action_url,
579 action,
580 lambda action_id: "{0}/v1/storage_boxes/actions/{1}".format(API_BASE_URL, action_id),
581 check_done_delay=1,
582 check_done_timeout=120,
583 )
584 except ApplyActionError as exc:
585 module.fail_json(msg='Error while updating password: {0}'.format(exc))
586
587
588 def update_subaccount_home_directory(module, storagebox_id, subaccount, new_home_directory):
589 action_url = "{0}/v1/storage_boxes/{1}/subaccounts/{2}/actions/change_home_directory".format(API_BASE_URL, storagebox_id, subaccount['id'])
590 action = {
591 'home_directory': new_home_directory,
592 }
593 try:
594 api_apply_action(
595 module,
596 action_url,
597 action,
598 lambda action_id: "{0}/v1/storage_boxes/actions/{1}".format(API_BASE_URL, action_id),
599 check_done_delay=1,
600 check_done_timeout=120,
601 )
602 except ApplyActionError as exc:
603 module.fail_json(msg='Error while updating home directory: {0}'.format(exc))
604
605
606 def get_subaccounts(module, storagebox_id, username=None):
607 url = "{0}/v1/storage_boxes/{1}/subaccounts".format(API_BASE_URL, storagebox_id)
608 if username is not None:
609 url = "{0}?{1}".format(url, urlencode({'username': username}))
610 result, dummy, error = api_fetch_url_json(module, url, accept_errors=['not_found'])
611 if error:
612 module.fail_json(msg='Storagebox with ID {0} does not exist'.format(storagebox_id))
613 return result['subaccounts']
614
615
616 def get_value_opt(dictionary, path):
617 for key in path[:-1]:
618 if key not in dictionary:
619 return None, False
620 dictionary = dictionary[key]
621 if path[-1] not in dictionary:
622 return None, False
623 return dictionary.get(path[-1]), True
624
625
626 def adjust_legacy(subaccount):
627 result = dict(subaccount)
628 for key, path in {
629 'homedirectory': ['home_directory'],
630 'samba': ['access_settings', 'samba_enabled'],
631 'ssh': ['access_settings', 'ssh_enabled'],
632 'webdav': ['access_settings', 'webdav_enabled'],
633 'external_reachability': ['access_settings', 'reachable_externally'],
634 'readonly': ['access_settings', 'readonly'],
635 'createtime': ['created'],
636 'comment': ['description'],
637 }.items():
638 value, exists = get_value_opt(subaccount, path)
639 if exists:
640 result[key] = deprecate_value(
641 value,
642 "The return value `{0}` is deprecated; use `{1}` instead.".format(key, ".".join(path)),
643 version="3.0.0",
644 )
645 return result
646
647
648 def main():
649 argument_spec = dict(
650 storagebox_id=dict(type="int", required=True),
651 password_mode=dict(
652 type="str",
653 no_log=False,
654 choices=["update-if-provided", "ignore-if-exists", "set-to-random"],
655 default="update-if-provided",
656 ),
657 state=dict(type="str", choices=["present", "absent"], default="present"),
658 username=dict(type="str"),
659 password=dict(type="str", no_log=True),
660 homedirectory=dict(type="str"),
661 samba=dict(type="bool"),
662 ssh=dict(type="bool"),
663 external_reachability=dict(type="bool"),
664 webdav=dict(type="bool"),
665 readonly=dict(type="bool"),
666 comment=dict(type="str"),
667 idempotence=dict(type="str", choices=["username", "comment"], default="username"),
668 )
669 argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC)
670 argument_spec.update(_ROBOT_DEFAULT_ARGUMENT_SPEC_COMPAT_DEPRECATED)
671 argument_spec.update(API_DEFAULT_ARGUMENT_SPEC)
672 argument_spec.update(_API_DEFAULT_ARGUMENT_SPEC_COMPAT)
673 module = AnsibleModule(
674 argument_spec=argument_spec,
675 supports_check_mode=True,
676 )
677
678 check_mode = module.check_mode
679 storagebox_id = module.params["storagebox_id"]
680 password_mode = module.params["password_mode"]
681 state = module.params["state"]
682 idempotence = module.params["idempotence"]
683 subaccount = {
684 "username": module.params["username"],
685 "password": module.params["password"],
686 "homedirectory": module.params["homedirectory"],
687 "samba": module.params["samba"],
688 "ssh": module.params["ssh"],
689 "external_reachability": module.params["external_reachability"],
690 "webdav": module.params["webdav"],
691 "readonly": module.params["readonly"],
692 "comment": module.params["comment"],
693 }
694 account_identifier = subaccount[idempotence]
695
696 if password_mode == 'set-to-random':
697 module.deprecate(
698 "password_mode=set-to-random is deprecated and will be removed in community.hrobot 3.0.0.",
699 collection_name="community.hrobot",
700 version="3.0.0",
701 )
702
703 if module.params["hetzner_user"] is not None:
704 module.deprecate(
705 "The hetzner_token parameter will be required from community.hrobot 3.0.0 on.",
706 collection_name="community.hrobot",
707 version="3.0.0",
708 )
709 # DEPRECATED: old API
710
711 existing_subaccounts = legacy_get_subaccounts(module, storagebox_id)
712
713 matches = [
714 sa for sa in existing_subaccounts
715 if sa[idempotence] == account_identifier
716 ]
717 if len(matches) > 1:
718 module.fail_json(msg="More than one subaccount matched the idempotence criteria.")
719
720 existing = matches[0] if matches else None
721
722 created = deleted = updated = password_updated = False
723
724 if state == "absent":
725 if existing:
726 if not check_mode:
727 legacy_delete_subaccount(module, storagebox_id, existing)
728 deleted = True
729 elif state == "present" and existing:
730 # Set the found username in case user used comment as idempotence
731 subaccount["username"] = existing["username"]
732
733 if (
734 password_mode == "set-to-random" or
735 (password_mode == "update-if-provided" and subaccount["password"])
736 ):
737 if password_mode == "set-to-random":
738 subaccount["password"] = None
739 if not check_mode:
740 new_password = legacy_update_subaccount_password(module, storagebox_id, subaccount)
741 subaccount["password"] = new_password
742 password_updated = True
743
744 if legacy_is_subaccount_updated(existing, subaccount):
745 if not check_mode:
746 legacy_update_subaccount(module, storagebox_id, subaccount)
747 updated = True
748 else: # state 'present' without pre-existing account
749 if not subaccount["homedirectory"]:
750 module.fail_json(msg="homedirectory is required when creating a new subaccount")
751 if password_mode == "set-to-random":
752 subaccount["password"] = None
753
754 del subaccount["username"] # username cannot be choosen
755 if not check_mode:
756 # not necessary, allows us to get additional infos (created time etc...)
757 existing = legacy_create_subaccount(module, storagebox_id, subaccount)
758 created = True
759
760 return_data = legacy_merge_subaccounts_infos(existing or {}, subaccount)
761
762 module.exit_json(
763 changed=any([created, deleted, updated, password_updated]),
764 created=created,
765 deleted=deleted,
766 updated=updated,
767 password_updated=password_updated,
768 subaccount=return_data if state != "absent" else None,
769 )
770
771 else:
772 # NEW API!
773
774 if password_mode == 'set-to-random':
775 module.fail_json(msg="The new Hetzner API does not support password_mode=set-to-random")
776 if idempotence == 'comment':
777 idempotence = 'description'
778
779 existing_subaccounts = get_subaccounts(module, storagebox_id, username=account_identifier if idempotence == "username" else None)
780
781 matches = [
782 sa for sa in existing_subaccounts
783 if sa[idempotence] == account_identifier
784 ]
785 if len(matches) > 1:
786 module.fail_json(msg="More than one subaccount matched the idempotence criteria.")
787
788 existing = matches[0] if matches else None
789
790 created = deleted = updated = password_updated = homedir_updated = False
791
792 if state == "absent":
793 if existing:
794 if not check_mode:
795 delete_subaccount(module, storagebox_id, existing)
796 deleted = True
797 elif state == "present" and existing:
798 # Set the found username in case user used comment as idempotence
799 subaccount["username"] = existing["username"]
800
801 if (
802 password_mode == "update-if-provided" and subaccount["password"]
803 ):
804 if not check_mode:
805 update_subaccount_password(module, storagebox_id, existing, subaccount["password"])
806 password_updated = True
807
808 if subaccount["homedirectory"] is not None:
809 # Hetzner likes to strip leading '/' from the home directory
810 current_home_dir = existing["home_directory"]
811 if current_home_dir is not None:
812 current_home_dir = current_home_dir.lstrip("/")
813 home_dir = subaccount["homedirectory"].lstrip("/")
814 if current_home_dir != home_dir:
815 if not check_mode:
816 update_subaccount_home_directory(module, storagebox_id, existing, home_dir)
817 homedir_updated = True
818
819 update, access_settings = get_subaccount_updates(existing, subaccount)
820 if update:
821 if not check_mode:
822 update_subaccount(module, storagebox_id, existing, update)
823 updated = True
824 if access_settings:
825 if not check_mode:
826 update_access_settings(module, storagebox_id, existing, access_settings)
827 updated = True
828 else: # state 'present' without pre-existing account
829 if not subaccount["homedirectory"]:
830 module.fail_json(msg="homedirectory is required when creating a new subaccount")
831 if not subaccount["password"]:
832 module.fail_json(msg="password is required when creating a new subaccount")
833
834 del subaccount["username"] # username cannot be choosen
835 if not check_mode:
836 new_subaccount_id = create_subaccount(module, storagebox_id, subaccount)
837 # Retrieve created subaccount
838 # (not necessary, allows us to get additional infos (created time etc...))
839 url = "{0}/v1/storage_boxes/{1}/subaccounts/{2}".format(API_BASE_URL, storagebox_id, new_subaccount_id)
840 existing = api_fetch_url_json(module, url, method='GET')[0]["subaccount"]
841 created = True
842
843 return_data = merge_subaccounts_infos(existing or {}, subaccount)
844
845 module.exit_json(
846 changed=any([created, deleted, updated, password_updated, homedir_updated]),
847 created=created,
848 deleted=deleted,
849 updated=updated or homedir_updated,
850 password_updated=password_updated,
851 subaccount=adjust_legacy(return_data) if state != "absent" else None,
852 )
853
854
855 if __name__ == "__main__": # pragma: no cover
856 main() # pragma: no cover