### Create and Manage Servers with Hetzner Cloud Python SDK (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Provides examples for creating and managing servers using the hcloud-python library. It covers basic server creation with essential parameters, advanced creation with SSH keys, networks, firewalls, user data, and labels. It also demonstrates listing, filtering, getting, updating, and deleting servers. ```python from hcloud import Client from hcloud.images import Image from hcloud.server_types import ServerType from hcloud.locations import Location from hcloud.ssh_keys import SSHKey from hcloud.networks import Network from hcloud.firewalls import Firewall client = Client(token="your_api_token_here") # Create a basic server response = client.servers.create( name="my-server", server_type=ServerType(name="cx22"), # 2 vCPU, 4 GB RAM image=Image(name="ubuntu-24.04"), location=Location(name="nbg1"), # Nuremberg datacenter start_after_create=True # Start immediately ) server = response.server action = response.action root_password = response.root_password next_actions = response.next_actions print(f"Server created: {server.id=}, {server.name=}, {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.network}") # Create server with advanced configuration response = client.servers.create( name="production-server", server_type=ServerType(name="cx32"), image=Image(name="ubuntu-24.04"), location=Location(name="fsn1"), ssh_keys=[SSHKey(id=12345), SSHKey(name="my-key")], networks=[Network(id=54321)], firewalls=[Firewall(id=98765)], user_data="""#cloud-config users: - name: deploy groups: sudo shell: /bin/bash sudo: ['ALL=(ALL) NOPASSWD:ALL'] packages: - docker.io - git """, labels={"environment": "production", "team": "backend"}, start_after_create=True, automount=True ) # List all servers servers = client.servers.get_all() for server in servers: print(f"{server.id=}, {server.name=}, {server.status=}") # Filter servers by name and status running_servers = client.servers.get_all( label_selector="environment=production", status=["running"] ) # Get server by ID or name server = client.servers.get_by_id(12345) server = client.servers.get_by_name("my-server") # Update server server = client.servers.update( server, name="renamed-server", labels={"updated": "true"} ) # Delete server action = client.servers.delete(server) print(f"Delete action: {action.id}, {action.status}") ``` -------------------------------- ### Install Hetzner Cloud Python from source Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library directly from its source code. This involves either cloning the GitHub repository or downloading a tarball, followed by an installation 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 . ``` -------------------------------- ### Get Server Actions with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This example shows how to retrieve a list of all actions performed on a server, with the ability to filter by status (e.g., 'running', 'success') using hcloud-python. ```python from hcloud import Client # Assuming 'server' is an existing Server object actions = server.get_actions(status=["running", "success"]) for action in actions: print(f"{action.command=}, {action.status=}, {action.progress=}") ``` -------------------------------- ### Configure Firewalls using Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Illustrates how to create, list, retrieve, apply, update, and delete firewalls with the Hetzner Cloud Python SDK. Includes examples for applying firewalls to servers directly or via label selectors, and managing firewall rules. ```python from hcloud import Client from hcloud.firewalls import FirewallRule, FirewallResource from hcloud.servers import Server client = Client(token="your_api_token_here") # Create firewall with rules firewall = client.firewalls.create( name="web-firewall", labels={"environment": "production"}, rules=[ FirewallRule( direction="in", protocol="tcp", source_ips=["0.0.0.0/0", "::/0"], port="80", description="Allow HTTP from anywhere" ), FirewallRule( direction="in", protocol="tcp", source_ips=["0.0.0.0/0", "::/0"], port="443", description="Allow HTTPS from anywhere" ), FirewallRule( direction="in", protocol="tcp", source_ips=["10.0.0.0/8"], port="22", description="Allow SSH from internal network" ), FirewallRule( direction="out", protocol="tcp", destination_ips=["0.0.0.0/0", "::/0"], port="any", description="Allow all outbound traffic" ) ] ) print(f"Firewall created: {firewall.id}, {firewall.name}") # List all firewalls firewalls = client.firewalls.get_all() # Get firewall by ID or name firewall = client.firewalls.get_by_id(98765) firewall = client.firewalls.get_by_name("web-firewall") # Apply firewall to server actions = firewall.apply_to_resources( resources=[ FirewallResource(type="server", server=Server(id=12345)) ] ) # Apply to servers matching label selector actions = firewall.apply_to_resources( resources=[ FirewallResource( type="label_selector", label_selector={"selector": "environment=production"} ) ] ) # Update firewall rules actions = firewall.set_rules( rules=[ FirewallRule( direction="in", protocol="tcp", source_ips=["0.0.0.0/0"], port="443" ) ] ) # Remove firewall from resources actions = firewall.remove_from_resources( resources=[FirewallResource(type="server", server=Server(id=12345))] ) # Delete firewall firewall.delete() ``` -------------------------------- ### Setup Virtual Environment for Development Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Sets up a virtual environment named 'venv' and activates it for developing the hcloud-python library. This is a standard practice for isolating project dependencies. ```shell make venv source venv/bin/activate ``` -------------------------------- ### Install Hetzner Cloud Python via pip Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/installation.rst Installs the most recent stable release of the Hetzner Cloud Python library using pip. This is the recommended installation method. Ensure pip is installed before proceeding. ```console pip install hcloud ``` -------------------------------- ### Server Power Management and Actions with Hetzner Cloud Python SDK (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Illustrates how to perform power management and other actions on a Hetzner Cloud server using the hcloud-python library. This includes starting, powering off, shutting down, rebooting, and resetting servers. It also covers password reset and enabling/disabling the rescue system. ```python from hcloud import Client client = Client(token="your_api_token_here") server = client.servers.get_by_name("my-server") # Power operations action = server.power_on() # Start server print(f"Power on action: {action.status}") action = server.power_off() # Force power off (immediate) action = server.shutdown() # Graceful shutdown (ACPI) action = server.reboot() # Graceful reboot (ACPI) action = server.reset() # Force reset (power cycle) # Password reset (requires qemu guest agent) response = server.reset_password() print(f"New root password: {response.root_password}") # Enable rescue system response = server.enable_rescue( type="linux64", ssh_keys=[12345] ) print(f"Rescue password: {response.root_password}") # Disable rescue action = server.disable_rescue() ``` -------------------------------- ### Manage Floating IPs using Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Provides examples for creating, listing, retrieving, assigning, unassigning, and deleting Floating IPs with the Hetzner Cloud Python SDK. It also shows how to change reverse DNS and update Floating IP properties. ```python from hcloud import Client from hcloud.floating_ips import FloatingIP from hcloud.locations import Location from hcloud.servers import Server client = Client(token="your_api_token_here") # Create floating IP floating_ip_response = client.floating_ips.create( type="ipv4", # or "ipv6" home_location=Location(name="fsn1"), name="web-loadbalancer-ip", description="Load balancer public IP", labels={"service": "web"} ) floating_ip = floating_ip_response.floating_ip print(f"Floating IP created: {floating_ip.ip}") # Create and assign to server floating_ip_response = client.floating_ips.create( type="ipv4", server=Server(id=12345), name="server-failover-ip" ) # List all floating IPs floating_ips = client.floating_ips.get_all() # Get by ID or name floating_ip = client.floating_ips.get_by_id(11111) floating_ip = client.floating_ips.get_by_name("web-loadbalancer-ip") # Assign to server action = floating_ip.assign(Server(id=12345)) # Unassign from server action = floating_ip.unassign() # Change reverse DNS action = floating_ip.change_dns_ptr( ip="1.2.3.4", dns_ptr="web.example.com" ) # Change protection action = floating_ip.change_protection(delete=True) # Update floating IP floating_ip.update( name="updated-name", description="Updated description", labels={"updated": "true"} ) # Delete floating IP floating_ip.delete() ``` -------------------------------- ### Install Pre-commit Hooks for Development Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Installs pre-commit hooks to automatically run code quality checks before committing changes. This helps maintain code consistency and catch potential issues early. ```shell pre-commit install ``` -------------------------------- ### Install Hetzner Cloud Python via conda Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/installation.rst Installs the Hetzner Cloud Python library from the conda-forge channel. Note that this package is third-party and may not be up-to-date. This method requires conda to be installed. ```console conda install -c conda-forge hcloud ``` -------------------------------- ### Manage SSH Keys with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Demonstrates the creation, retrieval, updating, and deletion of SSH keys using the hcloud-python library. It covers getting keys by name, fingerprint, or label selectors. ```python from hcloud import Client client = Client(token="your_api_token_here") # Create SSH key ssh_key = client.ssh_keys.create( name="my-laptop", public_key="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC...", labels={"owner": "john", "device": "laptop"} ) print(f"SSH key created: {ssh_key.id}, {ssh_key.fingerprint}") # List all SSH keys ssh_keys = client.ssh_keys.get_all() for key in ssh_keys: print(f"{key.name=}, {key.fingerprint=}") # Get by name or fingerprint ssh_key = client.ssh_keys.get_by_name("my-laptop") ssh_key = client.ssh_keys.get_by_fingerprint("aa:bb:cc:...") # Filter by label keys = client.ssh_keys.get_all(label_selector="owner=john") # Update SSH key ssh_key.update( name="laptop-2025", labels={"owner": "john", "device": "laptop", "year": "2025"} ) # Delete SSH key ssh_key.delete() ``` -------------------------------- ### Get Server Metrics with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This Python code snippet retrieves server metrics (CPU, network, disk) for a specified time range using the hcloud-python library. It demonstrates how to format the request and access the time series data. ```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", "network", "disk"], start=start, # ISO-8601 format or datetime end=end, step=60 # Resolution in seconds ) metrics = response.metrics print(f"CPU time series: {metrics.time_series['cpu']}") print(f"Network incoming: {metrics.time_series['network.0.bandwidth.in']}") print(f"Network outgoing: {metrics.time_series['network.0.bandwidth.out']}") print(f"Disk IOPS read: {metrics.time_series['disk.0.iops.read']}") print(f"Disk IOPS write: {metrics.time_series['disk.0.iops.write']}") # Each time series contains timestamps and values cpu_series = metrics.time_series['cpu'] for timestamp, value in zip(cpu_series['timestamps'], cpu_series['values']): print(f"{timestamp}: {value}% CPU") ``` -------------------------------- ### Python Deprecation Notice in Docstring Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Example of how to mark a Python function or module as deprecated within its docstring using Sphinx reStructuredText syntax. Includes the version it was deprecated and a suggestion for the replacement. ```python """Get image by name .. deprecated:: 1.19 Use :func:`hcloud.images.client.ImagesClient.get_by_name_and_architecture` instead. """ ``` -------------------------------- ### Python Deprecation Warning Implementation Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Shows how to raise a `DeprecationWarning` in Python when a deprecated function or method is called. It includes a clear message guiding the user to the new method and specifies the stack level. ```python import warnings warnings.warn( "The 'hcloud.images.client.ImagesClient.get_by_name' method is deprecated, please use the " "'hcloud.images.client.ImagesClient.get_by_name_and_architecture' method instead.", DeprecationWarning, stacklevel=2, ) ``` -------------------------------- ### Build and Open Documentation Locally Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Builds the project's documentation and opens it in a web browser. This is useful for developers to preview documentation changes locally. ```shell make docs ``` -------------------------------- ### Initialize Hetzner Cloud Client (Python) Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Demonstrates how to initialize the Hetzner Cloud client using an API token. It shows both basic initialization and advanced configuration with custom settings like API endpoint, application name, polling intervals, and timeouts. The client provides access to all resource endpoints. ```python from hcloud import Client # Create client with API token client = Client(token="your_api_token_here") # Advanced client configuration with custom settings client = Client( token="your_api_token_here", api_endpoint="https://api.hetzner.cloud/v1", # Custom endpoint application_name="my-app", # Custom user agent application_version="1.0.0", poll_interval=2.0, # Action polling interval in seconds poll_max_retries=120, # Max retries for polling timeout=(5.0, 30.0) # (connect, read) timeout in seconds ) # Client provides access to all resource endpoints print(f"Client initialized with token: {client._client._token[:10]}...") ``` -------------------------------- ### Create and List Servers with hcloud-python Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Demonstrates how to use the hcloud-python library to create a new server with specified parameters (name, server type, image) and then list all existing servers. 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=}") ``` -------------------------------- ### Manage Volumes using Hetzner Cloud Python SDK Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Demonstrates how to create, list, retrieve, attach, detach, resize, update, and delete block storage volumes using the Hetzner Cloud Python SDK. It also covers changing delete protection settings. ```python from hcloud import Client from hcloud.servers import Server from hcloud.locations import Location client = Client(token="your_api_token_here") # Create volume volume_response = client.volumes.create( size=100, # Size in GB name="database-volume", location=Location(name="fsn1"), labels={"purpose": "database", "app": "postgres"}, format="ext4" # Auto-format (optional) ) volume = volume_response.volume action = volume_response.action print(f"Volume created: {volume.id}, {volume.name}, {volume.size} GB") # List all volumes volumes = client.volumes.get_all() # Get volume by ID or name volume = client.volumes.get_by_id(67890) volume = client.volumes.get_by_name("database-volume") # Attach volume to server action = volume.attach(server=Server(id=12345), automount=True) print(f"Volume attached, device: {volume.linux_device}") # Detach volume action = volume.detach() # Resize volume (can only increase size) action = volume.resize(size=200) # Change protection action = volume.change_protection(delete=True) # Update volume volume.update(name="postgres-data", labels={"updated": "true"}) # Delete volume (must be detached first) volume.delete() ``` -------------------------------- ### List Available Hetzner Cloud Resources with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This snippet demonstrates how to list various resources available in Hetzner Cloud using the hcloud-python library. It covers fetching all datacenters, locations, server types, images (including filtering), ISOs, and load balancer types. The code iterates through the results and prints relevant details for each resource. It requires the 'hcloud' library. ```python from hcloud import Client client = Client(token="your_api_token_here") # List all datacenters datacenter = client.datacenters.get_all() for dc in datacenters: print(f"Datacenter: {dc.name}, Location: {dc.location.name}") # List all locations locations = client.locations.get_all() for loc in locations: print(f"Location: {loc.name}, City: {loc.city}, Country: {loc.country}") # List all server types server_types = client.server_types.get_all() for st in server_types: print(f"Type: {st.name}, Cores: {st.cores}, RAM: {st.memory} GB, " f"Disk: {st.disk} GB, Price: €{st.prices[0].price_monthly.gross}/month") # Filter server types server_types = client.server_types.get_all(name="cx22") # List all images images = client.images.get_all() for img in images: if img.type == "system": print(f"Image: {img.name}, OS: {img.os_flavor}, Arch: {img.architecture}") # Filter images ubuntu_images = client.images.get_all( name="ubuntu", architecture=["x86", "arm"] ) # Get image by name and architecture image = client.images.get_by_name_and_architecture( name="ubuntu-24.04", architecture="x86" ) # List ISOs isos = client.isos.get_all() for iso in isos: print(f"ISO: {iso.name}, Type: {iso.type}") # List all load balancer types lb_types = client.load_balancer_types.get_all() for lbt in lb_types: print(f"LB Type: {lbt.name}, Max connections: {lbt.max_connections}, " f"Max targets: {lbt.max_targets}") ``` -------------------------------- ### Create Server Snapshot with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This snippet demonstrates how to create a server snapshot using the hcloud-python library. It requires a server object and specifies the image type as 'snapshot' along with optional labels. ```python from hcloud import Client # Assuming 'server' is an existing Server object image_response = server.create_image( description="Production backup 2025-10-31", type="snapshot", labels={"backup": "daily", "server": server.name} ) print(f"Image created: {image_response.image.id}") ``` -------------------------------- ### Create and Manage Load Balancers with Python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This snippet shows how to create, configure, and manage Hetzner Cloud Load Balancers using the hcloud-python library. It covers adding and removing targets (servers, label selectors, IPs), updating load balancer settings, retrieving metrics, and deleting the load balancer. Dependencies include the 'hcloud' library and datetime objects for metrics. ```python from hcloud import Client from hcloud.load_balancers import ( LoadBalancerService, LoadBalancerServiceHttp, LoadBalancerHealthCheck, LoadBalancerHealthCheckHttp, LoadBalancerTarget ) from hcloud.load_balancer_types import LoadBalancerType from hcloud.locations import Location from hcloud.networks import Network from hcloud.servers import Server from datetime import datetime, timedelta, timezone client = Client(token="your_api_token_here") # Create load balancer with HTTP service response = client.load_balancers.create( name="web-lb", load_balancer_type=LoadBalancerType(name="lb11"), location=Location(name="nbg1"), labels={"service": "web"}, network=Network(id=54321), services=[ LoadBalancerService( protocol="https", listen_port=443, destination_port=80, proxyprotocol=False, http=LoadBalancerServiceHttp( sticky_sessions=True, cookie_name="HCLBSTICKY", cookie_lifetime=300, redirect_http=True, certificates=[12345] ), health_check=LoadBalancerHealthCheck( protocol="http", port=80, interval=15, timeout=10, retries=3, http=LoadBalancerHealthCheckHttp( domain="example.com", path="/health", response="OK", tls=False, status_codes=["200", "204"] ) ) ) ] ) load_balancer = response.load_balancer print(f"Load balancer created: {load_balancer.id}") print(f"Public IPv4: {load_balancer.public_net.ipv4.ip}") print(f"Public IPv6: {load_balancer.public_net.ipv6.ip}") # Add target servers action = load_balancer.add_target( LoadBalancerTarget( type="server", server=Server(id=12345), use_private_ip=True ) ) # Add label selector target action = load_balancer.add_target( LoadBalancerTarget( type="label_selector", label_selector={"selector": "role=webserver"}, use_private_ip=True ) ) # Add IP target action = load_balancer.add_target( LoadBalancerTarget( type="ip", ip={"ip": "203.0.113.1"} ) ) # Remove target action = load_balancer.remove_target( LoadBalancerTarget(type="server", server=Server(id=12345)) ) # Update load balancer load_balancer.update(name="production-lb", labels={"updated": "true"}) # Get load balancer metrics 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 ) # Delete load balancer load_balancer.delete() ``` -------------------------------- ### Server Operations Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This section details operations related to managing servers, such as creating snapshots, rebuilding, resizing, managing backups, and changing protection settings. ```APIDOC ## Server Operations ### Create Server Snapshot Creates a backup snapshot of the server. ```python image_response = server.create_image( description="Production backup 2025-10-31", type="snapshot", labels={"backup": "daily", "server": server.name} ) print(f"Image created: {image_response.image.id}") ``` ### Rebuild Server from Image Rebuilds the server using a specified image. ```python rebuild_response = server.rebuild(image=Image(name="ubuntu-24.04")) print(f"New root password: {rebuild_response.root_password}") ``` ### Change Server Type (Resize) Resizes the server to a different server type. ```python action = server.change_type( server_type=ServerType(name="cx32"), upgrade_disk=True ) ``` ### Enable/Disable Backups Manages backup settings for the server. ```python # Enable backups action = server.enable_backup() # Disable backups action = server.disable_backup() ``` ### Change Server Protection Settings Configures protection settings to prevent accidental deletion or rebuild. ```python action = server.change_protection(delete=True, rebuild=True) ``` ### Get Server Actions Retrieves a list of all actions performed on the server, with optional status filtering. ```python actions = server.get_actions(status=["running", "success"]) for action in actions: print(f"{action.command=}, {action.status=}, {action.progress=}") ``` ``` -------------------------------- ### Wait for Action to Complete (Automatic Polling) - Python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Demonstrates how to initiate a server action and wait for its completion using the library's automatic polling mechanism. The polling uses exponential backoff configured during client initialization. Includes error handling for failed actions. ```python from hcloud.servers import Server server = Server(id=12345) action = client.servers.power_on(server) # The library automatically polls until the action completes # Polling uses exponential backoff defined in client initialization try: action.wait_until_finished(max_retries=120) # Wait up to 120 polling attempts print(f"Action completed: {action.status}") except Exception as e: print(f"Action failed: {e}") # Manual action status check action = client.actions.get_by_id(action.id) if action.status == "success": print("Action succeeded") elif action.status == "error": print(f"Action failed: {action.error}") ``` -------------------------------- ### Python Docstring for Experimental Features Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md This Python docstring format is used to mark experimental features. It includes a notice about potential breaking changes and a link to the changelog for more details. Ensure the placeholders like $PRODUCT, $MATURITY, and $SLUG are updated accordingly. ```python """ Experimental: $PRODUCT is $MATURITY, breaking changes may occur within minor releases. See https://docs.hetzner.cloud/changelog#$SLUG for more details. """ ``` -------------------------------- ### Advanced Client Configuration - Python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Shows how to customize the Hetzner Cloud client for various needs, including setting constant or exponential backoff poll intervals, configuring connection and read timeouts, specifying application identification for the User-Agent, and directing requests to a custom API endpoint. ```python from hcloud import Client, constant_backoff_function, exponential_backoff_function # Custom poll interval (constant) client = Client( token="your_api_token_here", poll_interval=5.0 # Poll every 5 seconds ) # Custom poll interval (exponential backoff) client = Client( token="your_api_token_here", poll_interval=exponential_backoff_function( base=1.0, # Start at 1 second multiplier=2, # Double each time cap=60.0, # Cap at 60 seconds jitter=True # Add random jitter ) ) # Custom timeouts client = Client( token="your_api_token_here", timeout=30.0 # Single timeout for connect and read ) client = Client( token="your_api_token_here", timeout=(5.0, 30.0) # (connect_timeout, read_timeout) ) # Custom application identification client = Client( token="your_api_token_here", application_name="my-automation-tool", application_version="2.1.0" ) # User-Agent will be: "my-automation-tool/2.1.0 hcloud-python/2.9.0" # Custom API endpoint (for testing or proxies) client = Client( token="your_api_token_here", api_endpoint="https://custom-proxy.example.com/v1" ) # Direct HTTP request to API response = client.request( method="GET", url="/servers", params={"page": 1, "per_page": 50} ) print(response) # Returns dict with API response ``` -------------------------------- ### Clone hcloud-python Repository Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/CONTRIBUTING.rst Command to clone your forked hcloud-python repository locally for development. This is the first step after forking the repository on GitHub. ```bash git clone git@github.com:your_name_here/hcloud-python.git ``` -------------------------------- ### Attach and Manage Volumes with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This snippet provides the necessary imports for working with volumes in the hcloud-python library. It sets up the client and imports Volume and Location classes, preparing for volume operations. ```python from hcloud import Client from hcloud.volumes import Volume from hcloud.locations import Location client = Client(token="your_api_token_here") ``` -------------------------------- ### Enable/Disable Server Backups with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This snippet illustrates how to enable and disable backup services for a server using the hcloud-python library. Enabling backups incurs an additional cost. ```python from hcloud import Client # Assuming 'server' is an existing Server object action = server.enable_backup() action = server.disable_backup() ``` -------------------------------- ### Rebuild Server from Image with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This code shows how to rebuild a server using a specified image with the hcloud-python library. It returns the new root password upon successful rebuild. ```python from hcloud import Client from hcloud.images import Image # Assuming 'server' is an existing Server object rebuild_response = server.rebuild(image=Image(name="ubuntu-24.04")) print(f"New root password: {rebuild_response.root_password}") ``` -------------------------------- ### Lint Code with Makefile Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/README.md Runs the code linting process using the lint task defined in the Makefile. Linting helps ensure code quality and adherence to style guidelines. ```shell make lint ``` -------------------------------- ### Create and Manage Networks Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Facilitates the creation and management of private networks, including subnets, routes, and server attachments. ```APIDOC ## Create and Manage Networks ### Create Private Network Creates a new private network with a specified IP range and optional subnets and labels. **Parameters** #### Request Body - **name** (str) - Required - Name of the network. - **ip_range** (str) - Required - IP range for the network (e.g., "10.0.0.0/16"). - **labels** (dict) - Optional - Labels to apply to the network. - **subnets** (list[NetworkSubnet]) - Optional - List of subnets to create within the network. ### List Networks Retrieves all available networks. ### Get Network by ID or Name Retrieves a specific network by its ID or name. ### Add Subnet to Network Adds a new subnet to an existing network. **Parameters** #### Request Body - **subnet** (NetworkSubnet) - Required - The subnet to add. ### Add Route to Network Adds a route to the network's routing table. **Parameters** #### Request Body - **route** (NetworkRoute) - Required - The route to add. ### Attach Server to Network Attaches a server to the network with a specified IP address and optional alias IPs. **Parameters** #### Request Body - **server** (Server) - Required - The server to attach. - **ip** (str) - Required - The IP address for the server in the network. - **alias_ips** (list[str]) - Optional - List of alias IP addresses. ### Update Network Updates the name and labels of an existing network. ### Delete Network Deletes a network. ### Request Example (Create Network) ```python from hcloud import Client from hcloud.networks import NetworkSubnet client = Client(token="your_api_token_here") network = client.networks.create( name="private-network", ip_range="10.0.0.0/16", labels={"environment": "production"}, subnets=[ NetworkSubnet( type="cloud", network_zone="eu-central", ip_range="10.0.1.0/24" ) ] ) print(f"Network created: {network.id}, {network.ip_range}") ``` ### Request Example (Add Subnet) ```python action = network.add_subnet( NetworkSubnet( type="cloud", network_zone="eu-central", ip_range="10.0.2.0/24" ) ) ``` ### Request Example (Add Route) ```python from hcloud.networks import NetworkRoute action = network.add_route( NetworkRoute(destination="10.100.0.0/16", gateway="10.0.1.1") ) ``` ### Request Example (Attach Server) ```python from hcloud.servers import Server action = network.attach_to_network( server=Server(id=12345), ip="10.0.1.10", alias_ips=["10.0.1.11", "10.0.1.12"] ) ``` ### Request Example (Update Network) ```python network.update( name="production-network", labels={"updated": "true"} ) ``` ### Request Example (Delete Network) ```python network.delete() ``` ### Response Example (List Networks) ```json [ { "id": 54321, "name": "private-network", "ip_range": "10.0.0.0/16", "subnets": [ { "type": "cloud", "network_zone": "eu-central", "ip_range": "10.0.1.0/24" } ], "routes": [], "created": "2023-10-27T10:00:00Z", "labels": {"environment": "production"} } ] ``` ``` -------------------------------- ### Create and Manage Networks with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This section covers the creation and management of private networks using hcloud-python. It includes creating networks with subnets, adding routes, attaching servers, updating network details, and deleting networks. ```python from hcloud import Client from hcloud.networks import NetworkSubnet client = Client(token="your_api_token_here") # Create private network network = client.networks.create( name="private-network", ip_range="10.0.0.0/16", labels={"environment": "production"}, subnets=[ NetworkSubnet( type="cloud", network_zone="eu-central", ip_range="10.0.1.0/24" ) ] ) print(f"Network created: {network.id}, {network.ip_range}") # List all networks networks = client.networks.get_all() # Get network by ID or name network = client.networks.get_by_id(54321) network = client.networks.get_by_name("private-network") # Add subnet to network action = network.add_subnet( NetworkSubnet( type="cloud", network_zone="eu-central", ip_range="10.0.2.0/24" ) ) # Add route to network from hcloud.networks import NetworkRoute action = network.add_route( NetworkRoute(destination="10.100.0.0/16", gateway="10.0.1.1") ) # Attach server to network from hcloud.servers import Server action = network.attach_to_network( server=Server(id=12345), ip="10.0.1.10", alias_ips=["10.0.1.11", "10.0.1.12"] ) # Update network network.update( name="production-network", labels={"updated": "true"} ) # Delete network network.delete() ``` -------------------------------- ### Attach and Manage Volumes Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This section outlines operations for managing block storage volumes, including creation, attachment, detachment, and deletion. ```APIDOC ## Attach and Manage Volumes ### Create Volume Creates a new block storage volume. **Parameters** #### Request Body - **name** (str) - Required - Name of the volume. - **size** (int) - Required - Size of the volume in GB. - **location** (Location | str) - Optional - Location where the volume should be created. - **labels** (dict) - Optional - Labels to apply to the volume. - **server** (Server) - Optional - Server to which the volume should be attached directly upon creation. - **automount** (bool) - Optional - Whether the volume should be automatically mounted to the server. ### List Volumes Retrieves all available volumes, optionally filtered by label selector. ### Get Volume by ID or Name Retrieves a specific volume by its ID or name. ### Attach Volume to Server Attaches an existing volume to a server. **Parameters** #### Request Body - **server** (Server) - Required - The server to attach the volume to. - **automount** (bool) - Optional - Whether the volume should be automatically mounted. ### Detach Volume from Server Detaches a volume from its currently attached server. ### Update Volume Updates the name and labels of an existing volume. Can also be used to resize the volume. ### Delete Volume Deletes a volume. ### Request Example (Create Volume) ```python from hcloud import Client from hcloud.volumes import Volume from hcloud.locations import Location client = Client(token="your_api_token_here") volume = client.volumes.create( name="my-volume", size=50, location=Location(name="nbg1"), labels={"backup": "daily"} ) print(f"Volume created: {volume.id}, {volume.name}") ``` ### Request Example (Attach Volume) ```python from hcloud.servers import Server server = client.servers.get_by_name("my-server") volume = client.volumes.get_by_name("my-volume") action = volume.attach_to_server(server=server, automount=True) ``` ### Request Example (Update Volume) ```python volume.update(name="my-new-volume-name", size=100) ``` ### Request Example (Delete Volume) ```python volume.delete() ``` ### Response Example (List Volumes) ```json [ { "id": 12345, "name": "my-volume", "size": 50, "created": "2023-10-27T10:00:00Z", "status": "available", "labels": {"backup": "daily"}, "location": { "id": 1, "name": "nbg1", "country": "de", "city": 3205, "description": "Nuremberg 1", "latitude": 49.452, "longitude": 11.077 }, "server": null } ] ``` ``` -------------------------------- ### API Helpers Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/api.rst Documentation for helper utilities that assist in API interactions and data handling. ```APIDOC ## API Helpers ### Description This section describes helper functions and utilities provided by the hcloud-python library. These helpers can simplify common tasks related to API requests and responses. ### Method N/A (Module Documentation) ### Endpoint N/A (Module Documentation) ### Parameters (Refer to api.helpers module documentation for specific parameters) ### Request Example ```python # Example: Using a hypothetical helper function # from hcloud import helpers # formatted_name = helpers.format_resource_name("my_server") ``` ### Response (Refer to specific helper function return types) ### Success Response (200) N/A (Module Documentation) ``` -------------------------------- ### Handle `servers.rebuild` Full Response Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/upgrading.md Updates the return value handling for the `Client.servers.rebuild` method. The method now returns a full response object containing both the `action` and an optional `root_password`, instead of just the action. This provides more comprehensive information. ```python action = client.servers.rebuild(server, image) ``` ```python resp = client.servers.rebuild(server, image) action = resp.action root_password = resp.root_password ``` -------------------------------- ### Use `include_architecture_wildcard` Argument Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/upgrading.md Replaces the deprecated `include_wildcard_architecture` argument with `include_architecture_wildcard` in the `Client.isos.get_list` and `Client.isos.get_all` methods. This ensures compatibility with the latest API specifications. ```python client.isos.get_all( include_wildcard_architecture=True, ) ``` ```python client.isos.get_all( include_architecture_wildcard=True, ) ``` -------------------------------- ### Request Console Access with hcloud-python Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt This snippet shows how to request VNC console access for a server using the hcloud-python library. It provides a WebSocket URL and a password for connecting to the console. ```python from hcloud import Client client = Client(token="your_api_token_here") server = client.servers.get_by_name("my-server") # Request VNC console access console_response = server.request_console() print(f"WebSocket URL: {console_response.wss_url}") print(f"Console password: {console_response.password}") # Use the wss_url with a WebSocket client to connect to VNC # The console provides keyboard, monitor, and mouse access ``` -------------------------------- ### Server Metrics and Monitoring Source: https://context7.com/fahreddinozcan/hcloud-python-test21/llms.txt Retrieves performance metrics for a server, including CPU, network, and disk usage over a specified time range. ```APIDOC ## Server Metrics and Monitoring ### Get Server Metrics Retrieves metrics for a server within a specified time range and resolution. **Parameters** #### Query Parameters - **type** (list[str]) - Required - Type of metrics to retrieve (e.g., `cpu`, `network`, `disk`). - **start** (datetime | str) - Required - Start time for the metrics (ISO-8601 format or datetime object). - **end** (datetime | str) - Required - End time for the metrics (ISO-8601 format or datetime object). - **step** (int) - Optional - Resolution in seconds for the metrics. ### Request Example ```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", "network", "disk"], start=start, end=end, step=60 ) metrics = response.metrics print(f"CPU time series: {metrics.time_series['cpu']}") print(f"Network incoming: {metrics.time_series['network.0.bandwidth.in']}") print(f"Network outgoing: {metrics.time_series['network.0.bandwidth.out']}") print(f"Disk IOPS read: {metrics.time_series['disk.0.iops.read']}") print(f"Disk IOPS write: {metrics.time_series['disk.0.iops.write']}") # Each time series contains timestamps and values cpu_series = metrics.time_series['cpu'] for timestamp, value in zip(cpu_series['timestamps'], cpu_series['values']): print(f"{timestamp}: {value}% CPU") ``` ### Response Example ```json { "metrics": { "time_series": { "cpu": { "timestamps": ["2023-10-27T10:00:00Z", "2023-10-27T10:01:00Z"], "values": [10.5, 12.1] }, "network.0.bandwidth.in": { "timestamps": ["2023-10-27T10:00:00Z", "2023-10-27T10:01:00Z"], "values": [10240, 11000] }, "network.0.bandwidth.out": { "timestamps": ["2023-10-27T10:00:00Z", "2023-10-27T10:01:00Z"], "values": [5120, 5500] }, "disk.0.iops.read": { "timestamps": ["2023-10-27T10:00:00Z", "2023-10-27T10:01:00Z"], "values": [100, 110] }, "disk.0.iops.write": { "timestamps": ["2023-10-27T10:00:00Z", "2023-10-27T10:01:00Z"], "values": [50, 55] } } } } ``` ``` -------------------------------- ### HCloud Client Source: https://github.com/fahreddinozcan/hcloud-python-test21/blob/main/docs/api.rst Documentation for the main HCloud client interface, including its members and methods for interacting with the API. ```APIDOC ## Hcloud Client Interface ### Description This section details the main interface for interacting with the Hetzner Cloud API using the hcloud-python library. It covers the available methods and properties of the `hcloud.Client` class. ### Method N/A (Class Documentation) ### Endpoint N/A (Class Documentation) ### Parameters (Refer to hcloud.Client class documentation for specific parameters) ### Request Example ```python from hcloud import Client # Assuming you have your API token client = Client(token="YOUR_API_TOKEN") # Example usage of a client method (replace with actual method) # servers = client.servers.get_all() ``` ### Response (Refer to specific method return types within hcloud.Client documentation) ### Success Response (200) N/A (Class Documentation) ```