Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright: (c) 2019, 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: server
12
13 short_description: Create and manage cloud servers on the Hetzner Cloud.
14
15
16 description:
17 - Create, update and manage cloud servers on the Hetzner Cloud.
18 - To manage the DNS pointer of a Server, use the M(hetzner.hcloud.rdns) module.
19
20 author:
21 - Lukas Kaemmerling (@LKaemmerling)
22
23 options:
24 id:
25 description:
26 - ID of the Hetzner Cloud Server to manage.
27 - Only required if no server O(name) is given
28 type: int
29 name:
30 description:
31 - Name of the Hetzner Cloud Server to manage.
32 - Only required if no server O(id) is given or a server does not exist.
33 type: str
34 server_type:
35 description:
36 - Hetzner Cloud Server Type (name or ID) of the server.
37 - Required if server does not exist.
38 type: str
39 ssh_keys:
40 description:
41 - List of Hetzner Cloud SSH Keys (name or ID) to create the server with.
42 - Only used during the server creation.
43 type: list
44 elements: str
45 volumes:
46 description:
47 - List of Hetzner Cloud Volumes (name or ID) that should be attached to the server.
48 - Only used during the server creation.
49 type: list
50 elements: str
51 firewalls:
52 description:
53 - List of Hetzner Cloud Firewalls (name or ID) that should be attached to the server.
54 type: list
55 elements: str
56 image:
57 description:
58 - Hetzner Cloud Image (name or ID) to create the server from.
59 - Required if server does not exist or when O(state=rebuild).
60 type: str
61 image_allow_deprecated:
62 description:
63 - Allows the creation of servers with deprecated images.
64 type: bool
65 default: false
66 aliases: [allow_deprecated_image]
67 location:
68 description:
69 - Hetzner Cloud Location (name or ID) to create the server in.
70 - Required if the server does not exist.
71 - Only used during the server creation.
72 type: str
73 datacenter:
74 description:
75 - B(Deprecated:) The O(datacenter) argument is deprecated and will be removed
76 after 1 July 2026. Please use the O(location) argument instead.
77 See https://docs.hetzner.cloud/changelog#2025-12-16-phasing-out-datacenters.
78 - Hetzner Cloud Datacenter (name or ID) to create the server in.
79 - Required if no O(location) is given and the server does not exist.
80 - Only used during the server creation.
81 type: str
82 backups:
83 description:
84 - Enable or disable Backups for the given Server.
85 type: bool
86 upgrade_disk:
87 description:
88 - Resize the disk size, when resizing a server.
89 - If you want to downgrade the server later, this value should be False.
90 type: bool
91 default: false
92 enable_ipv4:
93 description:
94 - Enables the public ipv4 address.
95 type: bool
96 default: true
97 enable_ipv6:
98 description:
99 - Enables the public ipv6 address.
100 type: bool
101 default: true
102 ipv4:
103 description:
104 - Hetzner Cloud Primary IPv4 (name or ID) to use.
105 - If omitted and O(enable_ipv4=true), a new ipv4 Primary IP will automatically be created.
106 type: str
107 ipv6:
108 description:
109 - Hetzner Cloud Primary IPv6 (name or ID) to use.
110 - If omitted and O(enable_ipv6=true), a new ipv6 Primary IP will automatically be created.
111 type: str
112 private_networks:
113 description:
114 - List of Hetzner Cloud Networks (name or ID) the server should be attached to.
115 - If None, private networks are left as they are (e.g. if previously added by hcloud_server_network),
116 if it has any other value (including []), only those networks are attached to the server.
117 type: list
118 elements: str
119 force:
120 description:
121 - Force the update of the server.
122 - May power off the server if update is applied.
123 type: bool
124 default: false
125 user_data:
126 description:
127 - User Data to be passed to the server on creation.
128 - C(cloud-init), C(ignition) or similar provisioning tools may retrieve user configuration from the Server's C(user_data).
129 - Used during the server creation or server rebuild.
130 type: str
131 rescue_mode:
132 description:
133 - Add the Hetzner rescue system type you want the server to be booted into.
134 type: str
135 labels:
136 description:
137 - User-defined labels (key-value pairs).
138 type: dict
139 delete_protection:
140 description:
141 - Protect the Server for deletion.
142 - Needs to be the same as O(rebuild_protection).
143 type: bool
144 rebuild_protection:
145 description:
146 - Protect the Server for rebuild.
147 - Needs to be the same as O(delete_protection).
148 type: bool
149 placement_group:
150 description:
151 - Hetzner Cloud Placement Group (name or ID) to create the server in.
152 type: str
153 state:
154 description:
155 - State of the server.
156 default: present
157 choices: [ absent, present, created, restarted, started, stopped, rebuild ]
158 type: str
159 extends_documentation_fragment:
160 - hetzner.hcloud.hcloud
161
162 """
163
164 EXAMPLES = """
165 - name: Create a basic server
166 hetzner.hcloud.server:
167 name: my-server
168 server_type: cpx22
169 image: ubuntu-22.04
170 state: present
171
172 - name: Create a basic server with ssh key
173 hetzner.hcloud.server:
174 name: my-server
175 server_type: cpx22
176 image: ubuntu-22.04
177 location: fsn1
178 ssh_keys:
179 - me@myorganisation
180 state: present
181
182 - name: Create a basic server with additional cloud-init data disabling SSH password authentication
183 hetzner.hcloud.server:
184 name: my-server
185 server_type: cpx22
186 image: ubuntu-22.04
187 user_data: |
188 #cloud-config
189 ssh_pwauth: false
190 state: present
191
192 - name: Resize an existing server
193 hetzner.hcloud.server:
194 name: my-server
195 server_type: cpx22
196 upgrade_disk: true
197 state: present
198
199 - name: Ensure the server is absent (remove if needed)
200 hetzner.hcloud.server:
201 name: my-server
202 state: absent
203
204 - name: Ensure the server is started
205 hetzner.hcloud.server:
206 name: my-server
207 state: started
208
209 - name: Ensure the server is stopped
210 hetzner.hcloud.server:
211 name: my-server
212 state: stopped
213
214 - name: Ensure the server is restarted
215 hetzner.hcloud.server:
216 name: my-server
217 state: restarted
218
219 - name: Ensure the server is will be booted in rescue mode and therefore restarted
220 hetzner.hcloud.server:
221 name: my-server
222 rescue_mode: linux64
223 state: restarted
224
225 - name: Ensure the server is rebuild
226 hetzner.hcloud.server:
227 name: my-server
228 image: ubuntu-22.04
229 state: rebuild
230
231 - name: Add server to placement group
232 hetzner.hcloud.server:
233 name: my-server
234 placement_group: my-placement-group
235 force: true
236 state: present
237
238 - name: Remove server from placement group
239 hetzner.hcloud.server:
240 name: my-server
241 placement_group:
242 state: present
243
244 - name: Add server with private network only
245 hetzner.hcloud.server:
246 name: my-server
247 enable_ipv4: false
248 enable_ipv6: false
249 private_networks:
250 - my-network
251 - 4711
252 state: present
253 """
254
255 RETURN = """
256 hcloud_server:
257 description: The server instance
258 returned: Always
259 type: dict
260 contains:
261 id:
262 description: Numeric identifier of the server
263 returned: always
264 type: int
265 sample: 1937415
266 name:
267 description: Name of the server
268 returned: always
269 type: str
270 sample: my-server
271 created:
272 description: Point in time when the Server was created (in ISO-8601 format)
273 returned: always
274 type: str
275 sample: "2023-11-06T13:36:56+00:00"
276 status:
277 description: Status of the server
278 returned: always
279 type: str
280 sample: running
281 server_type:
282 description: Name of the server type of the server
283 returned: always
284 type: str
285 sample: cpx22
286 ipv4_address:
287 description: Public IPv4 address of the server
288 returned: always
289 type: str
290 sample: 116.203.104.109
291 ipv6:
292 description: IPv6 network of the server
293 returned: always
294 type: str
295 sample: 2a01:4f8:1c1c:c140::/64
296 private_networks:
297 description: List of private networks the server is attached to (name or ID)
298 returned: always
299 type: list
300 elements: str
301 sample: ['my-network', 'another-network', '4711']
302 private_networks_info:
303 description: List of private networks the server is attached to (dict with name and ip)
304 returned: always
305 type: list
306 elements: dict
307 sample: [{'name': 'my-network', 'ip': '192.168.1.1'}, {'name': 'another-network', 'ip': '10.185.50.40'}]
308 location:
309 description: Name of the location of the server
310 returned: always
311 type: str
312 sample: fsn1
313 placement_group:
314 description: Placement Group of the server
315 type: str
316 returned: always
317 sample: 4711
318 version_added: "1.5.0"
319 datacenter:
320 description: |
321 Name of the datacenter of the server.
322
323 B(Deprecated:) The RV(hcloud_server.datacenter) value is deprecated and will be removed
324 after 1 July 2026. Please use the RV(hcloud_server.location) value instead.
325 See https://docs.hetzner.cloud/changelog#2025-12-16-phasing-out-datacenters.
326 returned: always
327 type: str
328 sample: fsn1-dc14
329 rescue_enabled:
330 description: True if rescue mode is enabled, Server will then boot into rescue system on next reboot
331 returned: always
332 type: bool
333 sample: false
334 backup_window:
335 description: Time window (UTC) in which the backup will run, or null if the backups are not enabled
336 returned: always
337 type: bool
338 sample: 22-02
339 labels:
340 description: User-defined labels (key-value pairs)
341 returned: always
342 type: dict
343 delete_protection:
344 description: True if server is protected for deletion
345 type: bool
346 returned: always
347 sample: false
348 version_added: "0.1.0"
349 rebuild_protection:
350 description: True if server is protected for rebuild
351 type: bool
352 returned: always
353 sample: false
354 version_added: "0.1.0"
355 root_password:
356 description: Root password for the server
357 returned: when created without ssh_keys
358 type: str
359 sample: YItygq1v3GYjjMomLaKc
360 """
361
362 from datetime import timedelta
363 from typing import TYPE_CHECKING, Literal
364
365 from ansible.module_utils.basic import AnsibleModule
366
367 from ..module_utils._base import AnsibleHCloud
368 from ..module_utils._deprecation import deprecated_server_type_warning
369 from ..module_utils._vendor.hcloud import HCloudException
370 from ..module_utils._vendor.hcloud.firewalls import FirewallResource
371 from ..module_utils._vendor.hcloud.servers import (
372 BoundServer,
373 Server,
374 ServerCreatePublicNetwork,
375 )
376
377 if TYPE_CHECKING:
378 from ..module_utils._vendor.hcloud.actions import BoundAction
379 from ..module_utils._vendor.hcloud.firewalls import BoundFirewall
380 from ..module_utils._vendor.hcloud.networks import BoundNetwork
381 from ..module_utils._vendor.hcloud.placement_groups import BoundPlacementGroup
382 from ..module_utils._vendor.hcloud.primary_ips import PrimaryIP
383 from ..module_utils._vendor.hcloud.server_types import ServerType
384
385
386 class AnsibleHCloudServer(AnsibleHCloud):
387 represent = "hcloud_server"
388
389 hcloud_server: BoundServer | None = None
390
391 def _prepare_result(self):
392 return {
393 "id": self.hcloud_server.id,
394 "name": self.hcloud_server.name,
395 "created": self.hcloud_server.created.isoformat(),
396 "ipv4_address": (
397 self.hcloud_server.public_net.ipv4.ip if self.hcloud_server.public_net.ipv4 is not None else None
398 ),
399 "ipv6": self.hcloud_server.public_net.ipv6.ip if self.hcloud_server.public_net.ipv6 is not None else None,
400 "private_networks": [net.network.name for net in self.hcloud_server.private_net],
401 "private_networks_info": [
402 {"name": net.network.name, "ip": net.ip} for net in self.hcloud_server.private_net
403 ],
404 "image": self.hcloud_server.image.name if self.hcloud_server.image is not None else None,
405 "server_type": self.hcloud_server.server_type.name,
406 "datacenter": self.hcloud_server.datacenter and self.hcloud_server.datacenter.name,
407 "location": self.hcloud_server.location.name,
408 "placement_group": (
409 self.hcloud_server.placement_group.name if self.hcloud_server.placement_group is not None else None
410 ),
411 "rescue_enabled": self.hcloud_server.rescue_enabled,
412 "backup_window": self.hcloud_server.backup_window,
413 "labels": self.hcloud_server.labels,
414 "delete_protection": self.hcloud_server.protection["delete"],
415 "rebuild_protection": self.hcloud_server.protection["rebuild"],
416 "status": self.hcloud_server.status,
417 }
418
419 def _get_server(self):
420 try:
421 if self.module.params.get("id") is not None:
422 self.hcloud_server = self.client.servers.get_by_id(self.module.params.get("id"))
423 else:
424 self.hcloud_server = self.client.servers.get_by_name(self.module.params.get("name"))
425 except HCloudException as exception:
426 self.fail_json_hcloud(exception)
427
428 def _create_server(self):
429 self.module.fail_on_missing_params(required_params=["name", "server_type", "image"])
430
431 server_type = self._client_get_by_name_or_id("server_types", self.module.params.get("server_type"))
432 image = self._get_image(server_type)
433
434 params = {
435 "name": self.module.params.get("name"),
436 "labels": self.module.params.get("labels"),
437 "server_type": server_type,
438 "image": image,
439 "user_data": self.module.params.get("user_data"),
440 "public_net": ServerCreatePublicNetwork(
441 enable_ipv4=self.module.params.get("enable_ipv4"),
442 enable_ipv6=self.module.params.get("enable_ipv6"),
443 ),
444 }
445
446 if self.module.params.get("placement_group") is not None:
447 params["placement_group"] = self._client_get_by_name_or_id(
448 "placement_groups", self.module.params.get("placement_group")
449 )
450
451 if self.module.params.get("ipv4") is not None:
452 params["public_net"].ipv4 = self._client_get_by_name_or_id("primary_ips", self.module.params.get("ipv4"))
453
454 if self.module.params.get("ipv6") is not None:
455 params["public_net"].ipv6 = self._client_get_by_name_or_id("primary_ips", self.module.params.get("ipv6"))
456
457 if self.module.params.get("private_networks") is not None:
458 params["networks"] = [
459 self._client_get_by_name_or_id("networks", name_or_id)
460 for name_or_id in self.module.params.get("private_networks")
461 ]
462
463 if self.module.params.get("ssh_keys") is not None:
464 params["ssh_keys"] = [
465 self._client_get_by_name_or_id("ssh_keys", name_or_id)
466 for name_or_id in self.module.params.get("ssh_keys")
467 ]
468
469 if self.module.params.get("volumes") is not None:
470 params["volumes"] = [
471 self._client_get_by_name_or_id("volumes", name_or_id)
472 for name_or_id in self.module.params.get("volumes")
473 ]
474
475 if self.module.params.get("firewalls") is not None:
476 params["firewalls"] = [
477 self._client_get_by_name_or_id("firewalls", name_or_id)
478 for name_or_id in self.module.params.get("firewalls")
479 ]
480
481 server_type_location = None
482
483 if self.module.params.get("location") is None and self.module.params.get("datacenter") is None:
484 # When not given, the API will choose the location.
485 params["location"] = None
486 params["datacenter"] = None
487 elif self.module.params.get("location") is not None and self.module.params.get("datacenter") is None:
488 params["location"] = self._client_get_by_name_or_id("locations", self.module.params.get("location"))
489 server_type_location = params["location"]
490 elif self.module.params.get("location") is None and self.module.params.get("datacenter") is not None:
491 self.module.warn(
492 "The `datacenter` argument is deprecated and will be removed "
493 "after 1 July 2026. Please use the `location` argument instead. "
494 "See https://docs.hetzner.cloud/changelog#2025-12-16-phasing-out-datacenters."
495 )
496 value: str = self.module.params.get("datacenter")
497 # Backward compatible datacenter argument.
498 # datacenter hel1-dc2 => location hel1
499 if value and not value.isdigit():
500 # pylint: disable=disallowed-name
501 part1, _, _ = value.partition("-")
502 params["location"] = self.client.locations.get_by_name(part1)
503 server_type_location = params["location"]
504 else:
505 params["datacenter"] = self._client_get_by_name_or_id("datacenters", value)
506 server_type_location = params["datacenter"].location
507
508 if self.module.params.get("state") == "stopped" or self.module.params.get("state") == "created":
509 params["start_after_create"] = False
510
511 server_type_deprecation_printed = deprecated_server_type_warning(
512 self.module,
513 server_type,
514 server_type_location,
515 )
516
517 if not self.module.check_mode:
518 try:
519 resp = self.client.servers.create(**params)
520
521 if not server_type_deprecation_printed:
522 deprecated_server_type_warning(
523 self.module,
524 resp.server.server_type,
525 resp.server.location,
526 )
527
528 self.result["root_password"] = resp.root_password
529 # Action should take 60 to 90 seconds on average, but can be >10m when creating a
530 # server from a custom images
531 resp.action.wait_until_finished(max_retries=362) # 362 retries >= 1802 seconds
532 for action in resp.next_actions:
533 # Starting the server or attaching to the network might take a few minutes,
534 # depending on the current activity in the project.
535 # This waits up to 30minutes for each action in series, but in the background
536 # the actions are mostly running in parallel, so after the first one the other
537 # actions are usually completed already.
538 action.wait_until_finished(max_retries=362) # 362 retries >= 1802 seconds
539
540 rescue_mode = self.module.params.get("rescue_mode")
541 if rescue_mode:
542 self._get_server()
543 self._set_rescue_mode(rescue_mode)
544
545 backups = self.module.params.get("backups")
546 if backups:
547 self._get_server()
548 action = self.hcloud_server.enable_backup()
549 action.wait_until_finished()
550
551 delete_protection = self.module.params.get("delete_protection")
552 rebuild_protection = self.module.params.get("rebuild_protection")
553 if delete_protection is not None and rebuild_protection is not None:
554 self._get_server()
555 action = self.hcloud_server.change_protection(
556 delete=delete_protection,
557 rebuild=rebuild_protection,
558 )
559 action.wait_until_finished()
560 except HCloudException as exception:
561 self.fail_json_hcloud(exception)
562 self._mark_as_changed()
563 self._get_server()
564
565 def _get_image(self, server_type: ServerType):
566 image = self.client.images.get_by_name_and_architecture(
567 name=self.module.params.get("image"),
568 architecture=server_type.architecture,
569 include_deprecated=True,
570 )
571 if image is None:
572 image = self.client.images.get_by_id(self.module.params.get("image"))
573
574 if image.deprecated is not None:
575 available_until = image.deprecated + timedelta(days=90)
576 if self.module.params.get("image_allow_deprecated"):
577 self.module.warn(
578 f"You try to use a deprecated image. The image {image.name} will "
579 f"continue to be available until {available_until.strftime('%Y-%m-%d')}."
580 )
581 else:
582 self.module.fail_json(
583 msg=(
584 f"You try to use a deprecated image. The image {image.name} will "
585 f"continue to be available until {available_until.strftime('%Y-%m-%d')}. "
586 "If you want to use this image use image_allow_deprecated=true."
587 )
588 )
589 return image
590
591 def _update_server(self) -> None:
592 try:
593 previous_server_status = self.hcloud_server.status
594
595 update_params = {}
596
597 name = self.module.params.get("name")
598 if name is not None and self.hcloud_server.name != name:
599 self.module.fail_on_missing_params(required_params=["id"])
600 update_params["name"] = name
601
602 labels = self.module.params.get("labels")
603 if labels is not None and labels != self.hcloud_server.labels:
604 update_params["labels"] = labels
605
606 if update_params:
607 if not self.module.check_mode:
608 self.hcloud_server.update(**update_params)
609 self._mark_as_changed()
610
611 rescue_mode = self.module.params.get("rescue_mode")
612 if rescue_mode and self.hcloud_server.rescue_enabled is False:
613 if not self.module.check_mode:
614 self._set_rescue_mode(rescue_mode)
615 self._mark_as_changed()
616 elif not rescue_mode and self.hcloud_server.rescue_enabled is True:
617 if not self.module.check_mode:
618 action = self.hcloud_server.disable_rescue()
619 action.wait_until_finished()
620 self._mark_as_changed()
621
622 backups = self.module.params.get("backups")
623 if backups and self.hcloud_server.backup_window is None:
624 if not self.module.check_mode:
625 action = self.hcloud_server.enable_backup()
626 action.wait_until_finished()
627 self._mark_as_changed()
628 elif backups is not None and not backups and self.hcloud_server.backup_window is not None:
629 if not self.module.check_mode:
630 action = self.hcloud_server.disable_backup()
631 action.wait_until_finished()
632 self._mark_as_changed()
633
634 if self.module.params.get("firewalls") is not None:
635 self._update_server_firewalls()
636
637 if self.module.params.get("placement_group") is not None:
638 self._update_server_placement_group()
639
640 if self.module.params.get("ipv4") is not None:
641 self._update_server_ip("ipv4")
642
643 if self.module.params.get("ipv6") is not None:
644 self._update_server_ip("ipv6")
645
646 if self.module.params.get("private_networks") is not None:
647 self._update_server_networks()
648
649 if self.module.params.get("server_type") is not None:
650 self._update_server_server_type()
651
652 if not self.module.check_mode and (
653 (self.module.params.get("state") == "present" and previous_server_status == Server.STATUS_RUNNING)
654 or self.module.params.get("state") == "started"
655 ):
656 self.start_server()
657
658 delete_protection = self.module.params.get("delete_protection")
659 rebuild_protection = self.module.params.get("rebuild_protection")
660 if (delete_protection is not None and rebuild_protection is not None) and (
661 delete_protection != self.hcloud_server.protection["delete"]
662 or rebuild_protection != self.hcloud_server.protection["rebuild"]
663 ):
664 if not self.module.check_mode:
665 action = self.hcloud_server.change_protection(
666 delete=delete_protection,
667 rebuild=rebuild_protection,
668 )
669 action.wait_until_finished()
670 self._mark_as_changed()
671 self._get_server()
672 except HCloudException as exception:
673 self.fail_json_hcloud(exception)
674
675 def _update_server_placement_group(self) -> None:
676 current: BoundPlacementGroup | None = self.hcloud_server.placement_group
677 wanted = self.module.params.get("placement_group")
678
679 # Return if nothing changed
680 if current is not None and current.has_id_or_name(wanted):
681 return
682
683 # Fetch resource if parameter is truthy
684 if wanted:
685 placement_group = self._client_get_by_name_or_id("placement_groups", wanted)
686
687 # Remove if current is defined
688 if current is not None:
689 if not self.module.check_mode:
690 action = self.hcloud_server.remove_from_placement_group()
691 action.wait_until_finished()
692 self._mark_as_changed()
693
694 # Return if parameter is falsy
695 if not wanted:
696 return
697
698 # Assign new
699 self.stop_server_if_forced()
700 if not self.module.check_mode:
701 action = self.hcloud_server.add_to_placement_group(placement_group)
702 action.wait_until_finished()
703 self._mark_as_changed()
704
705 def _update_server_server_type(self) -> None:
706 current: ServerType = self.hcloud_server.server_type
707 wanted = self.module.params.get("server_type")
708
709 # Return if nothing changed
710 if current.has_id_or_name(wanted):
711 # Check if we should warn for using an deprecated server type
712 deprecated_server_type_warning(
713 self.module,
714 self.hcloud_server.server_type,
715 self.hcloud_server.location,
716 )
717 return
718
719 server_type = self._client_get_by_name_or_id("server_types", wanted)
720
721 # Check if we should warn for updating to a deprecated server type
722 deprecated_server_type_warning(
723 self.module,
724 server_type,
725 self.hcloud_server.location,
726 )
727
728 self.stop_server_if_forced()
729
730 if not self.module.check_mode:
731 upgrade_disk = self.module.params.get("upgrade_disk")
732
733 action = self.hcloud_server.change_type(
734 server_type=server_type,
735 upgrade_disk=upgrade_disk,
736 )
737 # Upgrading a server takes 160 seconds on average, upgrading the disk should
738 # take more time
739 # 122 retries >= 602 seconds
740 # 38 retries >= 182 seconds
741 action.wait_until_finished(max_retries=122 if upgrade_disk else 38)
742 self._mark_as_changed()
743
744 def _update_server_ip(self, kind: Literal["ipv4", "ipv6"]) -> None:
745 current: PrimaryIP | None = getattr(self.hcloud_server.public_net, f"primary_{kind}")
746 wanted = self.module.params.get(kind)
747 enable = self.module.params.get(f"enable_{kind}")
748
749 # Return if nothing changed
750 if current is not None and current.has_id_or_name(wanted) and enable:
751 return
752
753 # Fetch resource if parameter is truthy
754 if wanted:
755 primary_ip = self._client_get_by_name_or_id("primary_ips", wanted)
756
757 # Remove if current is defined
758 if current is not None:
759 self.stop_server_if_forced()
760 if not self.module.check_mode:
761 action = self.client.primary_ips.unassign(current)
762 action.wait_until_finished()
763 self._mark_as_changed()
764
765 # Return if parameter is falsy or resource is disabled
766 if not wanted or not enable:
767 return
768
769 # Assign new
770 self.stop_server_if_forced()
771 if not self.module.check_mode:
772 action = self.client.primary_ips.assign(
773 primary_ip,
774 assignee_id=self.hcloud_server.id,
775 assignee_type="server",
776 )
777 action.wait_until_finished()
778 self._mark_as_changed()
779
780 def _update_server_networks(self) -> None:
781 current: list[BoundNetwork] = [item.network for item in self.hcloud_server.private_net]
782 wanted: list[BoundNetwork] = [
783 self._client_get_by_name_or_id("networks", name_or_id)
784 for name_or_id in self.module.params.get("private_networks")
785 ]
786
787 current_ids = {item.id for item in current}
788 wanted_ids = {item.id for item in wanted}
789
790 # Removing existing but not wanted networks
791 actions: list[BoundAction] = []
792 for current_network in current:
793 if current_network.id in wanted_ids:
794 continue
795
796 self._mark_as_changed()
797 if self.module.check_mode:
798 continue
799
800 actions.append(self.hcloud_server.detach_from_network(current_network))
801
802 for action in actions:
803 action.wait_until_finished()
804
805 # Adding wanted networks that doesn't exist yet
806 actions: list[BoundAction] = []
807 for wanted_network in wanted:
808 if wanted_network.id in current_ids:
809 continue
810
811 self._mark_as_changed()
812 if self.module.check_mode:
813 continue
814
815 actions.append(self.hcloud_server.attach_to_network(wanted_network))
816
817 for action in actions:
818 action.wait_until_finished()
819
820 def _update_server_firewalls(self) -> None:
821 current: list[BoundFirewall] = [item.firewall for item in self.hcloud_server.public_net.firewalls]
822 wanted: list[BoundFirewall] = [
823 self._client_get_by_name_or_id("firewalls", name_or_id)
824 for name_or_id in self.module.params.get("firewalls")
825 ]
826
827 current_ids = {item.id for item in current}
828 wanted_ids = {item.id for item in wanted}
829
830 # Removing existing but not wanted firewalls
831 actions: list[BoundAction] = []
832 for current_firewall in current:
833 if current_firewall.id in wanted_ids:
834 continue
835
836 self._mark_as_changed()
837 if self.module.check_mode:
838 continue
839
840 actions.extend(
841 self.client.firewalls.remove_from_resources(
842 current_firewall,
843 [FirewallResource(type="server", server=self.hcloud_server)],
844 )
845 )
846
847 for action in actions:
848 action.wait_until_finished()
849
850 # Adding wanted firewalls that doesn't exist yet
851 actions: list[BoundAction] = []
852 for wanted_firewall in wanted:
853 if wanted_firewall.id in current_ids:
854 continue
855
856 self._mark_as_changed()
857 if self.module.check_mode:
858 continue
859
860 actions.extend(
861 self.client.firewalls.apply_to_resources(
862 wanted_firewall,
863 [FirewallResource(type="server", server=self.hcloud_server)],
864 )
865 )
866
867 for action in actions:
868 action.wait_until_finished()
869
870 def _set_rescue_mode(self, rescue_mode):
871 if self.module.params.get("ssh_keys"):
872 resp = self.hcloud_server.enable_rescue(
873 type=rescue_mode,
874 ssh_keys=[
875 self.client.ssh_keys.get_by_name(ssh_key_name).id
876 for ssh_key_name in self.module.params.get("ssh_keys")
877 ],
878 )
879 else:
880 resp = self.hcloud_server.enable_rescue(type=rescue_mode)
881 resp.action.wait_until_finished()
882 self.result["root_password"] = resp.root_password
883
884 def start_server(self):
885 try:
886 if self.hcloud_server:
887 if self.hcloud_server.status != Server.STATUS_RUNNING:
888 if not self.module.check_mode:
889 action = self.client.servers.power_on(self.hcloud_server)
890 action.wait_until_finished()
891 self._mark_as_changed()
892 self._get_server()
893 except HCloudException as exception:
894 self.fail_json_hcloud(exception)
895
896 def stop_server(self):
897 try:
898 if self.hcloud_server:
899 if self.hcloud_server.status != Server.STATUS_OFF:
900 if not self.module.check_mode:
901 action = self.client.servers.power_off(self.hcloud_server)
902 action.wait_until_finished()
903 self._mark_as_changed()
904 self._get_server()
905 except HCloudException as exception:
906 self.fail_json_hcloud(exception)
907
908 def stop_server_if_forced(self):
909 previous_server_status = self.hcloud_server.status
910 if previous_server_status == Server.STATUS_RUNNING and not self.module.check_mode:
911 if self.module.params.get("force") or self.module.params.get("state") == "stopped":
912 self.stop_server() # Only stopped server can be upgraded
913 return previous_server_status
914
915 self.module.warn(
916 f"You can not upgrade a running instance {self.hcloud_server.name}. "
917 "You need to stop the instance or use force=true."
918 )
919
920 return None
921
922 def rebuild_server(self):
923 self._get_server()
924 if self.hcloud_server is None:
925 self._create_server()
926 else:
927 self._update_server()
928
929 # Only rebuild the server if it already existed.
930 self.module.fail_on_missing_params(required_params=["image"])
931 try:
932 if not self.module.check_mode:
933 params = {
934 "image": self._get_image(self.hcloud_server.server_type),
935 }
936 if (value := self.module.params.get("user_data")) is not None:
937 params["user_data"] = value
938
939 resp = self.client.servers.rebuild(self.hcloud_server, **params)
940 # When we rebuild the server progress takes some more time.
941 resp.action.wait_until_finished(max_retries=202) # 202 retries >= 1002 seconds
942 self._mark_as_changed()
943
944 self._get_server()
945 except HCloudException as exception:
946 self.fail_json_hcloud(exception)
947
948 def present_server(self):
949 self._get_server()
950 if self.hcloud_server is None:
951 self._create_server()
952 else:
953 self._update_server()
954
955 def delete_server(self):
956 try:
957 self._get_server()
958 if self.hcloud_server is not None:
959 if not self.module.check_mode:
960 action = self.client.servers.delete(self.hcloud_server)
961 action.wait_until_finished()
962 self._mark_as_changed()
963 self.hcloud_server = None
964 except HCloudException as exception:
965 self.fail_json_hcloud(exception)
966
967 @classmethod
968 def define_module(cls):
969 return AnsibleModule(
970 argument_spec=dict(
971 id={"type": "int"},
972 name={"type": "str"},
973 image={"type": "str"},
974 image_allow_deprecated={"type": "bool", "default": False, "aliases": ["allow_deprecated_image"]},
975 server_type={"type": "str"},
976 location={"type": "str"},
977 datacenter={
978 "type": "str",
979 "removed_at_date": "2026-07-01",
980 "removed_from_collection": "hetzner.hcloud",
981 },
982 user_data={"type": "str"},
983 ssh_keys={"type": "list", "elements": "str", "no_log": False},
984 volumes={"type": "list", "elements": "str"},
985 firewalls={"type": "list", "elements": "str"},
986 labels={"type": "dict"},
987 backups={"type": "bool"},
988 upgrade_disk={"type": "bool", "default": False},
989 enable_ipv4={"type": "bool", "default": True},
990 enable_ipv6={"type": "bool", "default": True},
991 ipv4={"type": "str"},
992 ipv6={"type": "str"},
993 private_networks={"type": "list", "elements": "str", "default": None},
994 force={"type": "bool", "default": False},
995 rescue_mode={"type": "str"},
996 delete_protection={"type": "bool"},
997 rebuild_protection={"type": "bool"},
998 placement_group={"type": "str"},
999 state={
1000 "choices": ["absent", "present", "created", "restarted", "started", "stopped", "rebuild"],
1001 "default": "present",
1002 },
1003 **super().base_module_arguments(),
1004 ),
1005 required_one_of=[["id", "name"]],
1006 mutually_exclusive=[["location", "datacenter"]],
1007 required_together=[["delete_protection", "rebuild_protection"]],
1008 supports_check_mode=True,
1009 )
1010
1011
1012 def main():
1013 module = AnsibleHCloudServer.define_module()
1014
1015 hcloud = AnsibleHCloudServer(module)
1016 state = module.params.get("state")
1017 if state == "absent":
1018 hcloud.delete_server()
1019 elif state == "present":
1020 hcloud.present_server()
1021 hcloud.start_server()
1022 elif state == "created":
1023 hcloud.present_server()
1024 elif state == "started":
1025 hcloud.present_server()
1026 hcloud.start_server()
1027 elif state == "stopped":
1028 hcloud.present_server()
1029 hcloud.stop_server()
1030 elif state == "restarted":
1031 hcloud.present_server()
1032 hcloud.stop_server()
1033 hcloud.start_server()
1034 elif state == "rebuild":
1035 hcloud.rebuild_server()
1036
1037 module.exit_json(**hcloud.get_result())
1038
1039
1040 if __name__ == "__main__":
1041 main()