### Get Server Actions with Filtering and Sorting (Python) Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Retrieves all actions for a specific server, filtering by status and sorting by start time. It then iterates through the actions and prints their command, status, and start time. This requires a pre-initialized Hetzner Cloud client and a server name. ```python server = client.servers.get_by_name("my-server") actions = server.get_actions(status=["success"], sort=["started:desc"]) for action in actions: print(f"{action.command}: {action.status} (started: {action.started})") ``` -------------------------------- ### Create and Configure Private Network Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This code example demonstrates how to create a private network, add subnets and routes, and attach a server to the network using the Hetzner Cloud Python SDK. It requires the `hcloud` client and classes for `Network` and `NetworkSubnet`. The example shows how to retrieve network details after configuration. ```python from hcloud import Client from hcloud.networks import Network, NetworkSubnet client = Client(token="your_api_token_here") # Create a private network response = client.networks.create( name="private-network", ip_range="10.0.0.0/16", labels={"environment": "production"} ) network = response.network print(f"Network created: {network.id}") print(f"IP range: {network.ip_range}") # Add subnet to network subnet_action = network.add_subnet( type="cloud", network_zone="eu-central", ip_range="10.0.1.0/24" ) subnet_action.wait_until_finished() # Add route to network route_action = network.add_route( destination="10.100.0.0/16", gateway="10.0.1.1" ) route_action.wait_until_finished() # Attach server to network server = client.servers.get_by_name("my-server") attach_action = network.attach_to_server( server, ip="10.0.1.5" ) attach_action.wait_until_finished() print(f"Server attached to network with IP 10.0.1.5") # Get network details network = client.networks.get_by_id(network.id) print(f"Subnets: {[s.ip_range for s in network.subnets]}") print(f"Routes: {[(r.destination, r.gateway) for r in network.routes]}") print(f"Servers: {[s.id for s in network.servers]}") ``` -------------------------------- ### Setup Development Virtual Environment with Make Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Set up a virtual environment for development using the provided Makefile. This isolates project dependencies and ensures a consistent development environment. ```sh make venv source venv/bin/activate ``` -------------------------------- ### Install Hetzner Cloud Python Library Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Install the hcloud library using pip. This command fetches and installs the latest version of the library and its dependencies. ```sh pip install hcloud ``` -------------------------------- ### Install Pre-commit Hooks with Make Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Install pre-commit hooks using the Makefile. This automates code formatting and linting checks before each commit, ensuring code quality. ```sh pre-commit install ``` -------------------------------- ### Create, Attach, Detach, Resize, and Delete Volume Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This code example shows the lifecycle management of block storage volumes using the Hetzner Cloud Python SDK. It covers creating a volume, attaching it to a server, detaching it, resizing it (when detached), and finally deleting it. It requires the `hcloud` client, `Volume` and `Location` classes. ```python from hcloud import Client from hcloud.volumes import Volume from hcloud.locations import Location client = Client(token="your_api_token_here") server = client.servers.get_by_name("my-server") # Create a new volume response = client.volumes.create( size=100, # Size in GB name="database-volume", location=Location(name="nbg1"), format="ext4", labels={"purpose": "database"} ) volume = response.volume action = response.action print(f"Volume created: {volume.id}") print(f"Size: {volume.size} GB") print(f"Linux device: {volume.linux_device}") # Wait for volume creation action.wait_until_finished() # Attach volume to server attach_action = volume.attach(server, automount=True) attach_action.wait_until_finished() print(f"Volume attached to {server.name} at {volume.linux_device}") # Detach volume detach_action = volume.detach() detach_action.wait_until_finished() print("Volume detached") # Resize volume (only when detached) resize_action = volume.resize(200) # Resize to 200 GB resize_action.wait_until_finished() print(f"Volume resized to {volume.size} GB") # Delete volume client.volumes.delete(volume) print("Volume deleted") ``` -------------------------------- ### Get Specific Action by ID (Python) Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Fetches a specific action by its unique identifier. It requires the Hetzner Cloud client and the action ID. The example then prints the action's ID, command, and status. This is useful for checking the status of a particular operation. ```python action = client.actions.get_by_id(12345) print(f"Action {action.id}: {action.command} - {action.status}") ``` -------------------------------- ### Create and List Hetzner Cloud Servers with Python Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Example demonstrating how to create a server with a specified name, server type, and image using the Hetzner Cloud Python client. It also shows how to retrieve the root password and list all existing servers, printing their IDs, names, and statuses. ```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=}") ``` -------------------------------- ### Create Load Balancer with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This example demonstrates the creation and configuration of a load balancer using the hcloud-python SDK. It includes defining the load balancer type, location, public interface, labels, adding HTTP services with health checks, and attaching servers as targets. The snippet also shows how to retrieve load balancer metrics. Dependencies include Client, LoadBalancer, LoadBalancerService, LoadBalancerTarget, LoadBalancerType, and Location classes. ```python from hcloud import Client from hcloud.load_balancers import LoadBalancer, LoadBalancerService, LoadBalancerTarget from hcloud.load_balancer_types import LoadBalancerType from hcloud.locations import Location client = Client(token="your_api_token_here") # Create load balancer response = client.load_balancers.create( name="web-lb", load_balancer_type=LoadBalancerType(name="lb11"), # Small load balancer location=Location(name="nbg1"), public_interface=True, labels={"environment": "production"} ) load_balancer = response.load_balancer action = response.action print(f"Load balancer created: {load_balancer.id}") print(f"Public IP: {load_balancer.public_net.ipv4.ip}") action.wait_until_finished() # Add HTTP service service = LoadBalancerService( protocol="http", listen_port=80, destination_port=80, proxyprotocol=False, http={ "sticky_sessions": True, "cookie_name": "HCLBSTICKY", "cookie_lifetime": 300, "redirect_http": False }, health_check={ "protocol": "http", "port": 80, "interval": 15, "timeout": 10, "retries": 3, "http": { "domain": "example.com", "path": "/health", "status_codes": ["2??", "3??"] } } ) add_service_action = load_balancer.add_service(service) add_service_action.wait_until_finished() # Add servers as targets server1 = client.servers.get_by_name("web-server-1") server2 = client.servers.get_by_name("web-server-2") add_target_action = load_balancer.add_target( LoadBalancerTarget(type="server", server=server1, use_private_ip=False) ) add_target_action.wait_until_finished() add_target_action = load_balancer.add_target( LoadBalancerTarget(type="server", server=server2, use_private_ip=False) ) add_target_action.wait_until_finished() print(f"Load balancer configured with {len(load_balancer.targets)} targets") # Get load balancer metrics from datetime import datetime, timedelta, timezone end = datetime.now(timezone.utc) start = end - timedelta(hours=1) metrics_response = load_balancer.get_metrics( type=["open_connections", "requests_per_second"], start=start, end=end ) print(f"Metrics: {metrics_response.metrics.time_series.keys()}") ``` -------------------------------- ### List and Retrieve Hetzner Cloud Servers with Python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Demonstrates how to list all Hetzner Cloud servers, retrieve a specific server by name or ID, or filter servers using label selectors. It also shows how to handle paginated results. ```python from hcloud import Client client = Client(token="your_api_token_here") # Get all servers servers = client.servers.get_all() for server in servers: print(f"ID: {server.id}, Name: {server.name}, Status: {server.status}") print(f" Type: {server.server_type.name}") print(f" IPv4: {server.public_net.ipv4.ip}") print(f" Location: {server.datacenter.location.name}") # Get server by name server = client.servers.get_by_name("my-server") if server: print(f"Found server: {server.name} (ID: {server.id})") # Get server by ID server = client.servers.get_by_id(12345) # Get servers with label selector servers = client.servers.get_all(label_selector="environment=production") print(f"Found {len(servers)} production servers") # Get servers with pagination page_result = client.servers.get_list(page=1, per_page=25) servers = page_result.servers meta = page_result.meta print(f"Page {meta.pagination.page} of {meta.pagination.last_page}") ``` -------------------------------- ### Images, Server Types, and Locations API Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Query available operating system images, server hardware configurations, and datacenter locations. ```APIDOC ## Images, Server Types, and Locations API This section covers how to retrieve information about available resources like images, server types, and datacenters. ### List Images Retrieves a list of available operating system images. Images can be filtered by type. * **Method**: Implicitly via `client.images.get_all` * **Endpoint**: N/A (Client method) * **Parameters**: * **type** (string) - Optional - Filter images by type (e.g., `"system"`, `"snapshot"`, `"backup"`). ### Get Image by Name and Architecture Retrieves a specific image by its name and architecture. * **Method**: Implicitly via `client.images.get_by_name_and_architecture` * **Endpoint**: N/A (Client method) * **Parameters**: * **name** (string) - Required - The name of the image. * **architecture** (string) - Required - The architecture of the image (e.g., `"x86"`). ### List Server Types Retrieves a list of all available server hardware configurations. * **Method**: Implicitly via `client.server_types.get_all` * **Endpoint**: N/A (Client method) ### Get Server Type by Name Retrieves a specific server type by its name. * **Method**: Implicitly via `client.server_types.get_by_name` * **Endpoint**: N/A (Client method) * **Parameters**: * **name** (string) - Required - The name of the server type (e.g., `"cx22"`). ### List Datacenters Retrieves a list of all available datacenters. * **Method**: Implicitly via `client.datacenters.get_all` * **Endpoint**: N/A (Client method) ### List Locations Retrieves a list of all available locations. * **Method**: Implicitly via `client.locations.get_all` * **Endpoint**: N/A (Client method) ### Example Usage ```python from hcloud import Client client = Client(token="your_api_token_here") # List all available images images = client.images.get_all() for image in images: print(f"{image.name} - {image.description}") print(f" Type: {image.type}, OS: {image.os_flavor} {image.os_version}") print(f" Architecture: {image.architecture}") # List all server types server_types = client.server_types.get_all() for st in server_types: print(f"{st.name}: {st.cores} CPU, {st.memory} GB RAM, {st.disk} GB disk") print(f" Architecture: {st.architecture}") print(f" Price: €{st.prices[0].price_monthly.gross}/month") # List datacenters datacenters = client.datacenters.get_all() for dc in datacenters: print(f"{dc.name}: {dc.description} ({dc.location.city}, {dc.location.country})") ``` ``` -------------------------------- ### Create Hetzner Cloud Server with Python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Creates a new Hetzner Cloud server with specified configurations like name, server type, image, SSH keys, location, and user data. Includes error handling and waits for the server to be ready, outputting its details. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType from hcloud.ssh_keys import SSHKey from hcloud.locations import Location client = Client(token="your_api_token_here") try: # Create a server with basic configuration response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), # 2 vCPU, 4GB RAM image=Image(name="ubuntu-24.04"), ssh_keys=[SSHKey(name="my-ssh-key")], location=Location(name="nbg1"), # Nuremberg datacenter start_after_create=True, labels={"environment": "production", "project": "web-app"}, user_data="#cloud-config\nruncmd:\n - apt-get update" ) server = response.server action = response.action root_password = response.root_password print(f"Server created: {server.id}") print(f"Name: {server.name}") print(f"Status: {server.status}") print(f"IPv4: {server.public_net.ipv4.ip}") print(f"IPv6: {server.public_net.ipv6.ip}") print(f"Root password: {root_password}") # Wait for server to be ready action.wait_until_finished(max_retries=120) print(f"Server is ready: {server.status}") except Exception as e: print(f"Error creating server: {e}") ``` -------------------------------- ### List Cloud Resources with Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Shows how to query and list available operating system images, server hardware configurations, datacenters, and locations using the hcloud-python client. It demonstrates filtering images by type and retrieving specific resources by name. ```python from hcloud import Client # Assuming 'client' is an initialized HCloud Client object # List all available images images = client.images.get_all() for image in images: print(f"{image.name} - {image.description}") print(f" Type: {image.type}, OS: {image.os_flavor} {image.os_version}") print(f" Architecture: {image.architecture}") # Get images by type system_images = client.images.get_all(type="system") # Official images snapshot_images = client.images.get_all(type="snapshot") # User snapshots backup_images = client.images.get_all(type="backup") # Automated backups # Get specific image by name and architecture image = client.images.get_by_name_and_architecture("ubuntu-24.04", "x86") # List all server types server_types = client.server_types.get_all() for st in server_types: print(f"{st.name}: {st.cores} CPU, {st.memory} GB RAM, {st.disk} GB disk") print(f" Architecture: {st.architecture}") print(f" Price: €{st.prices[0].price_monthly.gross}/month") # Get specific server type server_type = client.server_types.get_by_name("cx22") print(f"Server type: {server_type.description}") # List datacenters and locations datacenters = client.datacenters.get_all() for dc in datacenters: print(f"{dc.name}: {dc.description} ({dc.location.city}, {dc.location.country})") locations = client.locations.get_all() for loc in locations: print(f"{loc.name}: {loc.city}, {loc.country} (Network zone: {loc.network_zone})") ``` -------------------------------- ### Manage SSH Keys with Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Demonstrates creating, listing, retrieving, updating, and deleting SSH keys using the hcloud-python client. It also shows how to associate an SSH key during server creation. ```python from hcloud.images import Image from hcloud.server_types import ServerType # Assuming 'client' is an initialized HCloud Client object # and 'public_key' is a string containing the public SSH key # Create SSH key ssh_key = client.ssh_keys.create( name="my-workstation", public_key=public_key, labels={"owner": "john.doe"} ) print(f"SSH key created: {ssh_key.id}") print(f"Fingerprint: {ssh_key.fingerprint}") # List all SSH keys all_keys = client.ssh_keys.get_all() for key in all_keys: print(f"{key.name}: {key.fingerprint}") # Get SSH key by name ssh_key = client.ssh_keys.get_by_name("my-workstation") # Update SSH key updated_key = client.ssh_keys.update( ssh_key, name="office-workstation", labels={"owner": "john.doe", "location": "office"} ) # Delete SSH key client.ssh_keys.delete(ssh_key) print("SSH key deleted") # Use SSH key when creating server response = client.servers.create( name="secure-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04"), ssh_keys=[ssh_key] # Server will have this SSH key ) ``` -------------------------------- ### Initialize Hetzner Cloud Client with Python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Initializes the Hetzner Cloud client using an API token. Supports custom API endpoints, application details, polling intervals, retry counts, and timeouts for robust interaction with the Hetzner Cloud API. ```python from hcloud import Client # Initialize client with API token client = Client(token="your_api_token_here") # Initialize with custom settings client = Client( token="your_api_token_here", api_endpoint="https://api.hetzner.cloud/v1", application_name="MyApp", application_version="1.0.0", poll_interval=2.0, # Seconds between action polls poll_max_retries=120, timeout=(5.0, 30.0) # Connection and read timeout ) # Access resource clients servers_client = client.servers volumes_client = client.volumes networks_client = client.networks ``` -------------------------------- ### Error Handling and Retries API Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Demonstrates how to handle API errors and configure retry mechanisms for transient failures using the hcloud-python client. ```APIDOC ## Error Handling and Retries API This section explains how to manage potential errors during API interactions and configure automatic retries. ### Handling API Exceptions Catch specific `APIException` errors to handle different API-related issues. * **Exception Types**: * `APIException`: Base class for API errors. Contains `message`, `code`, `correlation_id`, and `details`. * `HCloudException`: General library exceptions. ### Common API Error Codes * `rate_limit_exceeded`: Indicates that the API rate limit has been reached. * `uniqueness_error`: Occurs when trying to create a resource with a name that already exists. * `invalid_input`: Signifies that the provided request data is invalid. ### Customizing Retry Behavior Configure the client to use custom retry strategies, such as exponential backoff. * **`poll_interval`**: A function that determines the delay between retries. The `exponential_backoff_function` is provided for convenience. * **`poll_max_retries`**: The maximum number of times to retry an operation. ### Example Usage ```python from hcloud import Client, APIException, HCloudException from hcloud.images import Image from hcloud.server_types import ServerType client = Client(token="your_api_token_here") try: # Attempt to create server response = client.servers.create( name="test-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) server = response.server print(f"Server created: {server.id}") except APIException as e: # API returned an error print(f"API Error: {e.message}") print(f"Error code: {e.code}") print(f"Correlation ID: {e.correlation_id}") if e.code == "rate_limit_exceeded": print("Rate limit exceeded, retry after delay") elif e.code == "uniqueness_error": print("Server name already exists") elif e.code == "invalid_input": print(f"Invalid input: {e.details}") except HCloudException as e: # General library exception print(f"HCloud Error: {e}") except Exception as e: # Other exceptions print(f"Unexpected error: {e}") # Custom retry configuration with exponential backoff from hcloud import exponential_backoff_function custom_backoff = exponential_backoff_function( base=2.0, multiplier=2, cap=120.0, jitter=True ) client_with_retries = Client( token="your_api_token_here", poll_interval=custom_backoff, poll_max_retries=100 ) ``` ``` -------------------------------- ### Create and Configure Firewall with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This comprehensive snippet illustrates the creation, configuration, and management of firewalls using the hcloud-python SDK. It covers defining rules, applying the firewall to servers, updating rules, removing it from resources, and finally deleting the firewall. Dependencies include the Client, Firewall, and FirewallRule classes. Input includes firewall name, rules, labels, and server objects. Outputs are firewall ID and status messages. ```python from hcloud import Client from hcloud.firewalls import Firewall, FirewallRule client = Client(token="your_api_token_here") # Define firewall rules rules = [ FirewallRule( direction="in", protocol="tcp", source_ips=["0.0.0.0/0", "::/0"], port="22", description="Allow SSH from anywhere" ), FirewallRule( direction="in", protocol="tcp", source_ips=["0.0.0.0/0", "::/0"], port="80", description="Allow HTTP" ), FirewallRule( direction="in", protocol="tcp", source_ips=["0.0.0.0/0", "::/0"], port="443", description="Allow HTTPS" ), FirewallRule( direction="out", protocol="tcp", destination_ips=["0.0.0.0/0", "::/0"], port="any", description="Allow all outbound TCP" ) ] # Create firewall response = client.firewalls.create( name="web-firewall", rules=rules, labels={"purpose": "web-server"} ) firewall = response.firewall print(f"Firewall created: {firewall.id}") print(f"Rules: {len(firewall.rules)}") # Apply firewall to server server = client.servers.get_by_name("my-server") apply_action = firewall.apply_to_resources([{"type": "server", "server": server}]) apply_action.wait_until_finished() print(f"Firewall applied to server {server.name}") # Update firewall rules new_rules = rules + [ FirewallRule( direction="in", protocol="tcp", source_ips=["10.0.0.0/8"], port="3306", description="Allow MySQL from private network" ) ] firewall.set_rules(new_rules) print("Firewall rules updated") # Remove firewall from server remove_action = firewall.remove_from_resources([{"type": "server", "server": server}]) remove_action.wait_until_finished() # Delete firewall client.firewalls.delete(firewall) ``` -------------------------------- ### Reset and Restart Server Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This snippet demonstrates how to forcefully restart a server and reset its root password using the Hetzner Cloud Python SDK. It requires a server object and interacts with the server's reset and reset_password methods. ```python # Reset server (force restart) action = server.reset() action.wait_until_finished() # Reset root password response = server.reset_password() print(f"New root password: {response.root_password}") ``` -------------------------------- ### Monitor Actions with Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Demonstrates how to use the action objects returned by certain API calls (like server creation) to monitor their progress and wait for completion. It shows both default waiting and waiting with custom retry parameters. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType # Assuming 'client' is an initialized HCloud Client object # Create server returns an action response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) server = response.server action = response.action print(f"Action ID: {action.id}") print(f"Command: {action.command}") print(f"Status: {action.status}") print(f"Progress: {action.progress}%") # Wait for action to complete (with default timeout) action.wait_until_finished() print(f"Action completed: {action.status}") # Wait with custom parameters try: action.wait_until_finished(max_retries=60) except TimeoutError: print("Action did not complete in time") ``` -------------------------------- ### Implement Deprecation Notice in Docstring Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Example of how to mark a Python function or module as deprecated in its docstring. This includes specifying the version from which it is deprecated and suggesting an alternative. ```python """Get image by name .. deprecated:: 1.19 Use :func:`hcloud.images.client.ImagesClient.get_by_name_and_architecture` instead. """ ``` -------------------------------- ### Action Polling and Waiting API Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Monitor and wait for long-running operations to complete using action objects returned by certain API calls. ```APIDOC ## Action Polling and Waiting API This section describes how to track the progress of asynchronous operations (actions) and wait for them to finish. ### Action Objects Many operations, like server creation, return an `Action` object. This object represents the ongoing process and provides status updates. * **Attributes**: `id`, `command`, `status` (e.g., `"running"`, `"successful"`, `"failed"`), `progress` (percentage). ### Waiting for Actions The `Action` object provides a `wait_until_finished()` method to block execution until the action completes. * **`wait_until_finished()`**: Waits for the action to reach a terminal state (`successful` or `failed`). * **Parameters**: * `max_retries` (int) - Optional - The maximum number of retries before timing out. * **Raises**: `TimeoutError` if the action does not complete within the specified retries. ### Example Usage ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType client = Client(token="your_api_token_here") # Create server returns an action response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) sasdasd = response.server action = response.action print(f"Action ID: {action.id}") print(f"Command: {action.command}") print(f"Status: {action.status}") print(f"Progress: {action.progress}%") # Wait for action to complete (with default timeout) action.wait_until_finished() print(f"Action completed: {action.status}") # Wait with custom parameters try: action.wait_until_finished(max_retries=60) except TimeoutError: print("Action did not complete in time") ``` ``` -------------------------------- ### Delete Network with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This code demonstrates how to delete a network using the hcloud-python SDK. It requires a client instance and a network object to be passed to the delete method. ```python # Delete network client.networks.delete(network) ``` -------------------------------- ### Retrieve Server Metrics Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This code retrieves CPU, disk, and network metrics for a specific server over a given time range. It utilizes the `get_metrics` method and requires the `hcloud` client and `datetime` modules. The output includes time-series data for various metrics. ```python from hcloud import Client from datetime import datetime, timedelta, timezone client = Client(token="your_api_token_here") 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(f"CPU Usage: {metrics.time_series['cpu']['values']}") print(f"Disk IOPS: {metrics.time_series['disk.0.iops.read']['values']}") print(f"Network In: {metrics.time_series['network.0.bandwidth.in']['values']}") print(f"Network Out: {metrics.time_series['network.0.bandwidth.out']['values']}") # Process metric data points for timestamp, value in zip( metrics.time_series['cpu']['values'], metrics.time_series['cpu']['values'] ): print(f"{timestamp}: CPU {value}%") ``` -------------------------------- ### SSH Key Management API Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Manage SSH keys for your Hetzner Cloud account, including creation, listing, retrieval, updating, and deletion. SSH keys can also be associated with new servers during creation. ```APIDOC ## SSH Key Management API This section details the operations available for managing SSH keys using the hcloud-python client. ### Create SSH Key Creates a new SSH key. * **Method**: Implicitly via `client.ssh_keys.create` * **Endpoint**: N/A (Client method) * **Parameters**: * **name** (string) - Required - A name for the SSH key. * **public_key** (string) - Required - The public key string. * **labels** (dict) - Optional - Labels to associate with the SSH key. ### List All SSH Keys Retrieves a list of all SSH keys associated with the account. * **Method**: Implicitly via `client.ssh_keys.get_all` * **Endpoint**: N/A (Client method) ### Get SSH Key by Name Retrieves a specific SSH key by its name. * **Method**: Implicitly via `client.ssh_keys.get_by_name` * **Endpoint**: N/A (Client method) * **Parameters**: * **name** (string) - Required - The name of the SSH key to retrieve. ### Update SSH Key Updates an existing SSH key's name and labels. * **Method**: Implicitly via `client.ssh_keys.update` * **Endpoint**: N/A (Client method) * **Parameters**: * **ssh_key** (object) - Required - The SSH key object to update. * **name** (string) - Optional - The new name for the SSH key. * **labels** (dict) - Optional - The new labels for the SSH key. ### Delete SSH Key Deletes an SSH key. * **Method**: Implicitly via `client.ssh_keys.delete` * **Endpoint**: N/A (Client method) * **Parameters**: * **ssh_key** (object) - Required - The SSH key object to delete. ### Example Usage (Creating a Server with SSH Key) ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType client = Client(token="your_api_token_here") public_key = "ssh-rsa AAAAB3NzaC1yc2EAAA... user@example.com" # Create SSH key ssh_key = client.ssh_keys.create( name="my-workstation", public_key=public_key, labels={"owner": "john.doe"} ) # Use SSH key when creating server response = client.servers.create( name="secure-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04"), ssh_keys=[ssh_key] # Server will have this SSH key ) print(f"SSH key created: {ssh_key.id}") print(f"Server created: {response.server.id}") ``` ``` -------------------------------- ### Update, Protect, and Delete Server Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This snippet demonstrates how to update a server's name and labels, enable/disable delete protection, and delete a server using the Hetzner Cloud Python SDK. It includes error handling for cases where delete protection is enabled. ```python from hcloud import Client client = Client(token="your_api_token_here") server = client.servers.get_by_name("my-server") # Update server name and labels updated_server = client.servers.update( server, name="renamed-server", labels={"environment": "staging", "version": "2.0"} ) print(f"Server updated: {updated_server.name}") # Enable delete protection client.servers.change_protection( server, delete=True, rebuild=True ) # Delete server (will fail if protection is enabled) try: action = client.servers.delete(server) action.wait_until_finished() print("Server deleted successfully") except Exception as e: print(f"Delete failed: {e}") # Disable protection and delete client.servers.change_protection(server, delete=False) action = client.servers.delete(server) action.wait_until_finished() print("Server deleted after removing protection") ``` -------------------------------- ### Handle API Errors and Retries with Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Illustrates how to handle various API exceptions (APIException, HCloudException) and general exceptions when interacting with the Hetzner Cloud API. It also shows how to configure custom retry mechanisms with exponential backoff for improved resilience. ```python from hcloud import Client, APIException, HCloudException from hcloud.images import Image from hcloud.server_types import ServerType # Assuming 'client' is an initialized HCloud Client object try: # Attempt to create server response = client.servers.create( name="test-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) server = response.server print(f"Server created: {server.id}") except APIException as e: # API returned an error print(f"API Error: {e.message}") print(f"Error code: {e.code}") print(f"Correlation ID: {e.correlation_id}") if e.code == "rate_limit_exceeded": print("Rate limit exceeded, retry after delay") elif e.code == "uniqueness_error": print("Server name already exists") elif e.code == "invalid_input": print(f"Invalid input: {e.details}") except HCloudException as e: # General library exception print(f"HCloud Error: {e}") except Exception as e: # Other exceptions print(f"Unexpected error: {e}") # Custom retry configuration with exponential backoff from hcloud import exponential_backoff_function custom_backoff = exponential_backoff_function( base=2.0, multiplier=2, cap=120.0, jitter=True ) client = Client( token="your_api_token_here", poll_interval=custom_backoff, poll_max_retries=100 ) ``` -------------------------------- ### Control Hetzner Cloud Server Power State with Python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt Provides Python code to perform power operations on a Hetzner Cloud server, including powering off (hard shutdown), powering on, initiating a soft shutdown (graceful), and rebooting (hard reset). Each operation waits for completion. ```python from hcloud import Client client = Client(token="your_api_token_here") server = client.servers.get_by_name("my-server") # Power off server (hard shutdown) action = server.power_off() action.wait_until_finished() print(f"Server powered off: {server.status}") # Power on server action = server.power_on() action.wait_until_finished() print(f"Server powered on: {server.status}") # Soft shutdown (graceful) action = server.shutdown() action.wait_until_finished() # Reboot server (hard reset) action = server.reboot() action.wait_until_finished() ``` -------------------------------- ### Detach Server from Network with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This snippet shows how to detach a server from a network using the hcloud-python SDK. It requires a pre-existing network object and a server object to be passed to the detach_from_server method. The operation is asynchronous, and wait_until_finished() is used to ensure completion. ```python # Detach server from network detach_action = network.detach_from_server(server) detach_action.wait_until_finished() ``` -------------------------------- ### Manage SSH Keys with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python/llms.txt This snippet demonstrates how to read an SSH public key from a local file for use with Hetzner Cloud. It opens a specified file path, reads its content, and strips leading/trailing whitespace. This public key can then be used for server authentication or management through the hcloud-python SDK. ```python from hcloud import Client client = Client(token="your_api_token_here") # Read SSH public key from file with open("/home/user/.ssh/id_rsa.pub", "r") as f: public_key = f.read().strip() ``` -------------------------------- ### Build Documentation with Make Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Build the project's documentation locally using the Makefile. This command compiles the documentation and typically opens it in a web browser for review. ```sh make docs ``` -------------------------------- ### Run Tests with Make Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Execute the project's test suite using the current Python 3 version via the Makefile. This verifies the functionality and stability of the code. ```sh make test ``` -------------------------------- ### Raise DeprecationWarning in Python Function Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Demonstrates how to raise a DeprecationWarning in Python when a deprecated function or method is called. This informs users about the deprecation and guides them towards the recommended 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, ) ``` -------------------------------- ### Run Tests with Tox for Multiple Python Versions Source: https://github.com/fahreddinozcan/hcloud-python/blob/main/README.md Execute the project's test suite across multiple Python versions using tox. This ensures compatibility and stability across different Python environments. ```sh tox . ```