### Install from Local Sources Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/installation.md Install the Hetzner Cloud Python library after downloading the source code. Run this command in the root directory of the cloned repository or extracted tarball. ```console pip install . ``` -------------------------------- ### Install Stable Release with Pip Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/installation.md Use this command to install the latest stable version of the Hetzner Cloud Python library. This is the recommended installation method. ```console pip install hcloud ``` -------------------------------- ### Create and List Servers with hcloud-python Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Example demonstrating how to create a server with specified type and image, and then list all existing servers. Ensure your API token is correctly provided. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType client = Client( token="{YOUR_API_TOKEN}", # Please paste your API token here application_name="my-app", application_version="v1.0.0", ) # Create a server named my-server response = client.servers.create( name="my-server", server_type=ServerType(name="cx23"), image=Image(name="ubuntu-22.04"), ) server = response.server print(f"{server.id=} {server.name=} {server.status=}") print(f"root password: {response.root_password}") # List your servers servers = client.servers.get_all() for server in servers: print(f"{server.id=} {server.name=} {server.status=}") ``` -------------------------------- ### Setup Development Environment with venv Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Steps to create and activate a virtual environment for development. This is a prerequisite for running development tasks. ```sh make venv source venv/bin/activate ``` -------------------------------- ### Install pre-commit Hooks Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Install pre-commit to automatically run checks before committing changes. This helps maintain code quality. ```sh pre-commit install ``` -------------------------------- ### Install with Conda Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/installation.md Install the Hetzner Cloud Python library using conda from the conda-forge channel. Note that this package is third-party and may not be up-to-date. ```console conda install -c conda-forge hcloud ``` -------------------------------- ### Create Private Network with Subnets and Routes Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates software-defined private networks, allowing the addition of cloud subnets and static routes. Includes an example of listing all networks. ```python from hcloud import Client from hcloud.networks.domain import NetworkSubnet, NetworkRoute client = Client(token="") # Create the network network = client.networks.create( name="internal-net", ip_range="10.0.0.0/16", labels={"env": "production"}, ) # Add a cloud subnet action = network.add_subnet( NetworkSubnet( type=NetworkSubnet.TYPE_CLOUD, ip_range="10.0.1.0/24", network_zone="eu-central", ) ) action.wait_until_finished() # Add a static route action = network.add_route( NetworkRoute(destination="10.100.0.0/24", gateway="10.0.1.1") ) action.wait_until_finished() # List all networks for net in client.networks.get_all(): print(f"{net.id} {net.name} {net.ip_range}") ``` -------------------------------- ### Clone Repository with Git Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/installation.md Clone the Hetzner Cloud Python repository from GitHub to install from source. This method is useful for developers who want the latest code. ```console git clone git://github.com/hetznercloud/hcloud-python ``` -------------------------------- ### Create Stateful Firewall Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a stateful firewall with inbound/outbound rules and applies it to servers or label selectors. The example shows rules for HTTP, HTTPS, and restricted SSH access. ```python from hcloud import Client from hcloud.firewalls.domain import FirewallRule, FirewallResource client = Client(token="") response = client.firewalls.create( name="web-fw", rules=[ FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, port="80", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow HTTP", ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, port="443", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow HTTPS", ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, port="22", source_ips=["203.0.113.0/24"], # restrict SSH to office IP range destination_ips=[], description="Allow SSH from office", ), ], labels={"env": "production"}, ) firewall = response.firewall ``` -------------------------------- ### Download Tarball Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/installation.md Download the source code as a tarball using curl. This is an alternative to cloning the repository for installing from source. ```console curl -OL https://github.com/hetznercloud/hcloud-python/tarball/main ``` -------------------------------- ### Raise Deprecation Warning Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Example of how to raise a DeprecationWarning when a deprecated function is called, guiding users to the new method. ```python warnings.warn( "The 'hcloud.images.client.ImagesClient.get_by_name' method is deprecated, please use the " "'hcloud.images.client.ImagesClient.get_by_name_and_architecture' method instead.", DeprecationWarning, stacklevel=2, ) ``` -------------------------------- ### Deprecate Module with notice Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Example of how to mark a module or function as deprecated in its docstring, including version and alternative usage. ```python """Get image by name .. deprecated:: 1.19 Use :func:`hcloud.images.client.ImagesClient.get_by_name_and_architecture` instead. """ ``` -------------------------------- ### Retrieve Server Metrics Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Fetches time-series metrics (CPU, disk I/O, network) for a server over a specified time window. Metrics are retrieved for the given types, start and end times, and resolution. ```python from datetime import datetime, timedelta, timezone from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType client = Client(token="") server = client.servers.get_by_name("web-01") end = datetime.now(timezone.utc) start = end - timedelta(hours=2) response = server.get_metrics( type=["cpu", "disk", "network"], # or a single string like "cpu" start=start, end=end, step=60, # resolution in seconds ) metrics = response.metrics print(f"Time series start: {metrics.start}") print(f"Time series end: {metrics.end}") print(f"Step: {metrics.step}") for ts_name, ts in metrics.time_series.items(): print(f" {ts_name}: {len(ts.values)} data points") ``` -------------------------------- ### Build Documentation with make docs Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Command to build the project's documentation and open it in a web browser. ```sh make docs ``` -------------------------------- ### Client Initialization Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Initialize the Hetzner Cloud client with your API token and optional configuration. All resource clients are then available as attributes of the client object. ```APIDOC ## Client initialization `Client` is the entry point. It accepts an API token and optional metadata, timeout, and polling configuration. All sub-clients are available as attributes. ```python import os from hcloud import Client, exponential_backoff_function client = Client( token=os.environ["HCLOUD_TOKEN"], application_name="my-app", # included in User-Agent header application_version="1.0.0", poll_interval=exponential_backoff_function(base=0.25, multiplier=2, cap=5.0, jitter=True), poll_max_retries=240, # max polling attempts before ActionTimeoutException timeout=30.0, # requests timeout in seconds ) # All resource clients are available as attributes: # client.servers, client.volumes, client.networks, client.firewalls, # client.load_balancers, client.ssh_keys, client.floating_ips, # client.primary_ips, client.images, client.isos, client.certificates, # client.placement_groups, client.datacenters, client.locations, # client.server_types, client.load_balancer_types, client.storage_boxes, # client.storage_box_types, client.zones, client.actions ``` ``` -------------------------------- ### Create a Hetzner Cloud Server Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a new cloud server with specified parameters including name, server type, image, location, SSH keys, networks, user data, labels, and network configuration. Returns a `CreateServerResponse` containing the server details, root password, and pending actions. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType from hcloud.locations import Location from hcloud.ssh_keys import SSHKey from hcloud.networks import Network from hcloud.servers.domain import ServerCreatePublicNetwork client = Client(token="") response = client.servers.create( name="web-01", server_type=ServerType(name="cx23"), image=Image(name="ubuntu-24.04"), location=Location(name="fsn1"), ssh_keys=[SSHKey(name="my-laptop")], networks=[Network(id=123456)], user_data="#cloud-config\npackages:\n - nginx\n", labels={"env": "production", "role": "web"}, start_after_create=True, public_net=ServerCreatePublicNetwork(enable_ipv4=True, enable_ipv6=False), ) server = response.server print(f"Created server id={server.id} name={server.name} status={server.status}") print(f"IPv4: {server.public_net.ipv4.ip}") print(f"Root password: {response.root_password}") # Wait for all setup actions to finish for action in response.next_actions: action.wait_until_finished() ``` -------------------------------- ### Create Server Image (Snapshot/Backup) Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a disk image from a running or stopped server. This can be used for backups or creating new servers. Specify the description, type ('snapshot' or 'backup'), and optional labels. ```python from hcloud import Client client = Client(token="") server = client.servers.get_by_name("web-01") response = server.create_image( description="pre-upgrade snapshot", type="snapshot", # "snapshot" or "backup" labels={"trigger": "manual", "env": "prod"}, ) response.action.wait_until_finished() image = response.image print(f"Snapshot created: id={image.id} description={image.description}") ``` -------------------------------- ### client.storage_boxes.create Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a Hetzner Storage Box, a network-attached storage product accessible via SMB, SSH, and WebDAV. ```APIDOC ## client.storage_boxes.create — Managed storage boxes Creates a Hetzner Storage Box — a network-attached storage product accessible via SMB, SSH, and WebDAV. ```python from hcloud import Client from hcloud.locations import Location from hcloud.storage_box_types import StorageBoxType from hcloud.storage_boxes.domain import StorageBoxAccessSettings from hcloud.ssh_keys import SSHKey client = Client(token="") response = client.storage_boxes.create( name="backup-box", location=Location(name="fsn1"), storage_box_type=StorageBoxType(name="bx11"), labels={"purpose": "backups"}, password="s3cur3-p@ss", access_settings=StorageBoxAccessSettings( reachable_externally=True, samba_enabled=False, ssh_enabled=True, webdav_enabled=False, zfs_enabled=False, ), ssh_keys=[SSHKey(name="my-laptop")], ) response.action.wait_until_finished() box = response.storage_box print(f"Storage box: id={box.id} hostname={box.server}") ``` ``` -------------------------------- ### Rebuild a server (`server.rebuild`) Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Reinstalls a server's operating system from a specified image. This action will destroy all existing data on the server. Optional user data can be provided for initial configuration. ```APIDOC ## `server.rebuild` — Rebuild a server from an image Reinstalls a server's OS by overwriting its disk with the chosen image. All data is destroyed. ```python from hcloud import Client from hcloud.images import Image client = Client(token="") server = client.servers.get_by_name("web-01") user_data = """#cloud-config users: - name: deploy sudo: ALL=(ALL) NOPASSWD:ALL ssh_authorized_keys: - ssh-rsa AAAA... """ response = server.rebuild( image=Image(name="debian-12"), user_data=user_data, ) response.action.wait_until_finished() if response.root_password: print(f"New root password: {response.root_password}") ``` ``` -------------------------------- ### Create server image (`server.create_image`) Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a disk image from a server, which can be used for backups or creating new servers. The server can be running or stopped. Images can be of type 'snapshot' or 'backup'. ```APIDOC ## `server.create_image` — Create a snapshot or backup Creates a disk image from a running or stopped server. ```python from hcloud import Client client = Client(token="") server = client.servers.get_by_name("web-01") response = server.create_image( description="pre-upgrade snapshot", type="snapshot", # "snapshot" or "backup" labels={"trigger": "manual", "env": "prod"}, ) response.action.wait_until_finished() image = response.image print(f"Snapshot created: id={image.id} description={image.description}") ``` ``` -------------------------------- ### Rebuild Server from Image Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Reinstalls a server's OS by overwriting its disk with the chosen image, destroying all existing data. Optionally, user data can be provided for initial configuration. ```python from hcloud import Client from hcloud.images import Image client = Client(token="") server = client.servers.get_by_name("web-01") user_data = """#cloud-config users: - name: deploy sudo: ALL=(ALL) NOPASSWD:ALL ssh_authorized_keys: - ssh-rsa AAAA..." """ response = server.rebuild( image=Image(name="debian-12"), user_data=user_data, ) response.action.wait_until_finished() if response.root_password: print(f"New root password: {response.root_password}") ``` -------------------------------- ### Attach and Detach Server from Network Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Demonstrates how to attach a server to a private network with a specific IP and alias IPs, and how to detach it. Ensure the network and server exist and are in compatible locations. ```python action = server.attach_to_network( network=network, ip="10.0.0.10", alias_ips=["10.0.0.11"], ip_range="10.0.0.0/24", ) action.wait_until_finished() print("Server attached to private network") action = server.detach_from_network(network=network) action.wait_until_finished() ``` -------------------------------- ### Create Server Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a new cloud server with specified parameters and returns a response object containing the created server, root password, and pending actions. ```APIDOC ## `client.servers.create` — Create a server Creates a new cloud server and returns a `CreateServerResponse` with the `BoundServer`, root password, and pending actions. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType from hcloud.locations import Location from hcloud.ssh_keys import SSHKey from hcloud.networks import Network from hcloud.servers.domain import ServerCreatePublicNetwork client = Client(token="") response = client.servers.create( name="web-01", server_type=ServerType(name="cx23"), image=Image(name="ubuntu-24.04"), location=Location(name="fsn1"), ssh_keys=[SSHKey(name="my-laptop")], networks=[Network(id=123456)], user_data="#cloud-config\npackages:\n - nginx\n", labels={"env": "production", "role": "web"}, start_after_create=True, public_net=ServerCreatePublicNetwork(enable_ipv4=True, enable_ipv6=False), ) server = response.server print(f"Created server id={server.id} name={server.name} status={server.status}") print(f"IPv4: {server.public_net.ipv4.ip}") print(f"Root password: {response.root_password}") # Wait for all setup actions to finish for action in response.next_actions: action.wait_until_finished() ``` ``` -------------------------------- ### Run Development Tasks Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/index.md Common development tasks available via the Makefile, including building documentation, linting, and running tests. ```sh make docs ``` ```sh make lint ``` ```sh make test ``` -------------------------------- ### client.firewalls.create Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a stateful firewall with inbound and outbound rules and applies it to servers or label selectors. ```APIDOC ## `client.firewalls.create` — Stateful firewalls Creates a firewall with inbound/outbound rules and applies it to servers or label selectors. ### Create Firewall ```python response = client.firewalls.create( name="web-fw", rules=[ FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, port="80", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow HTTP", ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, port="443", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow HTTPS", ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, port="22", source_ips=["203.0.113.0/24"], # restrict SSH to office IP range destination_ips=[], description="Allow SSH from office", ), ], labels={"env": "production"}, ) firewall = response.firewall ``` ``` -------------------------------- ### Initialize Hetzner Cloud Client Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Initializes the `Client` object with an API token and optional configuration for application identification, polling, and request timeouts. All resource clients are accessible as attributes of this object. ```python import os from hcloud import Client, exponential_backoff_function client = Client( token=os.environ["HCLOUD_TOKEN"], application_name="my-app", # included in User-Agent header application_version="1.0.0", poll_interval=exponential_backoff_function(base=0.25, multiplier=2, cap=5.0, jitter=True), poll_max_retries=240, # max polling attempts before ActionTimeoutException timeout=30.0, # requests timeout in seconds ) # All resource clients are available as attributes: # client.servers, client.volumes, client.networks, client.firewalls, # client.load_balancers, client.ssh_keys, client.floating_ips, # client.primary_ips, client.images, client.isos, client.certificates, # client.placement_groups, client.datacenters, client.locations, # client.server_types, client.load_balancer_types, client.storage_boxes, # client.storage_box_types, client.zones, client.actions ``` -------------------------------- ### Use `include_architecture_wildcard` Argument Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/upgrading.md Replace the deprecated `include_wildcard_architecture` argument with `include_architecture_wildcard` in `Client.isos.get_list` and `Client.isos.get_all` methods. ```diff client.isos.get_all( - include_wildcard_architecture=True, + include_architecture_wildcard=True, ) ``` -------------------------------- ### Create a Storage Box Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a Hetzner Storage Box with specified name, location, type, labels, password, and access settings. Waits for the creation action to complete. ```python from hcloud import Client from hcloud.locations import Location from hcloud.storage_box_types import StorageBoxType from hcloud.storage_boxes.domain import StorageBoxAccessSettings from hcloud.ssh_keys import SSHKey client = Client(token="") response = client.storage_boxes.create( name="backup-box", location=Location(name="fsn1"), storage_box_type=StorageBoxType(name="bx11"), labels={"purpose": "backups"}, password="s3cur3-p@ss", access_settings=StorageBoxAccessSettings( reachable_externally=True, samba_enabled=False, ssh_enabled=True, webdav_enabled=False, zfs_enabled=False, ), ssh_keys=[SSHKey(name="my-laptop")], ) response.action.wait_until_finished() box = response.storage_box print(f"Storage box: id={box.id} hostname={box.server}") ``` -------------------------------- ### Resize a server (`server.change_type`) Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Migrates a server to a different server type (CPU/RAM/disk). Ensure the server is powered off before resizing for most operations. `upgrade_disk=False` allows for future downgrades. ```APIDOC ## `server.change_type` — Resize a server Migrates a server to a different server type (CPU/RAM/disk). Set `upgrade_disk=False` to allow future downgrade. ```python from hcloud import Client from hcloud.server_types import ServerType client = Client(token="") server = client.servers.get_by_name("web-01") # Power off first (required for most resize operations) server.shutdown().wait_until_finished() action = server.change_type( server_type=ServerType(name="cx33"), upgrade_disk=False, # False allows downgrading later ) action.wait_until_finished() server.power_on().wait_until_finished() print(f"Server now uses type: {server.server_type.name}") ``` ``` -------------------------------- ### client.placement_groups.create Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Ensures servers are spread across distinct physical hosts (type `spread`) for high availability. ```APIDOC ## `client.placement_groups.create` — Placement groups ### Description Ensures servers are spread across distinct physical hosts (type `spread`) for high availability. ### Method ```python client.placement_groups.create( name: str, type: str, # 'spread' or 'partition' labels: Optional[Dict[str, str]] = None, ) ``` ### Parameters * `name` (str) - The name of the placement group. * `type` (str) - The type of the placement group ('spread' or 'partition'). * `labels` (Optional[Dict[str, str]]) - Optional labels for the placement group. ### Request Example ```python from hcloud import Client client = Client(token="") pg = client.placement_groups.create( name="ha-cluster", type="spread", labels={"cluster": "production"}, ) print(f"Placement group created: id={pg.id} type={pg.type}") ``` ``` -------------------------------- ### Enable and Disable Rescue Mode Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Boots the server into the Hetzner Rescue System, which allows for system recovery or maintenance. Optional SSH keys can be injected for access. The server is typically reset to enter rescue mode. ```python from hcloud import Client client = Client(token="") server = client.servers.get_by_name("web-01") # Enable rescue mode (types: linux64, linux32, freebsd64) response = server.enable_rescue(type="linux64", ssh_keys=["my-laptop-key-id"]) response.action.wait_until_finished() print(f"Rescue root password: {response.root_password}") # Boot into rescue (reset is the quickest path) server.reset().wait_until_finished() # Disable rescue when done server.disable_rescue().wait_until_finished() ``` -------------------------------- ### Update `primary_ips.create` Datacenter Argument Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/upgrading.md The `datacenter` argument in `Client.primary_ips.create` is now optional and moved after the `name` argument. ```diff client.primary_ips.create( "ipv4", - None, "my-ip", assignee_id=12345, ) ``` ```diff client.primary_ips.create( "ipv4", - Datacenter(name="fsn1-dc14"), "my-ip", + datacenter=Datacenter(name="fsn1-dc14"), ) ``` -------------------------------- ### Stage, Commit, and Push Changes Source: https://github.com/hetznercloud/hcloud-python/blob/main/CONTRIBUTING.rst Stage all changes, commit them with a descriptive message, and push your branch to GitHub. ```bash git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Create Placement Group Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a placement group, which ensures servers are spread across distinct physical hosts for high availability. Supports different types like 'spread'. ```python from hcloud import Client client = Client(token="") pg = client.placement_groups.create( name="ha-cluster", type="spread", labels={"cluster": "production"}, ) print(f"Placement group created: id={pg.id} type={pg.type}") ``` -------------------------------- ### Add and Remove Server from Placement Group Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Assigns a server to a placement group to control its physical host distribution. Ensure the server and placement group exist. ```python from hcloud import Client from hcloud.placement_groups import PlacementGroup client = Client(token="") server = client.servers.get_by_name("app-01") pg = client.placement_groups.get_by_name("app-spread") action = server.add_to_placement_group(placement_group=pg) action.wait_until_finished() # Remove action = server.remove_from_placement_group() action.wait_until_finished() ``` -------------------------------- ### Apply Firewall to Servers Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Applies firewall rules to servers based on labels or to a specific server after creation. Ensures actions complete before proceeding. ```python for action in response.actions: action.wait_until_finished() server = client.servers.get_by_name("web-01") actions = firewall.apply_to_resources( [FirewallResource(type=FirewallResource.TYPE_SERVER, server=server)] ) for action in actions: action.wait_until_finished() ``` -------------------------------- ### List Placement Groups Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Iterates through all placement groups and prints their ID, name, and the number of associated servers. ```python for group in client.placement_groups.get_all(): print(f"{group.id} {group.name} servers={len(group.servers)}") ``` -------------------------------- ### client.zones.create Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates and manages DNS zones with resource record sets (RRSets). ```APIDOC ## client.zones.create — DNS zone management Creates and manages DNS zones with resource record sets (RRSets). ```python from hcloud import Client from hcloud.zones.domain import ZoneRRSet, ZoneRecord client = Client(token="") # Create a primary DNS zone response = client.zones.create( name="example.com", mode="primary", labels={"env": "production"}, rrsets=[ ZoneRRSet( name="@", type="A", ttl=300, records=[ZoneRecord(value="203.0.113.10", comment="web server")], ), ZoneRRSet( name="www", type="CNAME", ttl=300, records=[ZoneRecord(value="example.com.")], ), ZoneRRSet( name="@", type="MX", ttl=3600, records=[ZoneRecord(value="10 mail.example.com.")], ), ], ) response.action.wait_until_finished() zone = response.zone print(f"Zone created: id={zone.id} name={zone.name}") # Add a new RRSet rrset_response = zone.create_rrset( ZoneRRSet(name="api", type="A", ttl=60, records=[ZoneRecord(value="203.0.113.20")]) ) rset_response.action.wait_until_finished() # Export as BIND zone file export = zone.export_zonefile() print(export.zonefile) ``` ``` -------------------------------- ### Run Tests with make test Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Command to execute the project's tests using the current Python 3 version. ```sh make test ``` -------------------------------- ### client.floating_ips.create / assign / unassign Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates tenant-owned IP addresses that can be moved between servers. ```APIDOC ## `client.floating_ips.create` / `assign` / `unassign` — Floating IPs ### Description Creates tenant-owned IP addresses that can be moved between servers. ### Create Method ```python client.floating_ips.create( type: str, # 'ipv4' or 'ipv6' home_location: Location, description: Optional[str] = None, labels: Optional[Dict[str, str]] = None, ) ``` ### Create Parameters * `type` (str) - The type of the floating IP ('ipv4' or 'ipv6'). * `home_location` (Location) - The location where the floating IP is created. * `description` (Optional[str]) - An optional description for the floating IP. * `labels` (Optional[Dict[str, str]]) - Optional labels for the floating IP. ### Assign Method ```python floating_ip.assign(server: Server).wait_until_finished() ``` ### Assign Parameters * `server` (Server) - The server to assign the floating IP to. ### Unassign Method ```python floating_ip.unassign().wait_until_finished() ``` ### Request Example (Create and Assign) ```python from hcloud import Client from hcloud.locations import Location client = Client(token="") server = client.servers.get_by_name("web-01") response = client.floating_ips.create( type="ipv4", home_location=Location(name="fsn1"), description="web traffic IP", labels={"purpose": "web"}, ) floating_ip = response.floating_ip floating_ip.assign(server=server).wait_until_finished() print(f"Floating IP {floating_ip.ip} assigned to {server.name}") floating_ip.change_dns_ptr( ip=floating_ip.ip, dns_ptr="www.example.com" ).wait_until_finished() floating_ip.unassign().wait_until_finished() ``` ``` -------------------------------- ### List and Wait for Actions Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Retrieves all running actions, printing their ID, command, and progress. It also demonstrates waiting for a specific action to finish with a custom retry limit, handling potential failures or timeouts. ```python from hcloud import Client from hcloud.actions.domain import ActionStatus, ActionFailedException, ActionTimeoutException from hcloud.actions.client import ActionSort client = Client(token="") # List all running actions actions = client.actions.get_all( status=[ActionStatus.RUNNING], sort=["started:desc"], ) for action in actions: print(f"Action {action.id}: {action.command} progress={action.progress}%") # Wait for a specific action with a custom retry limit action = client.actions.get_by_id(112233) try: action.wait_until_finished(max_retries=60) print(f"Action finished: {action.status}") except ActionFailedException as e: print(f"Action failed: {e}") print(f"Error: {e.action.error}") except ActionTimeoutException: print("Action did not finish in time") ``` -------------------------------- ### Server Network Operations Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Demonstrates how to attach a server to a private network with a specific IP and alias IPs, and how to detach it. ```APIDOC ## Server Network Operations ### Attach to Network Attaches a server to a private network with a specified IP address and optional alias IPs. ```python action = server.attach_to_network( network=network, ip="10.0.0.10", alias_ips=["10.0.0.11"], ip_range="10.0.0.0/24", ) action.wait_until_finished() ``` ### Detach from Network Detaches a server from a private network. ```python action = server.detach_from_network(network=network) action.wait_until_finished() ``` ``` -------------------------------- ### Rescue Mode (`server.enable_rescue` / `disable_rescue`) Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Enables or disables rescue mode for a server, allowing it to boot into the Hetzner Rescue System. Optional SSH keys can be injected for access. The server may need to be reset to enter rescue mode. ```APIDOC ## `server.enable_rescue` / `disable_rescue` — Rescue mode Boots the server into the Hetzner Rescue System, injecting optional SSH keys. ```python from hcloud import Client client = Client(token="") server = client.servers.get_by_name("web-01") # Enable rescue mode (types: linux64, linux32, freebsd64) response = server.enable_rescue(type="linux64", ssh_keys=["my-laptop-key-id"]) response.action.wait_until_finished() print(f"Rescue root password: {response.root_password}") # Boot into rescue (reset is the quickest path) server.reset().wait_until_finished() # Disable rescue when done server.disable_rescue().wait_until_finished() ``` ``` -------------------------------- ### server.request_console Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Obtains a one-time WebSocket URL for browser-based KVM console access to a server. ```APIDOC ## `server.request_console` — VNC web console Obtains a one-time WebSocket URL for browser-based KVM console access. ```python response = server.request_console() response.action.wait_until_finished() print(f"Console URL: {response.wss_url}") print(f"VNC password: {response.password}") ``` ``` -------------------------------- ### API Clients Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/api.md The SDK provides dedicated clients for managing various Hetzner Cloud resources. Each client offers methods to interact with specific services. ```APIDOC ## API Clients The SDK provides dedicated clients for managing various Hetzner Cloud resources. Each client offers methods to interact with specific services. * [ActionsClient](api.clients.actions.md) * [CertificateClient](api.clients.certificates.md) * [DatacentersClient](api.clients.datacenters.md) * [FirewallsClient](api.clients.firewalls.md) * [Floating IPsClient](api.clients.floating_ips.md) * [ImagesClient](api.clients.images.md) * [ISOsClient](api.clients.isos.md) * [LoadBalancerTypesClient](api.clients.load_balancer_types.md) * [LoadBalancerClient](api.clients.load_balancers.md) * [LocationsClient](api.clients.locations.md) * [NetworksClient](api.clients.networks.md) * [PlacementGroupsClient](api.clients.placement_groups.md) * [PrimaryIPsClient](api.clients.primary_ips.md) * [ServerTypesClient](api.clients.server_types.md) * [ServersClient](api.clients.servers.md) * [SSHKeysClient](api.clients.ssh_keys.md) * [StorageBoxTypesClient](api.clients.storage_box_types.md) * [StorageBoxesClient](api.clients.storage_boxes.md) * [VolumesClient](api.clients.volumes.md) * [ZonesClient](api.clients.zones.md) ``` -------------------------------- ### client.load_balancers.create Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates a Layer 4/7 load balancer distributing traffic across server targets. ```APIDOC ## `client.load_balancers.create` — Managed load balancers ### Description Creates a Layer 4/7 load balancer distributing traffic across server targets. ### Method ```python client.load_balancers.create( name: str, load_balancer_type: LoadBalancerType, location: Location, algorithm: LoadBalancerAlgorithm, services: List[LoadBalancerService], targets: List[LoadBalancerTarget], labels: Optional[Dict[str, str]] = None, ) ``` ### Parameters * `name` (str) - The name of the load balancer. * `load_balancer_type` (LoadBalancerType) - The type of the load balancer. * `location` (Location) - The location of the load balancer. * `algorithm` (LoadBalancerAlgorithm) - The algorithm for traffic distribution. * `services` (List[LoadBalancerService]) - A list of services configured for the load balancer. * `targets` (List[LoadBalancerTarget]) - A list of targets for the load balancer. * `labels` (Optional[Dict[str, str]]) - Optional labels for the load balancer. ### Request Example ```python from hcloud import Client from hcloud.load_balancer_types import LoadBalancerType from hcloud.locations import Location from hcloud.load_balancers.domain import ( LoadBalancerAlgorithm, LoadBalancerService, LoadBalancerServiceHttp, LoadBalancerHealthCheck, LoadBalancerHealthCheckHttp, LoadBalancerTarget, LoadBalancerTargetLabelSelector ) client = Client(token="") response = client.load_balancers.create( name="web-lb", load_balancer_type=LoadBalancerType(name="lb11"), location=Location(name="fsn1"), algorithm=LoadBalancerAlgorithm(type=LoadBalancerAlgorithm.TYPE_ROUND_ROBIN), services=[ LoadBalancerService( protocol=LoadBalancerService.PROTOCOL_HTTP, listen_port=80, destination_port=8080, proxyprotocol=False, http=LoadBalancerServiceHttp( sticky_sessions=True, cookie_name="HCLB", ), health_check=LoadBalancerHealthCheck( protocol=LoadBalancerHealthCheck.PROTOCOL_HTTP, port=8080, interval=15, timeout=10, retries=3, http=LoadBalancerHealthCheckHttp(path="/health", status_codes=["2??", "3??"]), ), ) ], targets=[ LoadBalancerTarget( type=LoadBalancerTarget.TYPE_LABEL_SELECTOR, label_selector=LoadBalancerTargetLabelSelector(selector="role=web"), use_private_ip=True, ) ], labels={"env": "production"}, ) response.action.wait_until_finished() lb = response.load_balancer print(f"LB created: {lb.id} IPv4={lb.public_net.ipv4.ip}") ``` ``` -------------------------------- ### client.ssh_keys.create / get_all Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Manages SSH public keys that can be injected into servers at creation. ```APIDOC ## `client.ssh_keys.create` / `get_all` — SSH key management ### Description Manages SSH public keys that can be injected into servers at creation. ### Create Method ```python client.ssh_keys.create( name: str, public_key: str, labels: Optional[Dict[str, str]] = None, ) ``` ### Create Parameters * `name` (str) - The name of the SSH key. * `public_key` (str) - The public key content. * `labels` (Optional[Dict[str, str]]) - Optional labels for the SSH key. ### Get All Method ```python client.ssh_keys.get_all() ``` ### Get All Parameters None ### Request Example (Create) ```python from hcloud import Client client = Client(token="") with open("/home/user/.ssh/id_ed25519.pub") as f: pub_key = f.read().strip() ssh_key = client.ssh_keys.create( name="my-laptop", public_key=pub_key, labels={"owner": "alice"}, ) print(f"Fingerprint: {ssh_key.fingerprint}") ``` ### Request Example (List All) ```python from hcloud import Client client = Client(token="") keys = client.ssh_keys.get_all() for key in keys: print(f"{key.id} {key.name} {key.fingerprint}") ``` ``` -------------------------------- ### Handle `servers.rebuild` Response Structure Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/upgrading.md The `Client.servers.rebuild` method no longer returns a single action. It now returns a response object containing the action and an optional root password. ```diff -action = client.servers.rebuild(server, image) +resp = client.servers.rebuild(server, image) +action = resp.action +root_password = resp.root_password ``` -------------------------------- ### Enable/Disable Server Deletion and Rebuild Protection Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Use this to prevent accidental deletion or rebuild of a server. Call the function with `delete=True` and `rebuild=True` to enable protection, and `delete=False` and `rebuild=False` to disable it. ```python from hcloud import Client client = Client(token="") server = client.servers.get_by_name("db-primary") # Enable protection action = server.change_protection(delete=True, rebuild=True) action.wait_until_finished() print("Server is now protected from deletion and rebuild") # Remove protection action = server.change_protection(delete=False, rebuild=False) action.wait_until_finished() ``` -------------------------------- ### Clone the hcloud-python Repository Source: https://github.com/hetznercloud/hcloud-python/blob/main/CONTRIBUTING.rst Clone your forked repository locally to begin development. ```bash git clone git@github.com:your_name_here/hcloud-python.git ``` -------------------------------- ### Create and Manage SSH Keys Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Uploads an SSH public key, lists all keys, retrieves a key by fingerprint, and deletes a key. Requires reading the public key from a file. ```python from hcloud import Client client = Client(token="") # Create (upload public key) with open("/home/user/.ssh/id_ed25519.pub") as f: pub_key = f.read().strip() ssh_key = client.ssh_keys.create( name="my-laptop", public_key=pub_key, labels={"owner": "alice"}, ) print(f"Fingerprint: {ssh_key.fingerprint}") # List all keys keys = client.ssh_keys.get_all() for key in keys: print(f"{key.id} {key.name} {key.fingerprint}") # Find by fingerprint key = client.ssh_keys.get_by_fingerprint("SHA256:abc123...") # Delete ssh_key.delete() ``` -------------------------------- ### Commit and push changes Source: https://github.com/hetznercloud/hcloud-python/blob/main/docs/contributing.md Stage all changes, commit them with a descriptive message, and push the branch to GitHub. ```bash git add . $git commit -m "Your detailed description of your changes." $git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Resize Server Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Migrates a server to a different server type (CPU/RAM/disk). The server must be powered off before resizing. Set `upgrade_disk=False` to allow future downgrades. ```python from hcloud import Client from hcloud.server_types import ServerType client = Client(token="") server = client.servers.get_by_name("web-01") # Power off first (required for most resize operations) server.shutdown().wait_until_finished() action = server.change_type( server_type=ServerType(name="cx33"), upgrade_disk=False, # False allows downgrading later ) action.wait_until_finished() server.power_on().wait_until_finished() print(f"Server now uses type: {server.server_type.name}") ``` -------------------------------- ### Retrieve Hetzner Cloud Servers Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Fetches servers by ID, name, or retrieves all servers with optional filtering by status and labels. Supports paginated retrieval using `get_list`. ```python from hcloud import Client from hcloud.exceptions import APIException client = Client(token="") # By ID server = client.servers.get_by_id(123456) print(server.name, server.status, server.server_type.name) # By name (returns None if not found) server = client.servers.get_by_name("web-01") if server is None: print("Server not found") # All servers, filtered by status and label running_web = client.servers.get_all( label_selector="env=production,role=web", status=["running"], ) for s in running_web: print(f"{s.id} {s.name} {s.public_net.ipv4.ip}") # Paginated fetch page_result = client.servers.get_list(page=1, per_page=25, status=["running"]) servers, meta = page_result print(f"Page {meta.pagination.page} of {meta.pagination.last_page}") ``` -------------------------------- ### hcloud.exp.zone TXT record helpers Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Experimental utilities for formatting DNS TXT records according to RFC 1035, including auto-splitting long strings into 255-character chunks and escaping internal quotes. ```APIDOC ## hcloud.exp.zone — Experimental TXT record helpers ### Description Experimental utilities for formatting DNS TXT records according to RFC 1035 (255-character chunks). ### Usage ```python from hcloud.exp.zone import is_txt_record_quoted, format_txt_record raw = "v=spf1 include:_spf.google.com ~all" # Check if already quoted print(is_txt_record_quoted(raw)) # False print(is_txt_record_quoted('"v=spf1..."')) # True # Format for DNS zone file (auto-splits at 255 chars, escapes internal quotes) formatted = format_txt_record(raw) print(formatted) # "v=spf1 include:_spf.google.com ~all" long_value = "x" * 600 chunked = format_txt_record(long_value) print(chunked) # "xxx...255 chars..." "xxx...255 chars..." "xxx...90 chars..." ``` ``` -------------------------------- ### Run Tests with tox Source: https://github.com/hetznercloud/hcloud-python/blob/main/README.md Command to run tests across multiple Python 3 versions using tox. ```sh tox . ``` -------------------------------- ### Create a New Branch for Development Source: https://github.com/hetznercloud/hcloud-python/blob/main/CONTRIBUTING.rst Create a new branch for your bug fix or feature development. ```bash git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### client.networks.create / add_subnet / add_route Source: https://context7.com/hetznercloud/hcloud-python/llms.txt Creates and configures private networks with subnets and custom routes for inter-server communication. ```APIDOC ## `client.networks.create` / `add_subnet` / `add_route` — Private networks Creates software-defined private networks with subnets and custom routes. ### Create Network ```python network = client.networks.create( name="internal-net", ip_range="10.0.0.0/16", labels={"env": "production"}, ) ``` ### Add Cloud Subnet ```python action = network.add_subnet( NetworkSubnet( type=NetworkSubnet.TYPE_CLOUD, ip_range="10.0.1.0/24", network_zone="eu-central", ) ) action.wait_until_finished() ``` ### Add Static Route ```python action = network.add_route( NetworkRoute(destination="10.100.0.0/24", gateway="10.0.1.1") ) action.wait_until_finished() ``` ### List Networks ```python for net in client.networks.get_all(): print(f"{net.id} {net.name} {net.ip_range}") ``` ```