### Install and Use hcloud Python Library Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Demonstrates how to install the hcloud Python library using pip and provides a basic example of creating a server and listing all servers using the Hetzner Cloud API. ```shell pip install hcloud ``` ```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 # Create a server named my-server response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), 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 Virtual Environment for Development Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Instructions for setting up a Python virtual environment for developing the hcloud-python library. This includes creating and activating the environment. ```shell make venv source venv/bin/activate ``` -------------------------------- ### Setup Pre-commit Hooks for Development Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Guides on setting up pre-commit hooks to automatically run checks before committing changes in the hcloud-python development environment. ```shell pre-commit install ``` -------------------------------- ### Install Hetzner Cloud Python from Source (Git Clone) Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/installation.rst Installs the Hetzner Cloud Python SDK by first cloning the GitHub repository and then installing it locally using pip. This method allows for development or using the latest unreleased code. ```shell git clone git://github.com/hetznercloud/hcloud-python pip install . ``` -------------------------------- ### Install Hetzner Cloud Python from Source (Tarball) Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/installation.rst Installs the Hetzner Cloud Python SDK by downloading the source tarball from GitHub and then installing it locally using pip. This is an alternative method for installing from source. ```shell curl -OL https://github.com/hetznercloud/hcloud-python/tarball/main pip install . ``` -------------------------------- ### Create Hetzner Cloud Server with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Shows how to create a new Hetzner Cloud server using the Python SDK. Includes specifying server name, type, image, SSH keys, labels, and starting the server after creation. Demonstrates accessing server details and waiting for creation to complete. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType from hcloud.ssh_keys import SSHKey from hcloud.networks import Network client = Client(token="YOUR_API_TOKEN") # Create server with basic configuration response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), # 2 vCPU, 4 GB RAM image=Image(name="ubuntu-24.04"), ssh_keys=[SSHKey(name="my-key")], labels={"env": "production", "team": "backend"}, start_after_create=True ) # Access created server and metadata server = response.server root_password = response.root_password action = response.action next_actions = response.next_actions print(f"Server ID: {server.id}") print(f"Server Name: {server.name}") print(f"Status: {server.status}") print(f"Public IPv4: {server.public_net.ipv4.ip}") print(f"Root Password: {root_password}") # Wait for server to be ready action.wait_until_finished() print("Server is ready!") ``` -------------------------------- ### Install Hetzner Cloud Python via pip Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/installation.rst Installs the latest stable release of the Hetzner Cloud Python SDK using pip. This is the recommended installation method. Ensure you have pip installed. ```shell pip install hcloud ``` -------------------------------- ### Server Metrics: Get Performance Data (CPU, Disk, Network) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt This example demonstrates how to retrieve time-series performance metrics for a server, including CPU usage, disk I/O, and network traffic, within a specified time range. ```python from hcloud import Client from datetime import datetime, timedelta, timezone client = Client(token="YOUR_API_TOKEN") server = client.servers.get_by_name("my-server") # Get metrics for the last hour end = datetime.now(timezone.utc) start = end - timedelta(hours=1) response = server.get_metrics( type=["cpu", "disk", "network"], start=start, end=end, step=60 # Data points every 60 seconds ) metrics = response.metrics print("CPU Metrics:") for timestamp, value in zip(metrics.time_series["cpu"]["values"], metrics.time_series["cpu"]["timestamps"]): print(f" {timestamp}: {value}%") print("\nNetwork Traffic (bytes):") for timestamp, inbound, outbound in zip( metrics.time_series["network"]["timestamps"], metrics.time_series["network"]["values_in"], metrics.time_series["network"]["values_out"] ): print(f" {timestamp}: IN={inbound}, OUT={outbound}") ``` -------------------------------- ### Firewall Management: Create Rules and Apply to Server (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Guides on creating a firewall with specific inbound and outbound rules (TCP ports 80, 443, 22) and applying it to a server using hcloud-python. Requires API token and server name. ```python from hcloud import Client from hcloud.firewalls import ( Firewall, FirewallRule, FirewallResource ) client = Client(token="YOUR_API_TOKEN") # Create firewall with rules firewall = client.firewalls.create( name="web-firewall", labels={"service": "web"}, rules=[ FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, source_ips=["0.0.0.0/0", "::/0"], port="80", description="Allow HTTP" ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, source_ips=["0.0.0.0/0", "::/0"], port="443", description="Allow HTTPS" ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, source_ips=["203.0.113.0/24"], port="22", description="Allow SSH from office" ) ] ) print(f"Firewall created: {firewall.id}") # Apply firewall to server server = client.servers.get_by_name("my-server") actions = client.firewalls.apply_to_resources( firewall=firewall, resources=[ FirewallResource(type="server", server=server) ] ) for action in actions: action.wait_until_finished() print("Firewall applied to server") ``` -------------------------------- ### Manage Load Balancer Targets (Add/Remove Server, Label Selector, IP) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Demonstrates adding and removing various types of targets (server, label selector, IP) to an existing load balancer. Includes waiting for actions to complete and provides examples for different target configurations. ```python from hcloud import Client from hcloud.load_balancers import LoadBalancerTarget client = Client(token="YOUR_API_TOKEN") lb = client.load_balancers.get_by_name("web-lb") server = client.servers.get_by_name("my-server") # Add server target action = client.load_balancers.add_target( load_balancer=lb, target=LoadBalancerTarget( type="server", server=server, use_private_ip=False ) ) action.wait_until_finished() print("Server added as target") # Add label selector target (automatically includes matching servers) action = client.load_balancers.add_target( load_balancer=lb, target=LoadBalancerTarget( type="label_selector", label_selector="app=web,env=production", use_private_ip=True ) ) action.wait_until_finished() # Add IP target action = client.load_balancers.add_target( load_balancer=lb, target=LoadBalancerTarget( type="ip", ip={"ip": "203.0.113.1"} ) ) action.wait_until_finished() # Remove target action = client.load_balancers.remove_target( load_balancer=lb, target=LoadBalancerTarget(type="server", server=server) ) action.wait_until_finished() ``` -------------------------------- ### Server Rescue Mode: Enable, Disable, and Reboot Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt This example shows how to enable rescue mode for a server with specified SSH keys, retrieve the root password, reboot the server into rescue mode, and then disable rescue mode. ```python from hcloud import Client from hcloud.ssh_keys import SSHKey client = Client(token="YOUR_API_TOKEN") server = client.servers.get_by_name("my-server") # Enable rescue mode response = server.enable_rescue( ssh_keys=[SSHKey(name="my-key")] ) root_password = response.root_password action = response.action print(f"Rescue mode enabled") print(f"Root password: {root_password}") # Reboot into rescue mode action.wait_until_finished() reboot_action = server.reset() reboot_action.wait_until_finished() print("Server booted into rescue mode") # After maintenance, disable rescue mode server.disable_rescue() server.reset() # Reboot into normal mode ``` -------------------------------- ### Network Management: Attach Server to Network Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt This code example shows how to attach an existing server to a specified private network, allowing for secure internal communication. The server will receive an IP address automatically. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") server = client.servers.get_by_name("my-server") network = client.networks.get_by_name("prod-network") # Attach server to network with automatic IP action = server.attach_to_network(network=network) action.wait_until_finished() print("Server attached to network") ``` -------------------------------- ### Install Hetzner Cloud Python via conda Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/installation.rst Installs the Hetzner Cloud Python SDK using the conda package manager from the conda-forge channel. Note that this package is third-party and might not be up-to-date. ```shell conda install -c conda-forge hcloud ``` -------------------------------- ### Implement Deprecation Notice in Docstring Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Example of how to mark a Python function or module as deprecated in its docstring, including the version and recommended alternative. ```python """Get image by name .. deprecated:: 1.19 Use :func:`hcloud.images.client.ImagesClient.get_by_name_and_architecture` instead. """ ``` -------------------------------- ### Raise Deprecation Warning in Python Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Python code snippet demonstrating how to raise a DeprecationWarning when a deprecated function or method is called, guiding users to the correct alternative. ```python import warnings 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, ) ``` -------------------------------- ### Build Documentation for hcloud-python Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Command to build the documentation for the hcloud-python library and open it in a web browser. ```shell make docs ``` -------------------------------- ### Server Images: Create Backup Snapshot Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt This snippet illustrates how to create a snapshot image from a server, optionally with descriptions and labels, and then use that image to create a new server. ```python from hcloud import Client from hcloud.server_types import ServerType # Ensure ServerType is imported client = Client(token="YOUR_API_TOKEN") server = client.servers.get_by_name("my-server") # Create snapshot image response = server.create_image( description="backup-2025-10-23", labels={"type": "backup", "date": "2025-10-23"}, type="snapshot" # or "backup" for automatic backups ) image = response.image action = response.action print(f"Image ID: {image.id}") print(f"Image Name: {image.name}") print(f"Description: {image.description}") # Wait for image creation to complete action.wait_until_finished() print("Image created successfully") # Use image to create new server new_response = client.servers.create( name="cloned-server", server_type=ServerType(name="cx22"), image=image ) ``` -------------------------------- ### Initialize Hetzner Cloud Client with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Demonstrates how to initialize the Hetzner Cloud client using your API token. Covers basic and advanced configurations, including custom endpoints, application details, polling intervals, and timeouts. Shows how to access resource-specific clients. ```python from hcloud import Client # Basic initialization client = Client(token="YOUR_API_TOKEN") # Advanced initialization with custom configuration client = Client( token="YOUR_API_TOKEN", api_endpoint="https://api.hetzner.cloud/v1", application_name="my-app", application_version="1.0.0", poll_interval=1.0, # Seconds between action status checks poll_max_retries=120, # Maximum retries for action completion timeout=60.0 # Request timeout in seconds ) # Access resource clients servers_client = client.servers volumes_client = client.volumes networks_client = client.networks load_balancers_client = client.load_balancers firewalls_client = client.firewalls zones_client = client.zones ``` -------------------------------- ### Hetzner Cloud Client Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/api.rst Documentation for the main Hetzner Cloud client interface, which serves as the entry point for interacting with the Hetzner Cloud API. ```APIDOC ## hcloud.Client ### Description This class represents the main interface for interacting with the Hetzner Cloud API. It provides methods for managing various resources within your Hetzner Cloud account. ### Members Detailed members (methods and attributes) of this class are available in the full API documentation. ``` -------------------------------- ### Create DNS Zone (Beta) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt This snippet demonstrates the initial step of creating a DNS zone using the experimental DNS API in the Hetzner Cloud Python SDK. Further steps would involve adding record sets. ```python from hcloud import Client from hcloud.zones import Zone, ZoneRRSet, ZoneRecord client = Client(token="YOUR_API_TOKEN") # Example: Create a DNS Zone (this is a placeholder, actual creation might require more parameters) # zone = client.zones.create(name="example.com") # print(f"DNS Zone created: {zone.name}") ``` -------------------------------- ### Waiting for Action Completion and Error Checking Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Shows how to initiate an action (e.g., power on a server) and then wait for its completion. Includes error handling for failed actions and accessing action status and error details. ```python # Assuming 'client' and 'server' are already defined and valid action = server.power_on() try: action.wait_until_finished() except Exception as e: print(f"Action failed: {e}") print(f"Action status: {action.status}") print(f"Action error: {action.error}") ``` -------------------------------- ### Server Pagination and Filtering with Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Demonstrates how to retrieve server lists using automatic and manual pagination, and how to filter servers by label selectors, name patterns, status, and sort order using the Hetzner Cloud Python SDK. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Get all results (automatic pagination) all_servers = client.servers.get_all() print(f"Total servers: {len(all_servers)}") # Manual pagination page = 1 per_page = 25 while True: response = client.servers.get_list( page=page, per_page=per_page ) servers = response.servers meta = response.meta print(f"Page {page}: {len(servers)} servers") for server in servers: print(f" - {server.name}") if meta.pagination.next_page is None: break page = meta.pagination.next_page # Filter with label selectors prod_servers = client.servers.get_all( label_selector="env=production,region=eu" ) # Filter by name pattern web_servers = client.servers.get_all(name="web-*") # Combine filters filtered = client.servers.get_all( label_selector="app=web", status=["running", "starting"] ) # Sort results sorted_servers = client.servers.get_list( sort=["name:asc", "created:desc"] ) ``` -------------------------------- ### API Clients Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/api.rst Overview of the different API clients available for interacting with specific Hetzner Cloud services. ```APIDOC ## API Clients ### Description This section provides access to various API clients, each designed for managing specific Hetzner Cloud resources such as servers, networks, volumes, and more. Navigate through the linked documentation for detailed information on each client. ### Submodules - `api.clients.servers` - `api.clients.networks` - `api.clients.volumes` - (and others as specified in the toctree) ``` -------------------------------- ### Manage Hetzner Cloud Server Power with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Details how to perform power management operations on a Hetzner Cloud server using the Python SDK. Covers powering on, shutting down (graceful and forced), rebooting, and resetting servers. Includes checking the status of initiated actions. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") server = client.servers.get_by_name("my-server") # Power on server action = server.power_on() action.wait_until_finished() print("Server powered on") # Graceful shutdown (requires running OS) action = server.shutdown() action.wait_until_finished() # Force power off action = server.power_off() action.wait_until_finished() # Reboot (graceful restart) action = server.reboot() action.wait_until_finished() # Reset (hard reset) action = server.reset() action.wait_until_finished() # Check action status print(f"Action ID: {action.id}") print(f"Status: {action.status}") print(f"Progress: {action.progress}%") ``` -------------------------------- ### List and Query Hetzner Cloud Servers with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Explains how to retrieve a list of all servers or filter them using various criteria like name, ID, label selectors, and status. Demonstrates using `get_all()`, `get_by_name()`, `get_by_id()`, and label/status filters. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # List all servers servers = client.servers.get_all() for server in servers: print(f"ID: {server.id}, Name: {server.name}, Status: {server.status}") print(f" IPv4: {server.public_net.ipv4.ip}") print(f" Type: {server.server_type.name}") print(f" Datacenter: {server.datacenter.name}") # Query by name server = client.servers.get_by_name("my-server") if server: print(f"Found server: {server.id}") # Query by ID server = client.servers.get_by_id(12345) # Filter by label selector production_servers = client.servers.get_all( label_selector="env=production" ) # Filter by status running_servers = client.servers.get_all(status=["running"]) ``` -------------------------------- ### Create DNS Zone with Records - Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Creates a primary DNS zone for a domain and adds various record sets (A, CNAME, MX) with associated records. It then prints details about the created zone and waits for any associated actions to complete. ```python from hcloud.zones import Zone, ZoneRRSet, ZoneRecord # Assuming 'client' is an initialized hcloud.Client instance response = client.zones.create( name="example.com", mode=Zone.MODE_PRIMARY, ttl=86400, labels={"env": "production"}, rrsets=[ ZoneRRSet( name="@", type="A", ttl=3600, records=[ ZoneRecord( value="203.0.113.1", comment="Primary web server" ) ] ), ZoneRRSet( name="www", type="CNAME", records=[ ZoneRecord(value="@") ] ), ZoneRRSet( name="@", type="MX", records=[ ZoneRecord(value="10 mail.example.com.") ] ), ZoneRRSet( name="mail", type="A", records=[ ZoneRecord(value="203.0.113.2") ] ) ] ) zone = response.zone action = response.action action.wait_until_finished() print(f"Zone ID: {zone.id}") print(f"Zone Name: {zone.name}") print(f"Status: {zone.status}") print(f"Record Count: {zone.record_count}") print(f"Nameservers: {zone.authoritative_nameservers}") ``` -------------------------------- ### DNS Zone Management - Create Zone (Beta) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Create and manage DNS zones with resource record sets using the experimental DNS API. This allows for programmatic control over your domain's DNS records. ```APIDOC ## DNS Zone Management - Create Zone (Beta) ### Description Create and manage DNS zones with resource record sets using the experimental DNS API. ### Method POST ### Endpoint `/zones` ### Parameters #### Request Body - **name** (string) - Required - The name of the DNS zone (e.g., `example.com`). - **soa_mail** (string) - Required - The email address for the SOA record. - **ttl** (integer) - Optional - Default TTL for new record sets. ### Request Example ```json { "name": "example.com", "soa_mail": "hostmaster@example.com", "ttl": 3600 } ``` ### Response #### Success Response (200) - **zone** (object) - The created zone object. - **id** (integer) - Unique identifier for the zone. - **name** (string) - The name of the DNS zone. - **soa_mail** (string) - The email address in the SOA record. - **ttl** (integer) - Default TTL. - **created** (string) - Timestamp of creation. #### Response Example ```json { "zone": { "id": 11111, "name": "example.com", "soa_mail": "hostmaster@example.com", "ttl": 3600, "created": "2023-10-27T10:00:00Z" } } ``` ``` -------------------------------- ### Allocate and Manage Floating IPs (Create, Assign, Unassign, Update) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Shows how to create a floating IP with description, labels, and DNS PTR records. It also covers assigning the floating IP to a server, reassigning it to another server, unassigning it, and updating its properties. ```python from hcloud import Client from hcloud.locations import Location client = Client(token="YOUR_API_TOKEN") # Create floating IP floating_ip = client.floating_ips.create( type="ipv4", description="Production web server IP", labels={"service": "web"}, home_location=Location(name="fsn1"), dns_ptr=[{"ip": "203.0.113.1", "dns_ptr": "web.example.com"}] ) print(f"Floating IP: {floating_ip.ip}") print(f"ID: {floating_ip.id}") # Assign to server server = client.servers.get_by_name("my-server") action = client.floating_ips.assign( floating_ip=floating_ip, server=server ) action.wait_until_finished() print(f"Floating IP assigned to {server.name}") # Reassign to different server backup_server = client.servers.get_by_name("backup-server") action = client.floating_ips.assign( floating_ip=floating_ip, server=backup_server ) action.wait_until_finished() # Unassign from any server action = client.floating_ips.unassign(floating_ip=floating_ip) action.wait_until_finished() # Update reverse DNS floating_ip.update( description="Updated description", labels={"service": "web", "env": "prod"} ) ``` -------------------------------- ### Network Management: Create VPC, Subnet, and Route Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt This snippet demonstrates creating a private network (VPC), adding a subnet with a specified IP range, and adding a route to the network using the hcloud-python client. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Create network network = client.networks.create( name="prod-network", ip_range="10.0.0.0/16", labels={"env": "production"} ) print(f"Network created: {network.id}") print(f"IP Range: {network.ip_range}") # Add subnet subnet = client.networks.create_subnet( network=network, network_zone="eu-central", type="cloud", ip_range="10.0.1.0/24" ) print(f"Subnet created: {subnet.ip_range}") # Add route client.networks.add_route( network=network, destination="10.100.0.0/16", gateway="10.0.1.1" ) # Update network network.update( name="production-network", labels={"env": "production", "region": "eu"} ) ``` -------------------------------- ### Volume Management: Create, Attach, Resize, Detach (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Shows how to create, attach, resize, and detach block storage volumes using the hcloud-python client. Requires API token and server name. Volumes can be formatted and automounted. ```python from hcloud import Client from hcloud.locations import Location client = Client(token="YOUR_API_TOKEN") # Create volume volume = client.volumes.create( size=100, # Size in GB name="data-volume", labels={"type": "database"}, location=Location(name="fsn1"), format="ext4", # Automatically format the volume automount=False ) print(f"Volume ID: {volume.id}") print(f"Volume Name: {volume.name}") print(f"Size: {volume.size} GB") # Attach volume to server server = client.servers.get_by_name("my-server") action = client.volumes.attach( volume=volume, server=server, automount=True # Automatically mount on server ) action.wait_until_finished() print(f"Volume attached to: {volume.server.name}") print(f"Linux device: {volume.linux_device}") # Resize volume (must be detached or server must be powered off) action = client.volumes.resize(volume=volume, size=200) action.wait_until_finished() # Detach volume action = client.volumes.detach(volume=volume) action.wait_until_finished() ``` -------------------------------- ### Manage DNS Zone Records - Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Demonstrates managing DNS resource record sets within an existing zone, including adding/updating (upserting), listing, deleting specific records, and exporting the zone file in BIND format. Requires an initialized Hetzner Cloud client and a pre-existing zone. ```python from hcloud import Client from hcloud.zones import ZoneRRSet, ZoneRecord # Assuming 'client' is an initialized hcloud.Client instance zone = client.zones.get_by_name("example.com") # Upsert records (create or update) response = client.zones.upsert_rrsets( zone=zone, rrsets=[ ZoneRRSet( name="api", type="A", ttl=3600, records=[ ZoneRecord(value="203.0.113.10") ] ), ZoneRRSet( name="_acme-challenge", type="TXT", records=[ ZoneRecord(value="validation-token-here") ] ) ] ) response.action.wait_until_finished() # List all resource record sets rrsets, meta = client.zones.get_rrsets(zone=zone) for rrset in rrsets: print(f"Name: {rrset.name}, Type: {rrset.type}") for record in rrset.records: print(f" Value: {record.value}") # Delete specific record sets response = client.zones.delete_rrsets( zone=zone, rrsets=[ ZoneRRSet(name="_acme-challenge", type="TXT") ] ) response.action.wait_until_finished() # Export zone as BIND format export_response = client.zones.export_zonefile(zone=zone) print(export_response.zonefile) ``` -------------------------------- ### Client Initialization with Custom Retry Backoff Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Initializes the Hetzner Cloud client with custom retry backoff strategies. Supports exponential backoff with jitter or constant interval retries. ```python from hcloud import Client from hcloud.backoff import exponential_backoff_function, constant_backoff_function # Client with custom retry backoff client = Client( token="YOUR_API_TOKEN", backoff_function=exponential_backoff_function( base=1.0, multiplier=2, cap=60.0, jitter=True ) ) # Constant backoff (5 seconds between retries) client_constant = Client( token="YOUR_API_TOKEN", backoff_function=constant_backoff_function(interval=5.0) ) ``` -------------------------------- ### Create DNS Zone Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Creates a new DNS zone with specified name, mode, TTL, labels, and resource record sets. ```APIDOC ## POST /v1/zones ### Description Creates a new DNS zone for your account. ### Method POST ### Endpoint /v1/zones ### Parameters #### Request Body - **name** (string) - Required - The name of the zone. - **mode** (string) - Optional - The mode of the zone (e.g., 'primary'). Defaults to 'primary'. - **ttl** (integer) - Optional - The default TTL for records in the zone. Defaults to 3600. - **labels** (object) - Optional - User-defined labels for the zone. - **rrsets** (array) - Optional - An array of resource record set objects to initialize the zone with. - **name** (string) - Required - The name of the record set. - **type** (string) - Required - The type of the record set (e.g., 'A', 'CNAME', 'MX'). - **ttl** (integer) - Optional - The TTL for this record set. - **records** (array) - Required - An array of record objects. - **value** (string) - Required - The value of the record. - **comment** (string) - Optional - A comment for the record. ### Request Example ```python { "name": "example.com", "mode": "primary", "ttl": 86400, "labels": {"env": "production"}, "rrsets": [ { "name": "@", "type": "A", "ttl": 3600, "records": [ { "value": "203.0.113.1", "comment": "Primary web server" } ] } ] } ``` ### Response #### Success Response (201 Created) - **zone** (object) - The created zone object. - **id** (integer) - The ID of the zone. - **name** (string) - The name of the zone. - **status** (string) - The status of the zone. - **record_count** (integer) - The number of records in the zone. - **authoritative_nameservers** (array) - The authoritative nameservers for the zone. - **action** (object) - The action taken to create the zone. #### Response Example ```json { "zone": { "id": 12345, "name": "example.com", "status": "active", "record_count": 1, "authoritative_nameservers": ["ns1.example.com", "ns2.example.com"] }, "action": { "id": 67890, "command": "create_zone", "status": "running" } } ``` ``` -------------------------------- ### Add Experimental Notice to Python Code Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md This snippet shows how to add an 'Experimental' notice to Python classes and functions. It includes placeholders for product, maturity, and a changelog slug, with a link to the changelog for more details. ```python """ Experimental: $PRODUCT is $MATURITY, breaking changes may occur within minor releases. See https://docs.hetzner.cloud/changelog#$SLUG for more details. """ ``` -------------------------------- ### API and HCloud Exception Handling Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Demonstrates how to handle potential API exceptions (APIException) and general Hetzner Cloud exceptions (HCloudException) during server creation. Includes specific handling for common error codes like 'rate_limit_exceeded' and 'invalid_input'. ```python from hcloud import Client, APIException, HCloudException from hcloud.server_type import ServerType from hcloud.image import Image try: server = client.servers.create( name="test-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) except APIException as e: print(f"API Error: {e.code} - {e.message}") print(f"Details: {e.details}") print(f"Correlation ID: {e.correlation_id}") # Handle specific error codes if e.code == "rate_limit_exceeded": print("Rate limit exceeded, waiting...") elif e.code == "invalid_input": print(f"Invalid input: {e.details}") except HCloudException as e: print(f"General error: {e}") ``` -------------------------------- ### Hetzner Cloud Exceptions Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/api.rst Documentation for the base Hetzner Cloud exception class and its specific subclasses. ```APIDOC ## hcloud.HCloudException ### Description This is the base exception class for all errors that can occur when interacting with the Hetzner Cloud API using this SDK. ### Members - `__init__(message)`: Initializes the exception with a message. - `message`: The error message associated with the exception. ``` ```APIDOC ## hcloud.APIException ### Description This exception is raised for general API errors returned by the Hetzner Cloud API. ### Inheritance - Inherits from `hcloud.HCloudException` ``` ```APIDOC ## hcloud.actions.domain.ActionException ### Description Base exception for errors related to asynchronous actions in the Hetzner Cloud API. ### Inheritance - Inherits from `hcloud.HCloudException` ``` ```APIDOC ## hcloud.actions.domain.ActionFailedException ### Description This exception is raised when an asynchronous action initiated via the API fails. ### Inheritance - Inherits from `hcloud.actions.domain.ActionException` ``` ```APIDOC ## hcloud.actions.domain.ActionTimeoutException ### Description This exception is raised when an asynchronous action exceeds its expected timeout period. ### Inheritance - Inherits from `hcloud.actions.domain.ActionException` ``` -------------------------------- ### Server Network Operations (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Demonstrates attaching and detaching servers from networks with specific IP addresses, and configuring alias IPs. Requires a server and network object. ```python action = server.attach_to_network( network=network, ip="10.0.1.50" ) action.wait_until_finished() server.change_alias_ips( network=network, alias_ips=["10.0.1.51", "10.0.1.52"] ) action = server.detach_from_network(network=network) action.wait_until_finished() ``` -------------------------------- ### Run Tests with Current Python Version Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Command to execute the test suite for the hcloud-python library using the currently active Python interpreter. ```shell make test ``` -------------------------------- ### API Helpers and Deprecation Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/docs/api.rst Documentation for utility functions and information regarding deprecated features in the SDK. ```APIDOC ## API Helpers ### Description This section contains utility functions and helpers that can assist in various operations when working with the Hetzner Cloud API. ### Details Refer to the `api.helpers` module for specific functions and their usage. ``` ```APIDOC ## API Deprecation ### Description Information regarding deprecated features, endpoints, or methods within the Hetzner Cloud SDK. This section helps users understand what is being phased out and potential alternatives. ### Details Refer to the `api.deprecation` module for a list of deprecated items and migration guidance. ``` -------------------------------- ### Clone hcloud-python Repository Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/CONTRIBUTING.rst Instructions for cloning the hcloud-python repository for local development. This involves forking the repository on GitHub and then cloning your fork to your local machine. ```bash git clone git@github.com:your_name_here/hcloud-python.git ``` -------------------------------- ### Run Tests with Multiple Python Versions using Tox Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Command to run the hcloud-python test suite across multiple Python versions using the tox testing tool. ```shell tox . ``` -------------------------------- ### Lint Code for hcloud-python Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/README.md Command to run linting checks on the hcloud-python codebase to ensure code quality and style consistency. ```shell make lint ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/fahreddinozcan/hcloud-python-test2/blob/main/CONTRIBUTING.rst Steps to stage, commit, and push your local changes to your forked repository on GitHub. This includes adding all modified files, writing a descriptive commit message, and pushing the branch. ```bash git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Create Load Balancer with HTTP Service and Health Checks Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Creates a load balancer with specified type, location, algorithm, and an HTTP service. The service includes health checks, HTTP specific configurations like sticky sessions, and destination ports. ```python from hcloud import Client from hcloud.load_balancers import ( LoadBalancerService, LoadBalancerServiceHttp, LoadBalancerHealthCheck, LoadBalancerTarget, LoadBalancerAlgorithm ) from hcloud.load_balancer_types import LoadBalancerType from hcloud.locations import Location client = Client(token="YOUR_API_TOKEN") # Create load balancer response = client.load_balancers.create( name="web-lb", load_balancer_type=LoadBalancerType(name="lb11"), location=Location(name="fsn1"), labels={"env": "production"}, algorithm=LoadBalancerAlgorithm(type="round_robin"), services=[ LoadBalancerService( protocol="http", listen_port=80, destination_port=8080, proxyprotocol=False, health_check=LoadBalancerHealthCheck( protocol="http", port=8080, interval=15, timeout=10, retries=3, http={"path": "/health", "status_codes": ["200"]} ), http=LoadBalancerServiceHttp( sticky_sessions=True, redirect_http=False, cookie_name="LBSESSION", cookie_lifetime=300 ) ) ], targets=[] ) lb = response.load_balancer action = response.action action.wait_until_finished() print(f"Load Balancer ID: {lb.id}") print(f"Public IP: {lb.public_net.ipv4.ip}") ``` -------------------------------- ### Error Handling and Retry Logic Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Guidance on handling API exceptions and implementing custom retry strategies. ```APIDOC ## Error Handling and Retry Logic ### Description This section provides information on how to handle potential API errors and implement robust retry mechanisms using backoff strategies. ### API Exceptions The Hetzner Cloud API client raises specific exceptions for different error scenarios: - **APIException**: Base class for all Hetzner Cloud API related errors. - **HCloudException**: General exception for other client-side errors. ### Implementing Retry Logic You can configure custom retry strategies for API requests using backoff functions. #### Constant Backoff Retries after a fixed interval. ```python from hcloud import constant_backoff_function # Retry every 5 seconds backoff_func = constant_backoff_function(5) ``` #### Exponential Backoff Retries with an exponentially increasing interval. ```python from hcloud import exponential_backoff_function # Retry with intervals: 1, 2, 4, 8, 16 seconds backoff_func = exponential_backoff_function(initial_delay=1, backoff_factor=2, max_delay=16) ``` ### Example Usage with Client When initializing the client, you can pass a custom backoff function. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN", retry_strategy=constant_backoff_function(5)) ``` ### Handling Specific Errors You can catch specific exceptions to handle errors gracefully. ```python from hcloud import Client, APIException try: # Your API call here pass except APIException as e: print(f"API Error: {e.code} - {e.name}") # Handle the error appropriately except Exception as e: print(f"An unexpected error occurred: {e}") ``` ``` -------------------------------- ### Firewall Management: Update Rules and Remove (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Illustrates how to update existing firewall rules by setting a new list of rules and removing a firewall from a server resource using hcloud-python. Requires API token and firewall/server names. ```python from hcloud import Client from hcloud.firewalls import FirewallRule client = Client(token="YOUR_API_TOKEN") firewall = client.firewalls.get_by_name("web-firewall") # Replace all rules new_rules = [ FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, source_ips=["0.0.0.0/0", "::/0"], port="80", description="HTTP" ), FirewallRule( direction=FirewallRule.DIRECTION_IN, protocol=FirewallRule.PROTOCOL_TCP, source_ips=["0.0.0.0/0", "::/0"], port="443", description="HTTPS" ), FirewallRule( direction=FirewallRule.DIRECTION_OUT, protocol=FirewallRule.PROTOCOL_TCP, destination_ips=["0.0.0.0/0", "::/0"], port="443", description="Allow outbound HTTPS" ) ] actions = client.firewalls.set_rules(firewall=firewall, rules=new_rules) for action in actions: action.wait_until_finished() print("Firewall rules updated") # Remove firewall from resources server = client.servers.get_by_name("my-server") actions = client.firewalls.remove_from_resources( firewall=firewall, resources=[FirewallResource(type="server", server=server)] ) for action in actions: action.wait_until_finished() ``` -------------------------------- ### API Error Handling and Retries - Python Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Illustrates how to handle potential API exceptions and implement retry strategies for network requests. It imports necessary exception classes and backoff functions from the hcloud library for robust error management. ```python from hcloud import ( Client, APIException, HCloudException, constant_backoff_function, exponential_backoff_function ) ``` -------------------------------- ### DNS Zone Management - Update Records (Beta) Source: https://context7.com/fahreddinozcan/hcloud-python-test2/llms.txt Add, update, or delete DNS resource record sets in existing zones. ```APIDOC ## DNS Zone Management - Update Records (Beta) ### Description This section details operations for managing DNS resource record sets within an existing zone, including adding, updating, listing, and deleting records. ### Upsert Resource Record Sets Adds or updates resource record sets in a specified zone. #### Request Body (Upsert) - **zone** (object) - Required - The zone object to update. - **rrsets** (array) - Required - An array of resource record set objects to upsert. - **name** (string) - Required - The name of the record set. - **type** (string) - Required - The type of the record set. - **ttl** (integer) - Optional - The TTL for this record set. - **records** (array) - Required - An array of record objects. - **value** (string) - Required - The value of the record. ### List Resource Record Sets Retrieves all resource record sets for a given zone. #### Parameters - **zone** (object) - Required - The zone object to list records from. #### Response (List) - **rrsets** (array) - An array of resource record set objects. - **meta** (object) - Metadata about the response. ### Delete Resource Record Sets Deletes specified resource record sets from a zone. #### Request Body (Delete) - **zone** (object) - Required - The zone object from which to delete records. - **rrsets** (array) - Required - An array of resource record set objects to delete (only `name` and `type` are needed). ### Export Zonefile Exports the zone's records in BIND format. #### Parameters - **zone** (object) - Required - The zone object to export. #### Response (Export) - **zonefile** (string) - The zone file content in BIND format. ### Request Example (Upsert) ```python { "rrsets": [ { "name": "api", "type": "A", "ttl": 3600, "records": [ {"value": "203.0.113.10"} ] } ] } ``` ### Response Example (List) ```json { "rrsets": [ { "name": "api", "type": "A", "ttl": 3600, "records": [ {"value": "203.0.113.10"} ] } ], "meta": {} } ``` ```