### Action Management Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Examples for starting, monitoring, and retrieving actions on Hetzner Cloud resources. Includes starting a power-off action, waiting for completion with error handling, getting all actions for a resource, and fetching a specific action by ID. ```APIDOC ## Action Management ### Description Examples for starting, monitoring, and retrieving actions on Hetzner Cloud resources. Includes starting a power-off action, waiting for completion with error handling, getting all actions for a resource, and fetching a specific action by ID. ### Start a long-running action ```python action = server.power_off() print(f"Action ID: {action.id}") print(f"Action Command: {action.command}") print(f"Action Status: {action.status}") print(f"Action Progress: {action.progress}%") # Wait for action to complete with error handling try: action.wait_until_finished(max_retries=100) print("Action completed successfully") except ActionFailedException as e: print(f"Action failed: {e.action.error}") except ActionTimeoutException as e: print(f"Action timeout: still running after max retries") ``` ### Get all actions for a resource ```python actions = server.get_actions( status=["running", "success"], sort=["id:desc"] ) for action in actions: print(f"{action.command}: {action.status}") ``` ### Get specific action by ID ```python action = client.actions.get_by_id(12345) action.reload() # Refresh action status ``` ``` -------------------------------- ### Install from Source Code Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library directly from its source code repository. This involves cloning the GitHub repository or downloading a tarball, then installing using pip. ```console git clone git://github.com/hetznercloud/hcloud-python ``` ```console curl -OL https://github.com/hetznercloud/hcloud-python/tarball/main ``` ```console pip install . ``` -------------------------------- ### Install Stable Release using pip Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/installation.rst Installs the latest stable version of the Hetzner Cloud Python library using pip. This is the recommended installation method. Ensure you have pip installed; refer to the Python installation guide if needed. ```console pip install hcloud ``` -------------------------------- ### Server Types and Pricing Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Retrieve available server types and their specifications, including pricing details. Examples cover listing all server types, getting a specific type, and filtering by name patterns. ```APIDOC ## Server Types and Pricing ### Description Retrieve available server types and their specifications, including pricing details. Examples cover listing all server types, getting a specific type, and filtering by name patterns. ### List all server types ```python server_types = client.server_types.get_all() for st in server_types: print(f"{st.name}:") print(f" Cores: {st.cores}") print(f" Memory: {st.memory} GB") print(f" Disk: {st.disk} GB") print(f" Description: {st.description}") print(f" Architecture: {st.architecture}") ``` ### Get specific server type ```python server_type = client.server_types.get_by_name("cx22") print(f"Hourly price: €{server_type.prices[0].price_hourly.gross}") print(f"Monthly price: €{server_type.prices[0].price_monthly.gross}") ``` ### Filter by name pattern ```python server_types = client.server_types.get_all(name="cx*") ``` ``` -------------------------------- ### Install using conda-forge Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library via 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 ``` -------------------------------- ### Setup Virtual Environment for Development Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Creates and activates a virtual environment for developing the hcloud Python library. This isolates project dependencies. ```sh make venv source venv/bin/activate ``` -------------------------------- ### Manage Hetzner Cloud Servers Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Provides examples for managing the lifecycle of Hetzner Cloud servers, including power operations (on, off, reboot, shutdown, reset), updating server properties like name and labels, resetting the root password, enabling/disabling rescue mode, and deleting servers. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Get server by name or ID server = client.servers.get_by_name("my-server") # Or: server = client.servers.get_by_id(12345) # Power operations server.power_off().wait_until_finished() # Force power off server.power_on().wait_until_finished() # Power on server.reboot().wait_until_finished() # Graceful reboot server.shutdown().wait_until_finished() # Graceful shutdown server.reset().wait_until_finished() # Hard reset # Update server properties server.update( name="renamed-server", labels={"environment": "staging"} ) # Reset root password response = server.reset_password() new_password = response.root_password print(f"New root password: {new_password}") # Enable rescue mode response = server.enable_rescue( type="linux64", ssh_keys=[123, 456] # SSH key IDs ) rescue_password = response.root_password print(f"Rescue password: {rescue_password}") # Disable rescue mode server.disable_rescue().wait_until_finished() # Delete server server.delete().wait_until_finished() ``` -------------------------------- ### Load Balancer Setup with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Create and configure load balancers for distributing network traffic. This includes defining services, health checks, and adding target servers. Requires a Hetzner Cloud client instance and specific load balancer types. ```python from hcloud import Client from hcloud.load_balancers import ( LoadBalancerService, LoadBalancerServiceHttp, LoadBalancerHealthCheck, LoadBalancerHealthCheckHttp, LoadBalancerTarget ) from hcloud.load_balancer_types import LoadBalancerType client = Client(token="YOUR_API_TOKEN") response = client.load_balancers.create( name="web-lb", load_balancer_type=LoadBalancerType(name="lb11"), location=Location(name="nbg1"), labels={"environment": "production"} ) load_balancer = response.load_balancer service = LoadBalancerService( protocol="http", listen_port=80, destination_port=80, http=LoadBalancerServiceHttp( sticky_sessions=True, cookie_name="HCLB", redirect_http=True ), health_check=LoadBalancerHealthCheck( protocol="http", port=80, interval=15, timeout=10, retries=3, http=LoadBalancerHealthCheckHttp( path="/health", status_codes=["200", "201"] ) ) ) action = load_balancer.add_service(service) action.wait_until_finished() server1 = client.servers.get_by_name("web-1") server2 = client.servers.get_by_name("web-2") action = load_balancer.add_target( LoadBalancerTarget(type="server", server=server1) ) action.wait_until_finished() action = load_balancer.add_target( LoadBalancerTarget(type="server", server=server2) ) action.wait_until_finished() print(f"Load balancer IP: {load_balancer.public_net.ipv4.ip}") ``` -------------------------------- ### Action Monitoring and Waiting with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Monitor asynchronous actions performed via the Hetzner Cloud API and wait for their completion. This example demonstrates basic setup for action monitoring, including handling potential exceptions like ActionFailedException and ActionTimeoutException. Requires a Hetzner Cloud client instance. ```python from hcloud import Client from hcloud.actions import ActionFailedException, ActionTimeoutException client = Client(token="YOUR_API_TOKEN") server = client.servers.get_by_name("my-server") # The rest of the action monitoring logic would follow here... ``` -------------------------------- ### Install pre-commit Hooks for Development Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Installs pre-commit hooks to automatically run checks before committing code changes, ensuring code quality and consistency. ```sh pre-commit install ``` -------------------------------- ### Get Servers with Pagination and Filter by Status Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Demonstrates how to retrieve a list of servers with pagination support, allowing you to fetch servers page by page. It also shows how to filter servers based on their status, such as 'running'. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Get servers with pagination result = client.servers.get_list(page=1, per_page=25) servers = result.servers meta = result.meta print(f"Total servers: {meta.total_entries}") print(f"Current page: {meta.page}") # Filter by status servers = client.servers.get_all(status=["running"]) ``` -------------------------------- ### Manage Server Actions and Get Resource Details with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt This snippet shows how to initiate, monitor, and retrieve server actions using the Hetzner Cloud Python client. It includes waiting for actions to complete, handling potential failures or timeouts, and fetching lists of actions for a specific resource or by ID. It also demonstrates how to fetch details about available locations and datacenters. ```python from hcloud import Client from hcloud.actions import ActionFailedException, ActionTimeoutException # Assuming 'server' and 'client' objects are already initialized # Example: client = Client(token="YOUR_API_TOKEN") # Example: server = client.servers.get_by_name("my-server") # Start a long-running action action = server.power_off() print(f"Action ID: {action.id}") print(f"Action Command: {action.command}") print(f"Action Status: {action.status}") print(f"Action Progress: {action.progress}%") # Wait for action to complete with error handling try: action.wait_until_finished(max_retries=100) print("Action completed successfully") except ActionFailedException as e: print(f"Action failed: {e.action.error}") except ActionTimeoutException as e: print(f"Action timeout: still running after max retries") # Get all actions for a resource actions = server.get_actions( status=["running", "success"], sort=["id:desc"] ) for action in actions: print(f"{action.command}: {action.status}") # Get specific action by ID action = client.actions.get_by_id(12345) action.reload() # Refresh action status # List all locations locations = client.locations.get_all() for location in locations: print(f"{location.name}: {location.description} ({location.country})") print(f" City: {location.city}") print(f" Network Zone: {location.network_zone}") # Get specific location location = client.locations.get_by_name("nbg1") # List all datacenters datacenters = client.datacenters.get_all() for dc in datacenters: print(f"{dc.name}: {dc.location.name}") print(f" Supported server types: {dc.supported_types}") # Get datacenter by name datacenter = client.datacenters.get_by_name("nbg1-dc3") ``` -------------------------------- ### Use 'include_architecture_wildcard' Instead of Deprecated Argument Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/upgrading.md This example shows how to update calls to `Client.isos.get_list` and `Client.isos.get_all` in hcloud-python. The deprecated `include_wildcard_architecture` argument has been removed and replaced with `include_architecture_wildcard`. ```diff client.isos.get_all( - include_wildcard_architecture=True, + include_architecture_wildcard=True, ) ``` -------------------------------- ### Update Primary IP Creation Argument Order and Optionality Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/upgrading.md This code demonstrates changes to the `Client.primary_ips.create` method in hcloud-python. The `datacenter` argument has been moved after the `name` argument and is now optional. The examples show both removing a `None` placeholder and explicitly naming the `datacenter` 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"), ) ``` -------------------------------- ### Raise Deprecation Warning in Python Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Demonstrates how to issue a `DeprecationWarning` in Python when a deprecated function or module is called, guiding users to 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, ) ``` -------------------------------- ### Add Deprecation Notice to Docstring Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Example of how to mark a Python function or module as deprecated in its docstring, including the version it was deprecated in and suggesting an alternative. ```python Get image by name .. deprecated:: 1.19 Use :func:`hcloud.images.client.ImagesClient.get_by_name_and_architecture` instead. ``` -------------------------------- ### Create Hetzner Cloud Server Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Shows how to create new cloud servers using the Hetzner Cloud Python library. Covers basic server creation with name, server type, and image, as well as advanced creation with SSH keys, location, user data, labels, and more. Includes waiting for the server to be ready. ```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 client = Client(token="YOUR_API_TOKEN") # Create a basic server response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) server = response.server root_password = response.root_password action = response.action print(f"Server ID: {server.id}") print(f"Server Name: {server.name}") print(f"Server Status: {server.status}") print(f"Root Password: {root_password}") # Wait for server to be ready action.wait_until_finished() # Advanced server creation with full configuration response = client.servers.create( name="production-server", server_type=ServerType(name="cx32"), image=Image(name="ubuntu-24.04"), ssh_keys=[SSHKey(name="my-ssh-key")], location=Location(name="nbg1"), user_data="#!/bin/bash\napt-get update\napt-get install -y docker.io", labels={"environment": "production", "team": "backend"}, automount=False, start_after_create=True ) ``` -------------------------------- ### Initialize Hetzner Cloud Client Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Demonstrates how to initialize the Hetzner Cloud client using an API token. Includes basic initialization and advanced configuration with custom API endpoint, application details, polling intervals, retry limits, and timeouts. ```python from hcloud import Client # Basic client initialization client = Client(token="YOUR_API_TOKEN") # Advanced configuration with custom settings client = Client( token="YOUR_API_TOKEN", api_endpoint="https://api.hetzner.cloud/v1", application_name="my-app", application_version="1.0.0", poll_interval=2.0, # Seconds between action status polls poll_max_retries=120, # Maximum polling attempts timeout=(5.0, 30.0) # Connection and read timeouts ) ``` -------------------------------- ### Server Creation API Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Create new cloud servers with specified hardware configuration, operating system image, and optional networking settings. The response includes the created server object, its root password, and an action object. ```APIDOC ## POST /servers ### Description Create new cloud servers with specified hardware configuration, operating system image, and optional networking settings. ### Method `POST` ### Endpoint `/servers` ### Parameters #### Request Body - **name** (str) - Required - The name of the server. - **server_type** (ServerType object or str) - Required - The type of the server (e.g., `cx22`). Can be a `ServerType` object or its name. - **image** (Image object or str) - Required - The operating system image for the server (e.g., `ubuntu-24.04`). Can be an `Image` object or its name. - **ssh_keys** (list of SSHKey objects or IDs) - Optional - A list of SSH keys to add to the server. - **location** (Location object or str) - Optional - The datacenter location for the server (e.g., `nbg1`). Can be a `Location` object or its name. - **user_data** (str) - Optional - User data script to be executed on first boot. - **labels** (dict) - Optional - A dictionary of labels to assign to the server. - **automount** (bool) - Optional - Whether to automatically mount the primary disk. Defaults to `True`. - **start_after_create** (bool) - Optional - Whether to start the server immediately after creation. Defaults to `True`. ### Request Example ```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 client = Client(token="YOUR_API_TOKEN") # Create a basic server response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) server = response.server root_password = response.root_password action = response.action print(f"Server ID: {server.id}") print(f"Server Name: {server.name}") print(f"Server Status: {server.status}") print(f"Root Password: {root_password}") # Wait for server to be ready action.wait_until_finished() # Advanced server creation with full configuration response = client.servers.create( name="production-server", server_type=ServerType(name="cx32"), image=Image(name="ubuntu-24.04"), ssh_keys=[SSHKey(name="my-ssh-key")], location=Location(name="nbg1"), user_data="#!/bin/bash\napt-get update\napt-get install -y docker.io", labels={"environment": "production", "team": "backend"}, automount=False, start_after_create=True ) ``` ### Response #### Success Response (201 Created) - **server** (Server object) - The created server object. - **root_password** (str) - The root password for the server. - **action** (Action object) - The action object representing the server creation process. #### Response Example ```json { "server": { "id": 12345, "name": "my-server", "status": "creating", "created": "2023-01-01T10:00:00Z", "public_net": { "ipv4": { "ip": "1.2.3.4", "dns_ptr": "my-server.example.com" }, "ipv6": { "ip": "2001:db8::1", "dns_ptr": "my-server.example.com" } }, "datacenter": { "id": 1, "name": "nbg1", "location": { "id": 1, "name": "Falkenstein", "country": "de", "city": "Falkenstein" } }, "server_type": { "id": 1, "name": "cx22", "description": "2 vCPU, 4 GB RAM", "cores": 2, "memory": 4096, "disk": 40, "prices": [ { "location": "nbg1", "price_hourly": {"currency": "EUR", "amount": "0.0349"}, "price_monthly": {"currency": "EUR", "amount": "10.50"} } ] }, "image": { "id": 1, "type": "distribution", "name": "Ubuntu 24.04 LTS", "description": "Latest Ubuntu 24.04 LTS", "os": "linux", "os_version": "24.04", "architecture": "x86" }, "rescue_enabled": false, "iso_status": "available", "iso_available": true }, "root_password": "very_secret_password", "action": { "id": 123, "command": "create_server", "status": "running", "started": "2023-01-01T10:00:00Z", "finished": null, "resources": { "type": "server", "id": 12345 } } } ``` ``` -------------------------------- ### Build Documentation with Makefile Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Builds the project's documentation using the Makefile and opens it in a web browser for review. This command is useful for checking documentation output during development. ```sh make docs ``` -------------------------------- ### Create and List Servers with hcloud Python Client Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Demonstrates how to use the hcloud Python client to create a new server with specified details (name, type, image) and then lists all existing servers. It requires an API token for authentication. ```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=}") ``` -------------------------------- ### Client Initialization Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Initialize the Hetzner Cloud client with API authentication token and optional configuration parameters such as custom API endpoint, application details, polling intervals, and timeouts. ```APIDOC ## Client Initialization ### Description Initialize the Hetzner Cloud client with API authentication token and optional configuration parameters. ### Method `Client()` ### Parameters #### Constructor Parameters - **token** (str) - Required - Your Hetzner Cloud API token. - **api_endpoint** (str) - Optional - The base URL for the Hetzner Cloud API. Defaults to `https://api.hetzner.cloud/v1`. - **application_name** (str) - Optional - Name of your application for tracking purposes. - **application_version** (str) - Optional - Version of your application. - **poll_interval** (float) - Optional - Seconds between checking action status during polling. Defaults to `0.5`. - **poll_max_retries** (int) - Optional - Maximum number of retries for polling actions. Defaults to `120`. - **timeout** (tuple) - Optional - A tuple of (connect_timeout, read_timeout) in seconds. Defaults to `(5.0, 30.0)`. ### Request Example ```python from hcloud import Client # Basic client initialization client = Client(token="YOUR_API_TOKEN") # Advanced configuration with custom settings client = Client( token="YOUR_API_TOKEN", api_endpoint="https://api.hetzner.cloud/v1", application_name="my-app", application_version="1.0.0", poll_interval=2.0, # Seconds between action status polls poll_max_retries=120, # Maximum polling attempts timeout=(5.0, 30.0) # Connection and read timeouts ) ``` ``` -------------------------------- ### List and Filter Hetzner Cloud Servers Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Demonstrates how to retrieve lists of Hetzner Cloud servers with options for filtering. Includes fetching all servers, filtering by name, and filtering by label selectors. Supports pagination implicitly through the API. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Get all servers servers = client.servers.get_all() for server in servers: print(f"ID: {server.id}, Name: {server.name}, Status: {server.status}") # Filter servers by name servers = client.servers.get_all(name="production-server") # Filter by label selector servers = client.servers.get_all( label_selector="environment=production,team=backend" ) ``` -------------------------------- ### Annotate Experimental Python Code Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md This snippet shows the required docstring format to mark experimental features in Python classes and functions. It includes placeholders for product name, maturity level, and a changelog slug, along with a link to the changelog for more details. Ensure the $PRODUCT, $MATURITY, and $SLUG variables are correctly substituted. ```python """ Experimental: $PRODUCT is $MATURITY, breaking changes may occur within minor releases. See https://docs.hetzner.cloud/changelog#$SLUG for more details. """ ``` -------------------------------- ### Retrieve Server Type and Pricing Information with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt This snippet demonstrates how to fetch details about available server types, including their specifications like cores, memory, disk, and architecture. It also shows how to retrieve pricing information (hourly and monthly) for specific server types and filter server types by name patterns. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # List all server types server_types = client.server_types.get_all() for st in server_types: print(f"{st.name}:") print(f" Cores: {st.cores}") print(f" Memory: {st.memory} GB") print(f" Disk: {st.disk} GB") print(f" Description: {st.description}") print(f" Architecture: {st.architecture}") # Get specific server type server_type = client.server_types.get_by_name("cx22") print(f"Hourly price: €{server_type.prices[0].price_hourly.gross}") print(f"Monthly price: €{server_type.prices[0].price_monthly.gross}") # Filter by name pattern server_types = client.server_types.get_all(name="cx*") ``` -------------------------------- ### Manage Server Images (Create, List, Delete) Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Provides functionality to manage server images, including creating snapshots and backups from servers, listing all available images, filtering images by type or labels, and deleting unwanted images. ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Create snapshot from server server = client.servers.get_by_name("my-server") response = server.create_image( description="Backup before update", type="snapshot", labels={"backup": "pre-deployment"} ) image = response.image action = response.action action.wait_until_finished() print(f"Image ID: {image.id}") print(f"Image Name: {image.name}") # List all images images = client.images.get_all() for image in images: print(f"{image.id}: {image.name} ({image.type})") # Filter images custom_images = client.images.get_all( type=["snapshot"], label_selector="backup=pre-deployment" ) # Get image by name image = client.images.get_by_name("ubuntu-24.04") # Update image properties image.update( description="Updated description", labels={"reviewed": "true"} ) # Delete image image.delete() ``` -------------------------------- ### Main Interface - hcloud.Client Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/api.rst Documentation for the main HCloud client class, detailing its members and methods for interacting with the API. ```APIDOC ## hcloud.Client ### Description This class serves as the main interface for interacting with the Hetzner Cloud API. It provides methods to manage various resources and perform actions. ### Members This section details the available methods and attributes within the `hcloud.Client` class. ``` -------------------------------- ### Resource Locations and Datacenters Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Query available locations and datacenters for resource placement. Includes listing all locations and datacenters, and retrieving specific ones by name. ```APIDOC ## Resource Locations and Datacenters ### Description Query available locations and datacenters for resource placement. Includes listing all locations and datacenters, and retrieving specific ones by name. ### List all locations ```python locations = client.locations.get_all() for location in locations: print(f"{location.name}: {location.description} ({location.country})") print(f" City: {location.city}") print(f" Network Zone: {location.network_zone}") ``` ### Get specific location ```python location = client.locations.get_by_name("nbg1") ``` ### List all datacenters ```python datacenters = client.datacenters.get_all() for dc in datacenters: print(f"{dc.name}: {dc.location.name}") print(f" Supported server types: {dc.supported_types}") ``` ### Get datacenter by name ```python datacenter = client.datacenters.get_by_name("nbg1-dc3") ``` ``` -------------------------------- ### Configure Private Networks and Subnets Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Demonstrates the creation and management of private networks for inter-resource communication. This includes defining IP ranges, adding subnets, attaching servers to networks with specific IPs, adding routes, detaching servers, and deleting networks. ```python from hcloud import Client from hcloud.networks import NetworkSubnet client = Client(token="YOUR_API_TOKEN") # Create 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 ID: {network.id}") print(f"IP Range: {network.ip_range}") # Add subnet to network action = network.add_subnet( NetworkSubnet( type="cloud", network_zone="eu-central", ip_range="10.0.1.0/24" ) ) action.wait_until_finished() # Attach server to network server = client.servers.get_by_name("my-server") action = network.attach_server( server=server, ip="10.0.1.10" ) action.wait_until_finished() # Add route to network action = network.add_route( destination="192.168.1.0/24", gateway="10.0.1.1" ) action.wait_until_finished() # Detach server from network action = network.detach_server(server) action.wait_until_finished() # Delete network network.delete() ``` -------------------------------- ### Run Tests with Makefile Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Executes the project's tests using the current Python 3 version via the Makefile. This is a fundamental step for verifying code correctness. ```sh make test ``` -------------------------------- ### Clone Repository Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/CONTRIBUTING.rst Command to clone your forked repository locally for development. This is the first step after forking the project on GitHub. ```bash git clone git@github.com:your_name_here/hcloud-python.git ``` -------------------------------- ### Firewall Configuration with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Create, manage, and apply firewall rules to control network traffic. This involves defining rules with protocols, ports, and IP ranges, and associating them with servers. Requires a Hetzner Cloud client instance. ```python from hcloud import Client from hcloud.firewalls import FirewallRule client = Client(token="YOUR_API_TOKEN") rules = [ FirewallRule( direction="in", protocol="tcp", port="22", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow SSH" ), FirewallRule( direction="in", protocol="tcp", port="80", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow HTTP" ), FirewallRule( direction="in", protocol="tcp", port="443", source_ips=["0.0.0.0/0", "::/0"], destination_ips=[], description="Allow HTTPS" ) ] response = client.firewalls.create( name="web-firewall", rules=rules, labels={"type": "web"} ) firewall = response.firewall server = client.servers.get_by_name("my-server") actions = firewall.apply_to_resources([server]) for action in actions: action.wait_until_finished() new_rule = FirewallRule( direction="in", protocol="tcp", port="3306", source_ips=["10.0.0.0/8"], destination_ips=[], description="Allow MySQL from private network" ) actions = firewall.set_rules(rules + [new_rule]) for action in actions: action.wait_until_finished() actions = firewall.remove_from_resources([server]) for action in actions: action.wait_until_finished() ``` -------------------------------- ### Server Listing and Filtering API Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Retrieve a list of all servers or filter them based on name or labels. Supports pagination for large numbers of servers. ```APIDOC ## GET /servers ### Description Retrieve and filter servers with pagination support and label-based queries. ### Method `GET` ### Endpoint `/servers` ### Parameters #### Query Parameters - **name** (str) - Optional - Filter servers by name. - **label_selector** (str) - Optional - Filter servers by label selector (e.g., `environment=production,team=backend`). - **page** (int) - Optional - Page number for pagination. - **per_page** (int) - Optional - Number of items per page for pagination. ### Request Example ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Get all servers servers = client.servers.get_all() for server in servers: print(f"ID: {server.id}, Name: {server.name}, Status: {server.status}") # Filter servers by name servers = client.servers.get_all(name="production-server") # Filter by label selector servers = client.servers.get_all( label_selector="environment=production,team=backend" ) # Filter with pagination servers = client.servers.get_all(page=2, per_page=50) ``` ### Response #### Success Response (200 OK) - **servers** (list of Server objects) - A list of server objects matching the query. - **meta** (dict) - Metadata for pagination, including `pagination` details. #### Response Example ```json { "servers": [ { "id": 12345, "name": "production-server", "status": "running", "created": "2023-01-01T10:00:00Z", "public_net": { "ipv4": {"ip": "1.2.3.4", "dns_ptr": "production-server.example.com"} }, "server_type": {"name": "cx32", "cores": 4, "memory": 8192}, "image": {"name": "Ubuntu 24.04 LTS"}, "labels": {"environment": "production", "team": "backend"} } // ... more servers ], "meta": { "pagination": { "page": 1, "per_page": 25, "total_entries": 100, "next_page": 2, "previous_page": null, "last_page": 4 } } } ``` ``` -------------------------------- ### API Clients Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/docs/api.rst This section provides an overview of the different API clients available within the library, organized by their functionality. ```APIDOC ## API Clients ### Description The `api.clients.*` module contains specialized clients for different aspects of the Hetzner Cloud API. These clients offer methods to interact with specific resources like servers, networks, volumes, etc. ### Sub-modules - `api.clients.servers` - `api.clients.networks` - `api.clients.volumes` - (and other resource-specific clients) ``` -------------------------------- ### Manage Floating IPs (Allocate, Assign) Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Facilitates the allocation and management of floating IP addresses for high availability and flexible server assignment. This includes creating IPv4 floating IPs with descriptions and labels, and preparing for assignment to servers. ```python from hcloud import Client from hcloud.floating_ips import FloatingIP from hcloud.locations import Location client = Client(token="YOUR_API_TOKEN") # Create IPv4 floating IP response = client.floating_ips.create( type="ipv4", home_location=Location(name="nbg1"), description="Web server IP", labels={"service": "web"} ) floating_ip = response.floating_ip print(f"Floating IP: {floating_ip.ip}") print(f"Floating IP ID: {floating_ip.id}") ``` -------------------------------- ### Error Handling and Exceptions Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Handle API errors and exceptions with proper error recovery strategies. Demonstrates catching specific API exceptions, general HCloud exceptions, and handling specific error codes like rate limits or invalid input. ```APIDOC ## Error Handling and Exceptions ### Description Handle API errors and exceptions with proper error recovery strategies. Demonstrates catching specific API exceptions, general HCloud exceptions, and handling specific error codes like rate limits or invalid input. ### Example with server creation and error handling ```python from hcloud import Client, APIException, HCloudException from hcloud.actions import ActionFailedException, ActionTimeoutException import time client = Client(token="YOUR_API_TOKEN") try: # Attempt to create a server response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) # Wait for completion with timeout handling try: response.action.wait_until_finished(max_retries=60) except ActionTimeoutException: print("Server creation is taking longer than expected") # Continue polling or cancel except ActionFailedException as e: print(f"Server creation failed: {e.action.error.message}") 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 limited, waiting before retry") time.sleep(60) elif e.code == "resource_limit_exceeded": print("Resource limit reached") elif e.code == "invalid_input": print(f"Invalid input: {e.details}") except HCloudException as e: print(f"General HCloud error: {e}") ``` ``` -------------------------------- ### Lint Code with Makefile Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Runs code linting checks using the Makefile to ensure code style and quality standards are met. ```sh make lint ``` -------------------------------- ### Retrieve Server Metrics (CPU, Network, Disk) Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Fetches time-series metrics for server resource utilization, including CPU, network traffic (in/out), and disk I/O. It supports specifying a time range and resolution for the metrics. ```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") # Define time range for metrics end = datetime.now(timezone.utc) start = end - timedelta(hours=24) # Get CPU and network metrics response = server.get_metrics( type=["cpu", "network"], start=start, end=end, step=3600 # 1-hour resolution in seconds ) metrics = response.metrics cpu_metrics = metrics.time_series["cpu"] network_metrics = metrics.time_series["network"] print(f"CPU values: {cpu_metrics['values']}") print(f"Network in values: {network_metrics['values'][0]}") print(f"Network out values: {network_metrics['values'][1]}") # Get disk metrics response = server.get_metrics( type=["disk"], start=start, end=end ) ``` -------------------------------- ### Manage Persistent Volumes (Create, Attach, Detach, Resize, Delete) Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Enables management of persistent block storage volumes. This includes creating volumes with specified size and format, attaching them to servers, detaching them, resizing existing volumes, and deleting them when no longer needed. ```python from hcloud import Client from hcloud.locations import Location client = Client(token="YOUR_API_TOKEN") # Create a volume response = client.volumes.create( size=100, # Size in GB name="database-volume", location=Location(name="nbg1"), labels={"purpose": "database"}, automount=True, format="ext4" ) volume = response.volume action = response.action action.wait_until_finished() print(f"Volume ID: {volume.id}") print(f"Linux device: {volume.linux_device}") # Attach volume to server server = client.servers.get_by_name("my-server") action = volume.attach(server, automount=True) action.wait_until_finished() # Detach volume action = volume.detach() action.wait_until_finished() # Resize volume action = volume.resize(150) # New size in GB action.wait_until_finished() # Delete volume volume.delete() ``` -------------------------------- ### Run Tests with Tox for Multiple Python Versions Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/README.md Utilizes Tox to run tests across multiple Python versions, ensuring compatibility and stability. ```sh tox . ``` -------------------------------- ### Floating IP Management with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Manage floating IP addresses, including assigning to servers, unassigning, updating details, and deleting. Requires a Hetzner Cloud client instance and a floating IP object. ```python server = client.servers.get_by_name("my-server") action = floating_ip.assign(server) action.wait_until_finished() action = floating_ip.unassign() action.wait_until_finished() floating_ip.update( description="Updated description", labels={"service": "api"} ) floating_ip.delete() ``` -------------------------------- ### Handle API Exceptions and Timeouts in hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt This snippet provides comprehensive error handling for Hetzner Cloud API interactions. It demonstrates how to catch and process various exceptions, including general API errors, specific error codes like rate limits or invalid input, and action-specific exceptions like timeouts or failures during server creation. It also includes strategies for retrying requests after delays. ```python from hcloud import Client, APIException, HCloudException from hcloud.actions import ActionFailedException, ActionTimeoutException from hcloud.images import Image from hcloud.server_types import ServerType import time client = Client(token="YOUR_API_TOKEN") try: # Attempt to create a server response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) # Wait for completion with timeout handling try: response.action.wait_until_finished(max_retries=60) except ActionTimeoutException: print("Server creation is taking longer than expected") # Continue polling or cancel except ActionFailedException as e: print(f"Server creation failed: {e.action.error.message}") 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 limited, waiting before retry") time.sleep(60) elif e.code == "resource_limit_exceeded": print("Resource limit reached") elif e.code == "invalid_input": print(f"Invalid input: {e.details}") except HCloudException as e: print(f"General HCloud error: {e}") ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/fahreddinozcan/hcloud-python-test26/blob/main/CONTRIBUTING.rst Commands to stage, commit, and push your local changes to your forked repository on GitHub. This makes your changes visible for a pull request. ```bash git add . git commit -m "Your detailed description of your changes." git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Server Management Operations API Source: https://context7.com/fahreddinozcan/hcloud-python-test26/llms.txt Perform various management operations on existing servers, including power cycles, reboots, shutdowns, password resets, enabling/disabling rescue mode, and deletion. These operations often return an action object that can be polled for completion. ```APIDOC ## Server Management Operations ### Description Manage server lifecycle with power operations, updates, and configuration changes. ### Method Various (e.g., `GET`, `PUT`, `DELETE` on server resource) ### Endpoints - `/servers/{id}` or `/servers?name={name}` - Specific actions on server objects. ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the server. - **name** (str) - Required - The name of the server. #### Request Body (for update operations) - **name** (str) - Optional - New name for the server. - **labels** (dict) - Optional - New labels for the server. ### Request Example ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Get server by name or ID server = client.servers.get_by_name("my-server") # Or: server = client.servers.get_by_id(12345) # Power operations server.power_off().wait_until_finished() # Force power off server.power_on().wait_until_finished() # Power on server.reboot().wait_until_finished() # Graceful reboot server.shutdown().wait_until_finished() # Graceful shutdown server.reset().wait_until_finished() # Hard reset # Update server properties server.update( name="renamed-server", labels={"environment": "staging"} ) # Reset root password response = server.reset_password() new_password = response.root_password print(f"New root password: {new_password}") # Enable rescue mode response = server.enable_rescue( type="linux64", ssh_keys=[123, 456] # SSH key IDs ) rescue_password = response.root_password print(f"Rescue password: {rescue_password}") # Disable rescue mode server.disable_rescue().wait_until_finished() # Delete server server.delete().wait_until_finished() ``` ### Response #### Success Response (200 OK or 204 No Content) Responses vary depending on the operation. Power operations, reboots, shutdowns, rescue mode changes, and deletions typically return an `Action` object upon initiation. Updates return the modified `Server` object. #### Response Example (for `reset_password`) ```json { "root_password": "new_very_secret_password" } ``` #### Response Example (for power operations, reboots, etc. - returns an Action) ```json { "action": { "id": 456, "command": "power_off", "status": "running", "started": "2023-01-01T11:00:00Z", "finished": null, "resources": { "type": "server", "id": 12345 } } } ``` ```