Debian Codegraph @

ansible_collections/hetzner/hcloud/plugins/modules/storage_box.py

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2025, Hetzner Cloud GmbH <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6
7 from __future__ import annotations
8
9 DOCUMENTATION = """
10 ---
11 module: storage_box
12
13 short_description: Create and manage Storage Boxes in Hetzner.
14
15 description:
16 - Create, update and delete Storage Boxes in Hetzner.
17 - See the L(Storage Boxes API documentation,https://docs.hetzner.cloud/reference/hetzner#storage-boxes) for more details.
18
19 author:
20 - Jonas Lammler (@jooola)
21
22 options:
23 id:
24 description:
25 - ID of the Storage Box to manage.
26 - Required if no Storage Box O(name) is given.
27 - If the ID is invalid, the module will fail.
28 type: int
29 name:
30 description:
31 - Name of the Storage Box to manage.
32 - Required if no Storage Box O(id) is given.
33 - Required if the Storage Box does not exist.
34 type: str
35 storage_box_type:
36 description:
37 - Name or ID of the Storage Box Type for the Storage Box.
38 - Required if the Storage Box does not exist.
39 type: str
40 aliases: [type]
41 location:
42 description:
43 - Name or ID of the Location for the Storage Box.
44 - Required if the Storage Box does not exist.
45 type: str
46 password:
47 description:
48 - Password for the Storage Box.
49 - Required if the Storage Box does not exist.
50 type: str
51 labels:
52 description:
53 - User-defined labels (key-value pairs) for the Storage Box.
54 type: dict
55 ssh_keys:
56 description:
57 - SSH public keys in OpenSSH format to inject into the Storage Box.
58 type: list
59 elements: str
60 access_settings:
61 description:
62 - Access settings of the Storage Box.
63 type: dict
64 suboptions:
65 reachable_externally:
66 description:
67 - Whether access from outside the Hetzner network is allowed.
68 type: bool
69 default: false
70 samba_enabled:
71 description:
72 - Whether the Samba subsystem is enabled.
73 type: bool
74 default: false
75 ssh_enabled:
76 description:
77 - Whether the SSH subsystem is enabled.
78 type: bool
79 default: false
80 webdav_enabled:
81 description:
82 - Whether the WebDAV subsystem is enabled.
83 type: bool
84 default: false
85 zfs_enabled:
86 description:
87 - Whether the ZFS snapshot folder is visible.
88 type: bool
89 default: false
90 snapshot_plan:
91 description:
92 - Snapshot plan of the Storage Box.
93 - Use null to disabled the snapshot plan.
94 type: dict
95 suboptions:
96 max_snapshots:
97 description:
98 - Maximum amount of Snapshots that will be created by this Snapshot Plan.
99 - Older Snapshots will be deleted.
100 type: int
101 required: true
102 hour:
103 description:
104 - Hour when the Snapshot Plan is executed (UTC).
105 type: int
106 required: true
107 minute:
108 description:
109 - Minute when the Snapshot Plan is executed (UTC).
110 type: int
111 required: true
112 day_of_week:
113 description:
114 - Day of the week when the Snapshot Plan is executed.
115 - Starts at 1 for Monday til 7 for Sunday.
116 - Null means every day.
117 type: int
118 day_of_month:
119 description:
120 - Day of the month when the Snapshot Plan is executed.
121 - Null means every day.
122 type: int
123 delete_protection:
124 description:
125 - Protect the Storage Box from deletion.
126 type: bool
127 snapshot:
128 description:
129 - Snapshot ID or Name to rollback to.
130 - Only used when O(state=rollback_snapshot)
131 type: str
132 state:
133 description:
134 - State of the Storage Box.
135 - C(reset_password) and C(rollback_snapshot) are not idempotent.
136 default: present
137 choices: [absent, present, reset_password, rollback_snapshot]
138 type: str
139
140 extends_documentation_fragment:
141 - hetzner.hcloud.hcloud
142 """
143
144 EXAMPLES = """
145 - name: Create a Storage Box
146 hetzner.hcloud.storage_box:
147 name: my-storage-box
148 storage_box_type: bx11
149 location: fsn1
150 password: my-secret
151 labels:
152 env: prod
153 state: present
154
155 - name: Create a Storage Box with access settings
156 hetzner.hcloud.storage_box:
157 name: my-storage-box
158 storage_box_type: bx11
159 location: fsn1
160 password: my-secret
161 access_settings:
162 reachable_externally: true
163 ssh_enabled: true
164 samba_enabled: false
165 webdav_enabled: false
166 zfs_enabled: false
167 state: present
168
169 - name: Create a Storage Box with snapshot plan
170 hetzner.hcloud.storage_box:
171 name: my-storage-box
172 storage_box_type: bx11
173 location: fsn1
174 password: my-secret
175 snapshot_plan:
176 max_snapshots: 10
177 hour: 3
178 minute: 30
179 state: present
180
181 - name: Disable a Storage Box snapshot plan
182 hetzner.hcloud.storage_box:
183 name: my-storage-box
184 snapshot_plan: null
185 state: present
186
187 - name: Reset a Storage Box password
188 hetzner.hcloud.storage_box:
189 name: my-storage-box
190 password: my-secret
191 state: reset_password
192
193 - name: Rollback a Storage Box to a Snapshot
194 hetzner.hcloud.storage_box:
195 name: my-storage-box
196 snapshot: 2025-12-03T13-47-47
197 state: rollback_snapshot
198
199 - name: Delete a Storage Box
200 hetzner.hcloud.storage_box:
201 name: my-storage-box
202 state: absent
203 """
204
205 RETURN = """
206 hcloud_storage_box:
207 description: Details about the Storage Box.
208 returned: always
209 type: dict
210 contains:
211 id:
212 description: ID of the Storage Box.
213 returned: always
214 type: int
215 sample: 1937415
216 name:
217 description: Name of the Storage Box.
218 returned: always
219 type: str
220 sample: my-storage-box
221 storage_box_type:
222 description: Name of the Storage Box Type.
223 returned: always
224 type: str
225 sample: bx11
226 location:
227 description: Name of the Location of the Storage Box.
228 returned: always
229 type: str
230 sample: fsn1
231 labels:
232 description: User-defined labels (key-value pairs) of the Storage Box.
233 returned: always
234 type: dict
235 sample:
236 env: prod
237 delete_protection:
238 description: Protect the Storage Box from deletion.
239 returned: always
240 type: bool
241 sample: false
242 access_settings:
243 description: Access settings of the Storage Box.
244 returned: always
245 type: dict
246 contains:
247 reachable_externally:
248 description: Whether access from outside the Hetzner network is allowed.
249 returned: always
250 type: bool
251 sample: false
252 samba_enabled:
253 description: Whether the Samba subsystem is enabled.
254 returned: always
255 type: bool
256 sample: false
257 ssh_enabled:
258 description: Whether the SSH subsystem is enabled.
259 returned: always
260 type: bool
261 sample: true
262 webdav_enabled:
263 description: Whether the WebDAV subsystem is enabled.
264 returned: always
265 type: bool
266 sample: false
267 zfs_enabled:
268 description: Whether the ZFS snapshot folder is visible.
269 returned: always
270 type: bool
271 sample: false
272 snapshot_plan:
273 description: Snapshot plan of the Storage Box.
274 returned: when enabled
275 type: dict
276 contains:
277 max_snapshots:
278 description: Maximum amount of Snapshots that will be created by this Snapshot Plan.
279 returned: always
280 type: int
281 sample: 10
282 hour:
283 description: Hour when the Snapshot Plan is executed (UTC).
284 returned: always
285 type: int
286 sample: 3
287 minute:
288 description: Minute when the Snapshot Plan is executed (UTC).
289 returned: always
290 type: int
291 sample: 30
292 day_of_week:
293 description: Day of the week when the Snapshot Plan is executed. Null means every day.
294 returned: always
295 type: int
296 sample: 1
297 day_of_month:
298 description: Day of the month when the Snapshot Plan is executed. Null means every day.
299 returned: always
300 type: int
301 sample: 30
302 username:
303 description: User name of the Storage Box.
304 returned: always
305 type: str
306 sample: u505337
307 server:
308 description: FQDN of the Storage Box.
309 returned: always
310 type: str
311 sample: u505337.your-storagebox.de
312 system:
313 description: Host system of the Storage Box.
314 returned: always
315 type: str
316 sample: HEL1-BX136
317 status:
318 description: Status of the Storage Box.
319 returned: always
320 type: str
321 sample: active
322 stats:
323 description: Statistics of the Storage Box.
324 returned: always
325 type: dict
326 contains:
327 size:
328 description: Current disk usage in bytes.
329 returned: always
330 type: int
331 sample: 10485760
332 size_data:
333 description: Current disk usage for data in bytes.
334 returned: always
335 type: int
336 sample: 10485760
337 size_snapshots:
338 description: Current disk usage for snapshots in bytes.
339 returned: always
340 type: int
341 sample: 10485760
342 """
343
344 from ..module_utils import _storage_box
345 from ..module_utils._base import AnsibleHCloud, AnsibleModule
346 from ..module_utils._client import client_resource_not_found
347 from ..module_utils._vendor.hcloud import HCloudException
348 from ..module_utils._vendor.hcloud.locations import Location
349 from ..module_utils._vendor.hcloud.storage_box_types import StorageBoxType
350 from ..module_utils._vendor.hcloud.storage_boxes import (
351 BoundStorageBox,
352 StorageBoxAccessSettings,
353 StorageBoxSnapshot,
354 StorageBoxSnapshotPlan,
355 )
356
357
358 class AnsibleStorageBox(AnsibleHCloud):
359 represent = "storage_box"
360
361 storage_box: BoundStorageBox | None = None
362
363 def _prepare_result(self):
364 if self.storage_box is not None:
365 return _storage_box.prepare_result(self.storage_box)
366 return {}
367
368 def _fetch(self):
369 if self.module.params.get("id") is not None:
370 self.storage_box = self.client.storage_boxes.get_by_id(self.module.params.get("id"))
371 else:
372 self.storage_box = self.client.storage_boxes.get_by_name(self.module.params.get("name"))
373
374 def _create(self):
375 self.fail_on_invalid_params(
376 required=["name", "storage_box_type", "location", "password"],
377 )
378 params = {
379 "name": self.module.params.get("name"),
380 "storage_box_type": StorageBoxType(self.module.params.get("storage_box_type")),
381 "location": Location(self.module.params.get("location")),
382 "password": self.module.params.get("password"),
383 }
384
385 if (value := self.module.params.get("labels")) is not None:
386 params["labels"] = value
387
388 if (value := self.module.params.get("access_settings")) is not None:
389 params["access_settings"] = StorageBoxAccessSettings.from_dict(value)
390
391 if (value := self.module.params.get("ssh_keys")) is not None:
392 params["ssh_keys"] = value
393
394 if not self.module.check_mode:
395 resp = self.client.storage_boxes.create(**params)
396 self.storage_box = resp.storage_box
397 resp.action.wait_until_finished()
398
399 if (value := self.module.params.get("delete_protection")) is not None:
400 if not self.module.check_mode:
401 action = self.storage_box.change_protection(delete=value)
402 action.wait_until_finished()
403
404 if self.module.param_is_defined("snapshot_plan"):
405 if (value := self.module.params.get("snapshot_plan")) is not None:
406 if not self.module.check_mode:
407 action = self.storage_box.enable_snapshot_plan(StorageBoxSnapshotPlan.from_dict(value))
408 action.wait_until_finished()
409
410 if not self.module.check_mode:
411 self.storage_box.reload()
412
413 self._mark_as_changed()
414
415 def _update(self):
416 need_reload = False
417
418 if (value := self.module.params.get("storage_box_type")) is not None:
419 if not self.storage_box.storage_box_type.has_id_or_name(value):
420 if not self.module.check_mode:
421 action = self.storage_box.change_type(StorageBoxType(value))
422 action.wait_until_finished()
423 need_reload = True
424 self._mark_as_changed()
425
426 if (value := self.module.params.get("access_settings")) is not None:
427 access_settings = StorageBoxAccessSettings.from_dict(value)
428 if self.storage_box.access_settings.to_payload() != access_settings.to_payload():
429 if not self.module.check_mode:
430 action = self.storage_box.update_access_settings(access_settings)
431 action.wait_until_finished()
432 need_reload = True
433 self._mark_as_changed()
434
435 if (value := self.module.params.get("delete_protection")) is not None:
436 if self.storage_box.protection["delete"] != value:
437 if not self.module.check_mode:
438 action = self.storage_box.change_protection(delete=value)
439 action.wait_until_finished()
440 need_reload = True
441 self._mark_as_changed()
442
443 if self.module.param_is_defined("snapshot_plan"):
444 if (value := self.module.params.get("snapshot_plan")) is not None:
445 snapshot_plan = StorageBoxSnapshotPlan.from_dict(value)
446 if (
447 self.storage_box.snapshot_plan is None
448 or self.storage_box.snapshot_plan.to_payload() != snapshot_plan.to_payload()
449 ):
450 if not self.module.check_mode:
451 action = self.storage_box.enable_snapshot_plan(snapshot_plan)
452 action.wait_until_finished()
453 need_reload = True
454 self._mark_as_changed()
455 else:
456 if self.storage_box.snapshot_plan is not None:
457 if not self.module.check_mode:
458 action = self.storage_box.disable_snapshot_plan()
459 action.wait_until_finished()
460 need_reload = True
461 self._mark_as_changed()
462
463 params = {}
464 if (value := self.module.params.get("name")) is not None and value != self.storage_box.name:
465 self.fail_on_invalid_params(required=["id"])
466 params["name"] = value
467 self._mark_as_changed()
468
469 if (value := self.module.params.get("labels")) is not None and value != self.storage_box.labels:
470 params["labels"] = value
471 self._mark_as_changed()
472
473 # Update only if params holds changes or the data must be refreshed (actions
474 # were triggered)
475 if params or need_reload:
476 if not self.module.check_mode:
477 self.storage_box = self.storage_box.update(**params)
478
479 def _delete(self):
480 if not self.module.check_mode:
481 resp = self.storage_box.delete()
482 resp.action.wait_until_finished()
483
484 self.storage_box = None
485 self._mark_as_changed()
486
487 def present(self):
488 try:
489 self._fetch()
490 if self.storage_box is None:
491 self._create()
492 else:
493 self._update()
494
495 except HCloudException as exception:
496 self.fail_json_hcloud(exception)
497
498 def absent(self):
499 try:
500 self._fetch()
501 if self.storage_box is None:
502 return
503 self._delete()
504
505 except HCloudException as exception:
506 self.fail_json_hcloud(exception)
507
508 def reset_password(self):
509 self.fail_on_invalid_params(
510 required=["password"],
511 )
512 try:
513 self._fetch()
514 if self.storage_box is None:
515 raise client_resource_not_found(
516 "storage box",
517 self.module.params.get("id") or self.module.params.get("name"),
518 )
519 if not self.module.check_mode:
520 action = self.storage_box.reset_password(self.module.params.get("password"))
521 action.wait_until_finished()
522
523 self._mark_as_changed()
524
525 except HCloudException as exception:
526 self.fail_json_hcloud(exception)
527
528 def rollback_snapshot(self):
529 self.fail_on_invalid_params(
530 required=["snapshot"],
531 )
532 try:
533 self._fetch()
534 if self.storage_box is None:
535 raise client_resource_not_found(
536 "storage box",
537 self.module.params.get("id") or self.module.params.get("name"),
538 )
539
540 if not self.module.check_mode:
541 action = self.storage_box.rollback_snapshot(StorageBoxSnapshot(self.module.params.get("snapshot")))
542 action.wait_until_finished()
543
544 self._mark_as_changed()
545
546 except HCloudException as exception:
547 self.fail_json_hcloud(exception)
548
549 @classmethod
550 def define_module(cls):
551 return AnsibleModule(
552 argument_spec=dict(
553 id={"type": "int"},
554 name={"type": "str"},
555 storage_box_type={"type": "str", "aliases": ["type"]},
556 location={"type": "str"},
557 password={"type": "str", "no_log": True},
558 ssh_keys={"type": "list", "elements": "str", "no_log": False},
559 labels={"type": "dict"},
560 access_settings={
561 "type": "dict",
562 "options": dict(
563 reachable_externally={"type": "bool", "default": False},
564 samba_enabled={"type": "bool", "default": False},
565 ssh_enabled={"type": "bool", "default": False},
566 webdav_enabled={"type": "bool", "default": False},
567 zfs_enabled={"type": "bool", "default": False},
568 ),
569 },
570 snapshot_plan={
571 "type": "dict",
572 "options": dict(
573 max_snapshots={"type": "int", "required": True},
574 hour={"type": "int", "required": True},
575 minute={"type": "int", "required": True},
576 day_of_week={"type": "int"},
577 day_of_month={"type": "int"},
578 ),
579 },
580 delete_protection={"type": "bool"},
581 snapshot={"type": "str"},
582 state={
583 "choices": ["absent", "present", "reset_password", "rollback_snapshot"],
584 "default": "present",
585 },
586 **super().base_module_arguments(),
587 ),
588 required_one_of=[["id", "name"]],
589 supports_check_mode=True,
590 )
591
592
593 def main():
594 module = AnsibleStorageBox.define_module()
595 o = AnsibleStorageBox(module)
596
597 match module.params.get("state"):
598 case "reset_password":
599 o.reset_password()
600 case "rollback_snapshot":
601 o.rollback_snapshot()
602 case "absent":
603 o.absent()
604 case _:
605 o.present()
606
607 result = o.get_result()
608
609 # Legacy return value naming pattern
610 result["hcloud_storage_box"] = result.pop(o.represent)
611
612 module.exit_json(**result)
613
614
615 if __name__ == "__main__":
616 main()