### Install Hetzner Cloud Python from source using git clone Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library by cloning the source code from the GitHub repository and then using pip to install it. ```shell git clone git://github.com/hetznercloud/hcloud-python pip install . ``` -------------------------------- ### Install Hetzner Cloud Python from source using tarball Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library by downloading the source code as a tarball from GitHub and then using pip to install it. ```shell curl -OL https://github.com/hetznercloud/hcloud-python/tarball/main pip install . ``` -------------------------------- ### Install Hetzner Cloud Python using pip Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/installation.rst Installs the latest stable release of the Hetzner Cloud Python library using pip. This is the recommended installation method. Ensure you have pip installed. ```shell pip install hcloud ``` -------------------------------- ### Install and Use Hetzner Cloud Python Library Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Installs the 'hcloud' library using pip and provides a Python example to create a server, print its details and root password, and then list all existing servers. Requires an API token for authentication. ```sh 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 Development Environment with Virtualenv and Pre-commit Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Sets up a Python virtual environment using 'make venv' and activates it. It also demonstrates how to install 'pre-commit' for automated code linting before commits. ```sh make venv source venv/bin/activate pre-commit install ``` -------------------------------- ### Install Hetzner Cloud Python using conda Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library using conda-forge. Note that this package is third-party and may not be up-to-date. ```shell conda install -c conda-forge hcloud ``` -------------------------------- ### Hetzner Cloud Firewall Management with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Provides examples for creating firewalls with specific rules (inbound/outbound TCP), applying them to servers or by label selector, updating rules, removing them from resources, and deleting firewalls using the hcloud-python library. ```python from hcloud import Client from hcloud.firewalls import Firewall, FirewallRule, FirewallResource client = Client(token="your_api_token_here") # Create firewall with 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" ) ] response = client.firewalls.create( name="web-firewall", rules=rules, labels={"type": "web"} ) firewall = response.firewall print(f"Created firewall: {firewall.id}") # Apply firewall to server server = client.servers.get_by_name("my-server") actions = firewall.apply_to_resources([ FirewallResource(type="server", server=server) ]) for action in actions: action.wait_until_finished() # Apply firewall to servers by label selector actions = firewall.apply_to_resources([ FirewallResource( type="label_selector", label_selector={"selector": "env=production"} ) ]) # Get all firewalls firewalls = client.firewalls.get_all() for fw in firewalls: print(f"{fw.name}: {len(fw.rules)} rules") for rule in fw.rules: print(f" {rule.direction} {rule.protocol}:{rule.port} - {rule.description}") # 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" ) ] actions = firewall.set_rules(new_rules) for action in actions: action.wait_until_finished() # Remove firewall from resources actions = firewall.remove_from_resources([ FirewallResource(type="server", server=server) ]) for action in actions: action.wait_until_finished() # Delete firewall firewall.delete() ``` -------------------------------- ### Server Management - List and Get Servers Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Retrieves servers from your account with optional filtering by status or labels, and supports pagination for large result sets. Servers can also be retrieved by their name or ID. ```APIDOC ## GET /servers ### Description Retrieves a list of servers from your Hetzner Cloud account. Supports filtering by server status, label selectors, and pagination. You can also retrieve a specific server by its name or ID. ### Method `GET` ### Endpoint `/servers` ### Parameters #### Query Parameters - **status** (list of str) - Optional - Filters servers by their status (e.g., `["running"]`). Possible values: `creating`, `rebooting`, `running`, `stopping`, `stopped`, `deleting`. - **label_selector** (str) - Optional - Filters servers by label selector (e.g., `"env=production"`). - **page** (int) - Optional - Page number for pagination. Defaults to `1`. - **per_page** (int) - Optional - Number of servers per page. Defaults to `25`. ### Request Example ```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}") # Get servers with filtering running_servers = client.servers.get_all(status=["running"]) labeled_servers = client.servers.get_all(label_selector="env=production") # Get paginated list of servers result = client.servers.get_list(page=1, per_page=10) for server in result.servers: print(f"{server.name}: {server.status}") print(f"Total pages: {result.meta.pagination.total_entries // result.meta.pagination.per_page}") # Get server by name server = client.servers.get_by_name("my-server") if server: print(f"Found server: {server.id}") # Get server by ID server = client.servers.get_by_id(123456) print(f"Server: {server.name}") ``` ### Response #### Success Response (200) - **servers** (list of Server objects) - A list of server objects matching the query. - **meta.pagination** (Pagination object) - Pagination details including total entries and per page count. #### Response Example ```json { "servers": [ { "id": 1234567, "name": "my-server", "status": "running", "created": "2023-10-27T10:00:00Z", "public_net": { "ipv4": { "ip": "192.0.2.1", "dns_ptr": "my-server.example.com" }, "ipv6": { "ip": "2001:db8::1", "dns_ptr": "my-server.example.com" } }, "server_type": { "id": 1, "name": "cx22", "cores": 2, "ram": 4096, "disk": 40000, "cpu_type": "shared" }, "image": { "id": 123, "type": "appliance", "name": "ubuntu-24.04", "os_flavor": "ubuntu" }, "datacenter": { "id": 1, "name": "nbg1", "location": { "id": 1, "name": "nuernberg", "country": "de", "city": "Nuremberg" } } } ], "meta": { "pagination": { "page": 1, "per_page": 10, "total_entries": 50 } } } ``` ``` -------------------------------- ### Query and Monitor Actions with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt This snippet illustrates how to fetch and monitor asynchronous actions performed on Hetzner Cloud resources using the hcloud-python library. It covers retrieving all actions, filtering them by status or sorting, getting a specific action by its ID, and waiting for an action to complete. Requires the 'hcloud' library and an API token. ```python from hcloud import Client client = Client(token="your_api_token_here") # Get all actions actions = client.actions.get_all() for action in actions: print(f"Action {action.id}: {action.command} - {action.status}") print(f" Started: {action.started}") if action.finished: print(f" Finished: {action.finished}") print(f" Progress: {action.progress}%") # Get actions with filtering running_actions = client.actions.get_all(status=["running"]) sorted_actions = client.actions.get_all(sort=["id:desc"]) # Get specific action by ID action = client.actions.get_by_id(123456) print(f"Action status: {action.status}") # Wait for action to complete # action.wait_until_finished(max_retries=100) # print(f"Action completed with status: {action.status}") ``` -------------------------------- ### Raise Deprecation Warning in Python Code Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Demonstrates how to raise a `DeprecationWarning` in Python when a deprecated function or method 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, ) ``` -------------------------------- ### List and Get Hetzner Cloud Servers (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Retrieves Hetzner Cloud servers with options for filtering by status or labels, pagination, and direct retrieval by name or ID. Displays server details including IP addresses, type, and location. ```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" IPv4: {server.public_net.ipv4.ip if server.public_net.ipv4 else 'None'}") print(f" IPv6: {server.public_net.ipv6.ip if server.public_net.ipv6 else 'None'}") print(f" Type: {server.server_type.name}") print(f" Location: {server.datacenter.location.name}") # Get servers with filtering running_servers = client.servers.get_all(status=["running"]) labeled_servers = client.servers.get_all(label_selector="env=production") # Get paginated list of servers result = client.servers.get_list(page=1, per_page=10) for server in result.servers: print(f"{server.name}: {server.status}") print(f"Total pages: {result.meta.pagination.total_entries // result.meta.pagination.per_page}") # Get server by name server = client.servers.get_by_name("my-server") if server: print(f"Found server: {server.id}") # Get server by ID server = client.servers.get_by_id(123456) print(f"Server: {server.name}") ``` -------------------------------- ### Volume Management with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Shows how to create, get, attach, detach, resize, update, enable/disable delete protection, and delete block storage volumes using the hcloud-python SDK. Requires a valid API token and an existing server name for attachment. ```python from hcloud import Client from hcloud.volumes import Volume from hcloud.locations import Location client = Client(token="your_api_token_here") # Create a new volume response = client.volumes.create( size=10, # Size in GB name="my-volume", labels={"env": "production"}, location=Location(name="nbg1"), format="ext4" # Automatically format ) volume = response.volume action = response.action action.wait_until_finished() print(f"Created volume: {volume.id} at {volume.location.name}") # Get all volumes volumes = client.volumes.get_all() for vol in volumes: print(f"{vol.name}: {vol.size}GB, Status: {vol.status}") # Get volume by name volume = client.volumes.get_by_name("my-volume") # Attach volume to server server = client.servers.get_by_name("my-server") action = volume.attach(server, automount=True) action.wait_until_finished() print(f"Volume attached to {server.name}") # Detach volume action = volume.detach() action.wait_until_finished() # Resize volume (cannot shrink, only grow) action = volume.resize(size=20) # Increase to 20GB action.wait_until_finished() # Update volume properties volume = volume.update( name="renamed-volume", labels={"env": "staging"} ) # Enable delete protection action = volume.change_protection(delete=True) action.wait_until_finished() # Delete volume volume.change_protection(delete=False).wait_until_finished() volume.delete() ``` -------------------------------- ### Hetzner Cloud Floating IP Management with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Shows how to create, retrieve, assign, unassign, update, and delete floating IP addresses (IPv4 and IPv6) using the hcloud-python library. Includes examples for reverse DNS and delete protection. ```python from hcloud import Client from hcloud.floating_ips import FloatingIP from hcloud.locations import Location client = Client(token="your_api_token_here") # Create floating IPv4 response = client.floating_ips.create( type="ipv4", description="Web server IP", home_location=Location(name="nbg1"), labels={"service": "web"} ) floating_ip = response.floating_ip print(f"Created floating IP: {floating_ip.ip}") # Create floating IPv6 response = client.floating_ips.create( type="ipv6", description="IPv6 for web server", home_location=Location(name="fsn1") ) floating_ipv6 = response.floating_ip print(f"Created floating IPv6: {floating_ipv6.ip}") # Get all floating IPs floating_ips = client.floating_ips.get_all() for fip in floating_ips: print(f"{fip.ip}: {fip.description}, Assigned: {fip.server.name if fip.server else 'None'}") # Assign floating IP to server server = client.servers.get_by_name("my-server") action = floating_ip.assign(server) action.wait_until_finished() print(f"Assigned {floating_ip.ip} to {server.name}") # Unassign floating IP action = floating_ip.unassign() action.wait_until_finished() # Change reverse DNS entry action = floating_ip.change_dns_ptr( ip=floating_ip.ip, dns_ptr="server.example.com" ) action.wait_until_finished() # Update floating IP floating_ip = floating_ip.update( description="Production web server IP", labels={"env": "production", "service": "web"} ) # Enable delete protection action = floating_ip.change_protection(delete=True) action.wait_until_finished() # Delete floating IP floating_ip.change_protection(delete=False).wait_until_finished() floating_ip.delete() ``` -------------------------------- ### Configure Client Poll Interval During Initialization Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/upgrading.md This snippet illustrates a change in how the `Client.poll_interval` property is handled. It is now a private property and must be configured during the `Client` initialization instead of being set after the client object is created. This ensures proper client configuration from the start. ```diff -client = Client(token=token) -client.poll_interval = 2 +client = Client( + token=token, + poll_interval=2, +) ``` -------------------------------- ### Manage SSH Keys with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt This snippet demonstrates how to create, retrieve, update, and delete SSH keys using the hcloud-python library. It requires the 'hcloud' library and an API token. The code shows getting keys by name, fetching all keys, and updating key properties like name and labels. ```python from hcloud import Client client = Client(token="your_api_token_here") # Create SSH key ssh_key = client.ssh_keys.create( name="my-ssh-key", public_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDi...", labels={"user": "john"} ) print(f"Created SSH key: {ssh_key.id}") # Get all SSH keys ssh_keys = client.ssh_keys.get_all() for key in ssh_keys: print(f"{key.name}: {key.fingerprint}") # Get SSH key by name ssh_key = client.ssh_keys.get_by_name("my-ssh-key") # Update SSH key ssh_key = ssh_key.update( name="renamed-key", labels={"user": "jane", "env": "production"} ) # Delete SSH key # ssh_key.delete() # Uncomment to delete ``` -------------------------------- ### Build and View Documentation Locally Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Builds the project's documentation locally using the 'make docs' command and automatically opens it in a web browser for review. ```sh make docs ``` -------------------------------- ### Server Management - Create Server Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Creates a new cloud server with specified configuration. Supports basic creation with name, server type, and image, as well as advanced creation with SSH keys, networks, firewalls, labels, user data, and automatic startup. ```APIDOC ## POST /servers ### Description Creates a new cloud server with the specified configuration. Supports basic creation with name, server type, and image, as well as advanced creation with SSH keys, networks, firewalls, labels, user data, and automatic startup. The response includes the created server object, an action object representing the creation process, and the root password if applicable. ### Method `POST` ### Endpoint `/servers` ### Parameters #### Request Body - **name** (str) - Required - The name of the server. - **server_type** (ServerType object or str) - Required - The server type (e.g., `ServerType(name='cx22')` or `'cx22'`). - **image** (Image object or str) - Required - The image to use for the server (e.g., `Image(name='ubuntu-24.04')` or `'ubuntu-24.04'`). - **ssh_keys** (list of SSHKey objects or int) - Optional - A list of SSH keys to add to the server (e.g., `[SSHKey(name='my-ssh-key')]` or `[12345]`). - **networks** (list of Network objects or int) - Optional - A list of networks to connect the server to (e.g., `[Network(id=12345)]`). - **firewalls** (list of Firewall objects or int) - Optional - A list of firewalls to assign to the server (e.g., `[Firewall(id=67890)]`). - **labels** (dict) - Optional - A dictionary of labels to assign to the server (e.g., `{"env": "production"}`). - **user_data** (str) - Optional - User data script to run on server startup. - **start_after_create** (bool) - Optional - Whether to start the server immediately after creation. Defaults to `True`. - **automount** (bool) - Optional - Whether to automatically mount the primary disk. Defaults to `True`. ### Request Example ```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 from hcloud.firewalls import Firewall client = Client(token="your_api_token_here") # Basic server creation response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) # Advanced server creation response = client.servers.create( name="production-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04"), ssh_keys=[SSHKey(name="my-ssh-key")], networks=[Network(id=12345)], firewalls=[Firewall(id=67890)], labels={"env": "production", "app": "webserver"}, user_data="#!/bin/bash\napt-get update\napt-get install -y nginx", start_after_create=True, automount=True ) # Wait for server creation to complete response.action.wait_until_finished() print(f"Server {response.server.name} is ready!") ``` ### Response #### Success Response (200) - **server** (Server object) - The created server object. - **action** (Action object) - The action object representing the server creation process. - **root_password** (str) - The root password for the server (if generated). #### Response Example ```json { "server": { "id": 1234567, "name": "my-server", "status": "creating", "created": "2023-10-27T10:00:00Z", "public_net": { "ipv4": { "ip": "192.0.2.1", "dns_ptr": "my-server.example.com" }, "ipv6": { "ip": "2001:db8::1", "dns_ptr": "my-server.example.com" } }, "server_type": { "id": 1, "name": "cx22", "cores": 2, "ram": 4096, "disk": 40000, "cpu_type": "shared" }, "image": { "id": 123, "type": "appliance", "name": "ubuntu-24.04", "os_flavor": "ubuntu" }, "datacenter": { "id": 1, "name": "nbg1", "location": { "id": 1, "name": "nuernberg", "country": "de", "city": "Nuremberg" } } }, "action": { "id": 98765, "command": "create_server", "status": "running", "started_at": "2023-10-27T10:00:05Z", "completed_at": null }, "root_password": "example_root_password" } ``` ``` -------------------------------- ### Create Hetzner Cloud Server (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Creates a new Hetzner Cloud server with basic or advanced configurations. Supports specifying server type, image, SSH keys, networks, firewalls, labels, user data, and waiting for completion. ```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 from hcloud.firewalls import Firewall client = Client(token="your_api_token_here") # Basic server creation response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04") ) server = response.server action = response.action root_password = response.root_password print(f"Server ID: {server.id}") print(f"Server Name: {server.name}") print(f"Server Status: {server.status}") print(f"Root Password: {root_password}") print(f"Public IPv4: {server.public_net.ipv4.ip}") print(f"Public IPv6: {server.public_net.ipv6.ip}") # Advanced server creation with SSH keys, networks, and firewalls response = client.servers.create( name="production-server", server_type=ServerType(name="cx22"), image=Image(name="ubuntu-24.04"), ssh_keys=[SSHKey(name="my-ssh-key")], networks=[Network(id=12345)], firewalls=[Firewall(id=67890)], labels={"env": "production", "app": "webserver"}, user_data="#!/bin/bash\napt-get update\napt-get install -y nginx", start_after_create=True, automount=True ) # Wait for server creation to complete response.action.wait_until_finished() print(f"Server {response.server.name} is ready!") ``` -------------------------------- ### Lint Codebase with Makefile Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Runs the code linting process for the project using the 'make lint' command, which helps ensure code quality and consistency. ```sh make lint ``` -------------------------------- ### Client Initialization Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Initializes the Hetzner Cloud client with your API token for authentication. Supports custom configurations for API endpoint, application details, polling, and timeouts. ```APIDOC ## Client Initialization ### Description Initialize the Hetzner Cloud client with your API token to authenticate all subsequent requests. Supports custom configurations for API endpoint, application details, polling interval, polling max retries, and request timeout. ### Method `Client` class constructor ### Parameters #### Initialization Parameters - **token** (str) - Required - Your Hetzner Cloud API token. - **api_endpoint** (str) - Optional - The API endpoint URL. Defaults to `https://api.hetzner.cloud/v1`. - **application_name** (str) - Optional - The name of your application. - **application_version** (str) - Optional - The version of your application. - **poll_interval** (float) - Optional - Seconds between action polling. Defaults to `0.5`. - **poll_max_retries** (int) - Optional - Maximum retries for action polling. Defaults to `120`. - **timeout** (float) - Optional - Request timeout in seconds. Defaults to `60.0`. ### Request Example ```python from hcloud import Client # Initialize client with API token client = Client(token="your_api_token_here") # Initialize with custom configuration client = Client( token="your_api_token_here", api_endpoint="https://api.hetzner.cloud/v1", application_name="MyApp", application_version="1.0.0", poll_interval=1.0, poll_max_retries=120, timeout=60.0 ) ``` ``` -------------------------------- ### Server Lifecycle Operations with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Demonstrates performing power control (on, off, reboot, shutdown), resetting the root password, rebuilding with a new image, resizing, enabling rescue mode, and deleting servers using the hcloud-python SDK. Requires a valid API token and an existing server name. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType client = Client(token="your_api_token_here") server = client.servers.get_by_name("my-server") # Power operations action = server.power_on() action.wait_until_finished() action = server.power_off() action.wait_until_finished() action = server.reboot() action.wait_until_finished() action = server.shutdown() # Graceful shutdown action.wait_until_finished() # Reset root password response = server.reset_password() print(f"New root password: {response.root_password}") response.action.wait_until_finished() # Rebuild server with new image response = server.rebuild(Image(name="ubuntu-22.04")) print(f"New root password: {response.root_password}") response.action.wait_until_finished() # Resize server (must be powered off first) server.power_off().wait_until_finished() action = server.change_type( server_type=ServerType(name="cx32"), upgrade_disk=True ) action.wait_until_finished() server.power_on().wait_until_finished() # Enable rescue mode response = server.enable_rescue(type="linux64", ssh_keys=[]) print(f"Root password for rescue: {response.root_password}") response.action.wait_until_finished() # Delete server server.delete() ``` -------------------------------- ### Initialize Hetzner Cloud Client (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Initializes the Hetzner Cloud client using an API token for authentication. Supports custom configurations for API endpoint, application details, polling intervals, and timeouts. ```python from hcloud import Client # Initialize client with API token client = Client(token="your_api_token_here") # Initialize with custom configuration client = Client( token="your_api_token_here", api_endpoint="https://api.hetzner.cloud/v1", # Default endpoint application_name="MyApp", application_version="1.0.0", poll_interval=1.0, # Seconds between action polling poll_max_retries=120, # Max retries for action polling timeout=60.0 # Request timeout in seconds ) ``` -------------------------------- ### Main Interface: hcloud.Client Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/api.rst Details the main interface for interacting with the Hetzner Cloud API using the Python SDK. This includes methods for managing various resources. ```APIDOC ## hcloud.Client ### Description Represents the main interface for interacting with the Hetzner Cloud API. This class provides access to various API clients for managing different resources. ### Method Not applicable (Class definition) ### Endpoint Not applicable (Class definition) ### Parameters This class has various members (methods) that represent API calls. Refer to the specific client documentation for details on parameters for each method. ### Request Example ```python from hcloud import Client # Assuming you have your API token client = Client(token="YOUR_API_TOKEN") # Example of calling a method (e.g., listing servers) servers = client.servers.all() ``` ### Response #### Success Response (200) Responses will vary based on the specific method called. Refer to individual API client documentation for details. #### Response Example ```json // Example response for client.servers.all() { "servers": [ { "id": 12345, "name": "test-server", "status": "running", "created": "2023-10-27T10:00:00Z", "public_net": { "ipv4": { "ip": "192.0.2.1", "dns_ptr": "server.example.com" }, "ipv6": { "ip": "2001:db8::1", "dns_ptr": null } } } ], "meta": { "pagination": { "page": 1, "per_page": 25, "total_page": 1 } } } ``` ``` -------------------------------- ### Network Management with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Illustrates creating private networks, adding subnets with specified IP ranges and zones, and adding routes to define network traffic gateways using the hcloud-python SDK. Requires a valid API token. ```python from hcloud import Client from hcloud.networks import Network, NetworkSubnet, NetworkRoute client = Client(token="your_api_token_here") # Create a private network network = client.networks.create( name="my-network", ip_range="10.0.0.0/16", labels={"env": "production"} ) print(f"Created network: {network.name} with range {network.ip_range}") # Add subnet to network subnet = NetworkSubnet( ip_range="10.0.1.0/24", network_zone="eu-central", type="cloud" ) action = network.add_subnet(subnet) action.wait_until_finished() # Add route to network route = NetworkRoute( destination="10.100.0.0/16", gateway="10.0.1.1" ) action = network.add_route(route) action.wait_until_finished() ``` -------------------------------- ### Create and Configure Load Balancers with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt This snippet shows how to create a load balancer, add HTTP and HTTPS services with health checks, attach server and label selector targets, change the load balancing algorithm, retrieve metrics, and delete the load balancer. It requires the 'hcloud' library and an API token. ```python from hcloud import Client from hcloud.load_balancers import ( LoadBalancer, LoadBalancerService, LoadBalancerServiceHttp, LoadBalancerHealthCheck, LoadBalancerHealthCheckHttp, LoadBalancerTarget, LoadBalancerAlgorithm ) from hcloud.load_balancer_types import LoadBalancerType from hcloud.locations import Location from datetime import datetime, timedelta, timezone client = Client(token="your_api_token_here") # Create load balancer response = client.load_balancers.create( name="web-lb", load_balancer_type=LoadBalancerType(name="lb11"), location=Location(name="nbg1"), labels={"env": "production"} ) load_balancer = response.load_balancer action = response.action action.wait_until_finished() print(f"Created load balancer: {load_balancer.public_net.ipv4.ip}") # Add HTTP service with health check service = LoadBalancerService( protocol="http", listen_port=80, destination_port=8080, proxyprotocol=False, http=LoadBalancerServiceHttp( sticky_sessions=True, cookie_name="LBSESSION", cookie_lifetime=3600, redirect_http=False ), health_check=LoadBalancerHealthCheck( protocol="http", port=8080, interval=15, timeout=10, retries=3, http=LoadBalancerHealthCheckHttp( domain="example.com", path="/health", response="", tls=False, status_codes=["200", "201"] ) ) ) action = load_balancer.add_service(service) action.wait_until_finished() # Add HTTPS service https_service = LoadBalancerService( protocol="https", listen_port=443, destination_port=8443, proxyprotocol=False, http=LoadBalancerServiceHttp( sticky_sessions=True, certificates=[Certificate(id=12345)] # Assuming Certificate class is available ), health_check=LoadBalancerHealthCheck( protocol="https", port=8443, interval=15, timeout=10, retries=3 ) ) action = load_balancer.add_service(https_service) action.wait_until_finished() # Add server targets server1 = client.servers.get_by_name("web-server-1") server2 = client.servers.get_by_name("web-server-2") action = load_balancer.add_target( LoadBalancerTarget(type="server", server=server1, use_private_ip=False) ) action.wait_until_finished() action = load_balancer.add_target( LoadBalancerTarget(type="server", server=server2, use_private_ip=False) ) action.wait_until_finished() # Add label selector target (automatically includes matching servers) action = load_balancer.add_target( LoadBalancerTarget( type="label_selector", label_selector={"selector": "app=web"}, use_private_ip=False ) ) action.wait_until_finished() # Change load balancer algorithm action = load_balancer.change_algorithm( LoadBalancerAlgorithm(type="least_connections") ) action.wait_until_finished() # Get load balancer metrics end = datetime.now(timezone.utc) start = end - timedelta(hours=1) response = load_balancer.get_metrics( type=["open_connections", "requests_per_second"], start=start, end=end ) print(f"Metrics: {response.metrics.time_series.keys()}") # Delete load balancer # load_balancer.delete() # Uncomment to delete ``` -------------------------------- ### Clone Repository for Local Development Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/CONTRIBUTING.rst This command clones your forked 'hcloud-python' repository to your local machine. Ensure you replace 'your_name_here' with your GitHub username. This is the first step in setting up the project for local development. ```shell git clone git@github.com:your_name_here/hcloud-python.git ``` -------------------------------- ### Run Tests with Current Python Version Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Executes the project's test suite using the current active Python interpreter via the 'make test' command. ```sh make test ``` -------------------------------- ### Hetzner Cloud Network Operations with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Demonstrates how to attach and detach servers from networks, retrieve network details, update network properties, and delete subnets and networks using the hcloud-python library. ```python from hcloud import Client client = Client(token="your_api_token_here") network = client.networks.get_by_name("my-network") server = client.servers.get_by_name("my-server") # Attach server to network action = network.attach_to_server(server, ip="10.0.1.5") action.wait_until_finished() # Get all networks networks = client.networks.get_all() for net in networks: print(f"{net.name}: {net.ip_range}") for subnet in net.subnets: print(f" Subnet: {subnet.ip_range}") # Detach server from network action = network.detach_from_server(server) action.wait_until_finished() # Update network network = network.update( name="renamed-network", labels={"env": "staging"}, expose_routes_to_vswitch=True ) # Delete subnet and network action = network.delete_subnet(subnet) action.wait_until_finished() network.delete() ``` -------------------------------- ### Run Tests Across Multiple Python Versions with Tox Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Executes the project's test suite across various Python versions using the 'tox' tool, as defined in the configuration. ```sh tox . ``` -------------------------------- ### Update PrimaryIPs Create Method Argument Order Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/upgrading.md This snippet demonstrates a change in the `Client.primary_ips.create` method's argument order. The `datacenter` argument has been moved to appear after the `name` argument and is now optional. This adjustment allows for more flexible creation of primary IPs. ```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"), ) ``` -------------------------------- ### API Clients Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/api.rst Provides access to specific API client modules for managing different Hetzner Cloud resources, such as servers, networks, and volumes. ```APIDOC ## API Clients ### Description This section details the various API client modules available within the hcloud library. Each client is responsible for managing a specific type of resource within the Hetzner Cloud. ### Method Not applicable (Module overview) ### Endpoint Not applicable (Module overview) ### Parameters Refer to the specific API client documentation within the `api.clients.*` directory for details on parameters and methods for each resource type. ### Request Example ```python from hcloud import Client client = Client(token="YOUR_API_TOKEN") # Accessing the servers client servers_client = client.servers # Accessing the networks client networks_client = client.networks ``` ### Response N/A (Module overview) ### Further Documentation - `api.clients.servers` - `api.clients.networks` - `api.clients.volumes` - etc. ``` -------------------------------- ### Annotate Experimental Python Features Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md This snippet demonstrates how to annotate experimental Python classes and functions. It includes an `Experimental` notice with details about potential breaking changes and a link to the changelog for further information. This is a crucial step for communicating the experimental nature of certain features to users. ```python """ Experimental: $PRODUCT is $MATURITY, breaking changes may occur within minor releases. See https://docs.hetzner.cloud/changelog#$SLUG for more details. """ ``` -------------------------------- ### Use include_architecture_wildcard in IsosClient Methods Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/upgrading.md This snippet highlights the removal of the `include_wildcard_architecture` argument from `Client.isos.get_list` and `Client.isos.get_all` methods. Users should now use the `include_architecture_wildcard` argument instead. This change improves clarity and consistency in the API arguments. ```diff client.isos.get_all( - include_wildcard_architecture=True, + include_architecture_wildcard=True, ) ``` -------------------------------- ### Handle Servers Rebuild Method Return Value Change Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/upgrading.md This snippet shows the updated return value for the `Client.servers.rebuild` method. The method previously returned a single action object, but now it returns a response object that wraps the action and an optional root password. Users need to adjust their code to access the action and root password from this new response structure. ```diff -action = client.servers.rebuild(server, image) +resp = client.servers.rebuild(server, image) +action = resp.action +root_password = resp.root_password ``` -------------------------------- ### Retrieve Server Metrics with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test24/llms.txt Fetches time-series metrics data (CPU, disk, network) for a specified server within a given time range using the hcloud-python SDK. Supports custom time ranges and sampling intervals (steps). Requires a valid API token and an existing server name. ```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 ) # Process CPU metrics if "cpu" in response.metrics.time_series: cpu_data = response.metrics.time_series["cpu"] print(f"CPU values: {cpu_data['values']}") # Process network metrics if "network.0.bandwidth.in" in response.metrics.time_series: bandwidth_in = response.metrics.time_series["network.0.bandwidth.in"] print(f"Network bandwidth in: {bandwidth_in['values']}") # Get metrics for last 24 hours start = end - timedelta(hours=24) response = server.get_metrics( type=["cpu", "network"], start=start, end=end, step=300 # 5-minute intervals ) for metric_name, metric_data in response.metrics.time_series.items(): print(f"{metric_name}: {len(metric_data['values'])} data points") ``` -------------------------------- ### Exceptions Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/api.rst Details the exception hierarchy for handling errors encountered during API interactions, including general API errors and specific action-related exceptions. ```APIDOC ## Exceptions ### Description This section outlines the exception classes provided by the hcloud library for robust error handling. It includes a base exception for general API errors and specific exceptions for action-related failures. ### Method Not applicable (Exception class overview) ### Endpoint Not applicable (Exception class overview) ### Parameters N/A ### Request Example ```python from hcloud import Client, HCloudException, APIException from hcloud.actions.domain import ActionFailedException try: client = Client(token="INVALID_TOKEN") servers = client.servers.all() except APIException as e: print(f"An API error occurred: {e}") except HCloudException as e: print(f"A general Hetzner Cloud error occurred: {e}") try: # Example that might raise an ActionFailedException action = client.servers.reboot(server_id=12345) # Simulate a failed action for demonstration # In a real scenario, this would be determined by the API response if action.status == 'failed': raise ActionFailedException(action) except ActionFailedException as e: print(f"An action failed: {e}") ``` ### Response N/A (Exception class overview) ### Exception Hierarchy - **hcloud.HCloudException**: Base exception for all Hetzner Cloud related errors. - **hcloud.APIException**: Raised for errors returned by the Hetzner Cloud API. - **hcloud.actions.domain.ActionException**: Base exception for errors related to actions. - **hcloud.actions.domain.ActionFailedException**: Raised when an action fails. - **hcloud.actions.domain.ActionTimeoutException**: Raised when an action times out. ``` -------------------------------- ### Stage and Commit Changes Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/CONTRIBUTING.rst These commands are used to stage all your modified files and then commit them with a descriptive message. The commit message should clearly explain the changes you have made. This prepares your changes for pushing to your remote repository. ```shell git add . git commit -m "Your detailed description of your changes." ``` -------------------------------- ### Implement Deprecation Notice in Docstring Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/README.md Shows how to add a '.. deprecated::' directive to a Python docstring, indicating that a function or module 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. """ ``` -------------------------------- ### Update Import Path for hcloud.hcloud Module Removal Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/upgrading.md This snippet demonstrates how to update import paths after the removal of the deprecated `hcloud.hcloud` module. Users should now import the `Client` class directly from the `hcloud` package instead of the now-removed submodule. ```diff -from hcloud.hcloud import Client +from hcloud import Client ``` -------------------------------- ### Create a New Branch for Development Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/CONTRIBUTING.rst This command creates a new branch for your bugfix or feature development. Replacing 'name-of-your-bugfix-or-feature' with a descriptive name will help in managing your changes. This isolates your work from the main development branch. ```shell git checkout -b name-of-your-bugfix-or-feature ``` -------------------------------- ### Push Changes to Remote Repository Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/CONTRIBUTING.rst This command pushes your committed changes from your local branch to your remote repository on GitHub. This makes your changes available for creating a pull request. ```shell git push origin name-of-your-bugfix-or-feature ``` -------------------------------- ### Handle Empty API Response in Client.request Method Source: https://github.com/fahreddinozcan/hcloud-python-test24/blob/main/docs/upgrading.md This snippet shows an update to the `Client.request` method's behavior. When the API response is empty, the method now returns an empty dictionary (`{}`) instead of an empty string (`""`). This change affects how developers should assert the results of empty responses. ```diff response = client.request(method="DELETE", url="/primary_ips/123456") -assert response == "" +assert response == {} ```