From 589095e2a84ae7db7b33587f869765289ea88806 Mon Sep 17 00:00:00 2001 From: Maxime Van Hees Date: Thu, 17 Jul 2025 14:03:49 +0200 Subject: [PATCH] added examples --- README.md | 178 ++-------------------------- create_server.rhai | 25 ---- examples/01_create_server.rhai | 56 +++++++++ examples/02_list_servers.rhai | 11 ++ examples/03_get_server_details.rhai | 15 +++ examples/04_server_actions.rhai | 43 +++++++ examples/05_list_ssh_keys.rhai | 11 ++ examples/06_list_images.rhai | 58 +++++++++ test.rhai | 47 -------- 9 files changed, 206 insertions(+), 238 deletions(-) delete mode 100644 create_server.rhai create mode 100644 examples/01_create_server.rhai create mode 100644 examples/02_list_servers.rhai create mode 100644 examples/03_get_server_details.rhai create mode 100644 examples/04_server_actions.rhai create mode 100644 examples/05_list_ssh_keys.rhai create mode 100644 examples/06_list_images.rhai delete mode 100644 test.rhai diff --git a/README.md b/README.md index 06c8f70..b7de94e 100644 --- a/README.md +++ b/README.md @@ -14,179 +14,25 @@ Replace `"YOUR_API_TOKEN_HERE"` with your actual Hetzner API token. ## Usage -You can execute any `.rhai` script by passing it as an argument to `cargo run`. +You can execute any of the example scripts by passing the file path to `cargo run`. ```bash -cargo run -- .rhai +cargo run -- examples/.rhai ``` -For example, to run the provided `test.rhai` script: +For example, to run the script that creates a server: ```bash -cargo run -- test.rhai +cargo run -- examples/01_create_server.rhai ``` -## API Examples +## Examples -Here are some examples of what you can do with the API, taken from the `test.rhai` script. +The `examples/` directory contains a collection of scripts demonstrating the available functionality. For detailed examples, please see the files in that directory: -### 1. Create a Client - -All API interactions start by creating a client instance. - -```rust -// Create client to communicate with Hetzner API -let client = new_hetzner_client(HETZNER_API_TOKEN); -``` - -### 2. Create a Server - -You can create a new server using the `ServerBuilder` pattern. This provides a flexible way to configure the server before creation. - -```rust -// Create a server builder with required parameters -let server_builder = new_server_builder("my-new-server", "cpx11", "ubuntu-20.04"); - -// Chain optional parameters -let server_builder = server_builder - .with_location("fsn1") - .with_datacenter("fsn1-dc14") - .with_start_after_create(true) - .with_user_data("#cloud-config\nruncmd:\n - [ ls, -l, / ]"); - -// Specify SSH key IDs. If this is omitted, all SSH keys in your project will be used. -let server_builder = server_builder.with_ssh_keys([12345, 67890]); - -// Create the server -let response = client.create_server(server_builder); - -print(`Server creation initiated for: ${response.name}`); -``` - -The following options are available on the `ServerBuilder`: - -| Method | Description | -| :--- | :--- | -| `with_location(string)` | Sets the server location (e.g., "fsn1"). | -| `with_datacenter(string)`| Sets the datacenter (e.g., "fsn1-dc14"). | -| `with_user_data(string)` | Provides user data for cloud-init. | -| `with_start_after_create(bool)` | Specifies whether the server should start after creation. | -| `with_ssh_keys(array)` | An array of SSH Key IDs to attach to the server. | - - -### 3. List Servers & Display Details - -You can fetch all your servers and display their details in a formatted table. - -```rust -// List all servers and print in table -print("Listing all servers..."); -let servers = client.list_servers(); -print(servers.show_table()); - -// Get a specific server by ID and show its details -let test_server = client.get_server(104301883); -print(test_server.show_details()); -``` - -### 4. List SSH Keys - -You can also list all the SSH keys in your project. - -```rust -// List all SSH keys and print in table -print("Listing all SSH keys..."); -let ssh_keys = client.list_ssh_keys(); -print(ssh_keys.show_table()); -``` - -### 5. Manage Server State - -Perform actions like enabling rescue mode, disabling it, or rebooting the server. - -```rust -// Enable rescue mode and get the root password -print(`Enabling rescue mode on server with ID: ${test_server.id}`); -let root_password = client.enable_rescue_mode(test_server.id); -print(`Root password is: ${root_password}`); - -// Disable rescue mode -print(`Disabling rescue mode on server with ID: ${test_server.id}`); -client.disable_rescue_mode(test_server.id); - -// Reboot server -print(`Rebooting server with ID: ${test_server.id}`); -client.reboot(test_server.id); -``` -#### Injecting SSH Keys into Rescue Mode - -You can also inject SSH keys into the rescue image. The `enable_rescue_mode` function accepts an optional SSH key ID (integer) or an array of SSH key IDs. If no keys are provided, all available SSH keys in your project will be automatically used. - -**Important:** The SSH keys must already exist in your Hetzner Cloud project. You can add them in the [Hetzner Cloud Console](https://console.hetzner.cloud/). For more details, refer to the [official documentation on enabling rescue mode](https://docs.hetzner.cloud/reference/cloud#server-actions-enable-rescue-mode-for-a-server). - -Here are some examples of how to use this feature in your Rhai script: - -```rust -// A single SSH key ID -client.enable_rescue_mode(test_server.id, 1337); - -// An array of SSH key IDs -let ssh_keys = [123, 456, 789]; -client.enable_rescue_mode(test_server.id, ssh_keys); - -// Reading an SSH key from an environment variable -let ssh_key_from_env = get_env("SSH_KEY_ID"); -if ssh_key_from_env != "" { - client.enable_rescue_mode(test_server.id, ssh_key_from_env.parse_int()); -} -``` - -### 6. Example Output (from `test.rhai` script) - -```text -Listing all servers... -+-------------+-------------------+---------+-------------+ -| Server List | | | | -+=============+===================+=========+=============+ -| ID | Name | Status | Public IPv4 | -+-------------+-------------------+---------+-------------+ -| 104298257 | ubuntu-4gb-fsn1-2 | Running | 91.99.1.255 | -+-------------+-------------------+---------+-------------+ -| 104301883 | ubuntu-4gb-fsn1-4 | Running | 91.99.178.6 | -+-------------+-------------------+---------+-------------+ - -Listing all SSH keys... -+-----------+------------------------------+-------------------------------------------------+ -| SSH Keys | | | -+===========+==============================+=================================================+ -| ID | Name | Fingerprint | -+-----------+------------------------------+-------------------------------------------------+ -| 100324992 | mahmmoud.hassanein@gmail.com | 45:67:42:b7:e0:38:0d:40:40:80:a6:8a:0d:ac:73:6b | -+-----------+------------------------------+-------------------------------------------------+ -| 100325001 | maxime@maxime-arch | e0:73:80:26:80:46:f0:c8:bb:74:f4:d0:2d:10:2d:6f | -+-----------+------------------------------+-------------------------------------------------+ - -Listing details from server with ID 104301883... -+-------------------+----------------------+ -| ubuntu-4gb-fsn1-4 | | -+===================+======================+ -| ID | 104301883 | -+-------------------+----------------------+ -| Status | Running | -+-------------------+----------------------+ -| Created | 2025-07-15T12:25:29Z | -+-------------------+----------------------+ -| IPv4 | 91.99.178.6 | -+-------------------+----------------------+ -| Type | cx22 | -+-------------------+----------------------+ -| Included Traffic | 20480 GB | -+-------------------+----------------------+ -| Ingoing Traffic | 0 MB | -+-------------------+----------------------+ -| Outgoing Traffic | 0 MB | -+-------------------+----------------------+ -| Primary Disk Size | 40 | -+-------------------+----------------------+ -| Rescue Enabled | false | -+-------------------+----------------------+ +- [`examples/01_create_server.rhai`](examples/01_create_server.rhai): Shows how to create a new server with various configuration options using a builder pattern. +- [`examples/02_list_servers.rhai`](examples/02_list_servers.rhai): Lists all servers in your project. +- [`examples/03_get_server_details.rhai`](examples/03_get_server_details.rhai): Fetches and displays detailed information for a single server. +- [`examples/04_server_actions.rhai`](examples/04_server_actions.rhai): Demonstrates how to reboot, reset, and manage rescue mode for a server. +- [`examples/05_list_ssh_keys.rhai`](examples/05_list_ssh_keys.rhai): Lists all SSH keys in your project. +- [`examples/06_list_images.rhai`](examples/06_list_images.rhai): Shows how to list system images and snapshots, with examples of filtering and sorting. diff --git a/create_server.rhai b/create_server.rhai deleted file mode 100644 index 1fd4a92..0000000 --- a/create_server.rhai +++ /dev/null @@ -1,25 +0,0 @@ -let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); - -let server_builder = new_server_builder("my-new-test-server", "cx22", "ubuntu-24.04"); - -// Example of using the new optional parameters -let server_builder = server_builder - .with_location("fsn1"); - // .with_datacenter("fsn1-dc14") - // .with_start_after_create(true) - // .with_user_data("#cloud-config\nruncmd:\n - [ ls, -l, / ]"); - -// Example of specifying SSH key IDs. -// If you don't call with_ssh_keys, all keys will be added by default. -// let server_builder = server_builder.with_ssh_keys([12345, 67890]); - -let response = client.create_server(server_builder); - -print(`Server creation initiated for: ${response.name}`); -print(` ID: ${response.id}`); -print(` Status: ${response.status}`); -if response.root_password != "" { - print(` Root Password: ${response.root_password}`); -} else { - print(" Root Password: Not set (SSH key id was provided)"); -} \ No newline at end of file diff --git a/examples/01_create_server.rhai b/examples/01_create_server.rhai new file mode 100644 index 0000000..c364da8 --- /dev/null +++ b/examples/01_create_server.rhai @@ -0,0 +1,56 @@ +// This script demonstrates how to create a new server using the Hetzner Cloud API. +// It showcases the use of the `ServerBuilder` to configure the server's properties. + +// Initialize the Hetzner client with your API token. +// It's recommended to use an environment variable for the token for security. +let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); + +// Create a new server builder. +// The `new_server_builder` function requires three arguments: +// 1. name: The name of the server (e.g., "my-server"). +// 2. server_type: The type of server (e.g., "cx11" for a basic server). +// 3. image: The OS image to use (e.g., "ubuntu-22.04"). +let server_builder = new_server_builder("my-awesome-server", "cx22", "ubuntu-24.04"); + +// The `ServerBuilder` provides several optional methods to customize the server. +// You can chain these methods to configure the server as needed. + +// .with_location(location: string): +// Specifies the location to create the server in (e.g., "nbg1", "fsn1", "hel1"). +// If not specified, the server will be created in a default location. +// +// .with_datacenter(datacenter: string): +// Specifies the datacenter to create the server in (e.g., "nbg1-dc3", "fsn1-dc14"). +// This is more specific than the location. +// +// .with_start_after_create(start: bool): +// Determines whether the server should be started immediately after creation. +// Defaults to `true`. +// +// .with_user_data(user_data: string): +// Provides cloud-init user data to configure the server on its first boot. +// This is useful for automating setup tasks. +// Example: "#cloud-config\nruncmd:\n - [ ls, -l, / ]" +// +// .with_ssh_keys(ssh_keys: array): +// An array of SSH key IDs to associate with the server. +// If this method is not called, all available SSH keys in your account will be added. +// Example: .with_ssh_keys([12345, 67890]) + +// Example of chaining optional builder methods: +let server_builder = server_builder + .with_location("fsn1") + .with_user_data("#cloud-config\nruncmd:\n - [ apt-get, update ]\n - [ apt-get, install, -y, htop ]"); + +// Create the server using the configured builder. +let response = client.create_server(server_builder); + +// Print the details of the server creation response. +print(`Server creation initiated for: ${response.name}`); +print(` ID: ${response.id}`); +print(` Status: ${response.status}`); +if response.root_password != "" { + print(` Root Password: ${response.root_password}`); +} else { + print(" Root Password: Not set (SSH key was provided)"); +} \ No newline at end of file diff --git a/examples/02_list_servers.rhai b/examples/02_list_servers.rhai new file mode 100644 index 0000000..d1866b3 --- /dev/null +++ b/examples/02_list_servers.rhai @@ -0,0 +1,11 @@ +// This script demonstrates how to list all servers in your Hetzner Cloud project. + +// Initialize the Hetzner client with your API token. +let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); + +// Retrieve the list of all servers. +print("Listing all servers..."); +let servers = client.list_servers(); + +// The `show_table` method formats the server list into a user-friendly table. +print(servers.show_table()); \ No newline at end of file diff --git a/examples/03_get_server_details.rhai b/examples/03_get_server_details.rhai new file mode 100644 index 0000000..cf82496 --- /dev/null +++ b/examples/03_get_server_details.rhai @@ -0,0 +1,15 @@ +// This script demonstrates how to retrieve detailed information for a specific server. + +// Initialize the Hetzner client with your API token. +let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); + +// Replace this with the ID of the server you want to inspect. +// You can get the server ID by listing all servers (see 02_list_servers.rhai). +let server_id = 104298257; // FIXME: Replace with your own ID + +// Get the server object by its ID. +print(`Fetching details for server with ID: ${server_id}...`); +let server = client.get_server(server_id); + +// The `show_details` method provides a comprehensive overview of the server's properties. +print(server.show_details()); \ No newline at end of file diff --git a/examples/04_server_actions.rhai b/examples/04_server_actions.rhai new file mode 100644 index 0000000..35944ce --- /dev/null +++ b/examples/04_server_actions.rhai @@ -0,0 +1,43 @@ +// This script demonstrates how to perform various actions on a server, +// such as rebooting, resetting, and managing rescue mode. + +// Initialize the Hetzner client with your API token. +let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); + +// Replace this with the ID of the server you want to manage. +let server_id = 1234567; // FIXME: Replace with a real server ID + +// --- Reboot Server --- +// A soft reboot is attempted first. If it doesn't succeed, a hard reset is performed. +print(`Rebooting server with ID: ${server_id}...`); +client.reboot(server_id); +print("Reboot command sent."); + +// --- Reset Server --- +// This is equivalent to a hard reset (power cycle). +// print(`Resetting server with ID: ${server_id}...`); +// client.reset(server_id); +// print("Reset command sent."); + +// --- Enable Rescue Mode --- +// Enables rescue mode for a server. This is useful for maintenance and recovery. +// The `enable_rescue_mode` function can be called in three ways: + +// 1. With only the server ID: +// This will enable rescue mode and add all SSH keys from your account to the rescue system. +// let root_password = client.enable_rescue_mode(server_id); + +// 2. With a single SSH key ID: +// let ssh_key_id = 98765; // FIXME: Replace with your SSH key ID +// let root_password = client.enable_rescue_mode(server_id, ssh_key_id); + +// 3. With an array of SSH key IDs: +// let ssh_key_ids = [98765, 54321]; // FIXME: Replace with your SSH key IDs +// let root_password = client.enable_rescue_mode(server_id, ssh_key_ids); +// print(`Rescue mode enabled. Root password: ${root_password}`); + +// --- Disable Rescue Mode --- +// Disables rescue mode and reboots the server back into its normal OS. +// print(`Disabling rescue mode for server ID: ${server_id}...`); +// client.disable_rescue_mode(server_id); +// print("Rescue mode disabled."); \ No newline at end of file diff --git a/examples/05_list_ssh_keys.rhai b/examples/05_list_ssh_keys.rhai new file mode 100644 index 0000000..086115a --- /dev/null +++ b/examples/05_list_ssh_keys.rhai @@ -0,0 +1,11 @@ +// This script demonstrates how to list all SSH keys in your Hetzner Cloud project. + +// Initialize the Hetzner client with your API token. +let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); + +// Retrieve the list of all SSH keys. +print("Listing all SSH keys..."); +let ssh_keys = client.list_ssh_keys(); + +// The `show_table` method formats the SSH key list into a user-friendly table. +print(ssh_keys.show_table()); \ No newline at end of file diff --git a/examples/06_list_images.rhai b/examples/06_list_images.rhai new file mode 100644 index 0000000..3f174ee --- /dev/null +++ b/examples/06_list_images.rhai @@ -0,0 +1,58 @@ +// This script demonstrates how to list available images using various filters. +// It showcases the `ListImagesParamsBuilder` for customizing the query. + +// Initialize the Hetzner client with your API token. +let client = new_hetzner_client(get_env("HETZNER_API_TOKEN")); + +// Create a new builder for listing images. +// You can use this builder to filter and sort the results. +let params_builder = new_list_images_params_builder(); + +// The `ListImagesParamsBuilder` provides several optional methods: +// +// .with_status(status: string): +// Filters images by status. Can be "available" or "creating". +// +// .with_type(type: string): +// Filters images by type. Can be "system", "snapshot", or "backup". +// +// .with_sort(sort: string): +// Sorts the results. Can be "id", "id:asc", "id:desc", "name", "name:asc", +// "name:desc", "created", "created:asc", "created:desc". +// +// .with_bound_to(server_id: string): +// Filters images bound to a specific server ID. +// +// .with_include_deprecated(include: bool): +// Determines whether to include deprecated images. Defaults to `false`. +// +// .with_name(name: string): +// Filters images by name. +// +// .with_label_selector(selector: string): +// Filters by label selector. +// +// .with_architecture(architecture: string): +// Filters by architecture. Can be "x86" or "arm". + +// Example: List all available snapshots, sorted by creation date. +let params = params_builder + .with_type("snapshot") + .with_status("available") + .with_sort("created:desc"); + +// List the images using the configured parameters. +print("Listing all available snapshots..."); +let images = client.list_images(params); + +// Display the results in a table. +print(images.show_table()); + +// Example 2: Find a specific system image by name. +let params2 = new_list_images_params_builder() + .with_type("system") + .with_name("ubuntu-24.04"); + +print("\nFinding Ubuntu 24.04 image..."); +let ubuntu_image = client.list_images(params2); +print(ubuntu_image.show_table()); \ No newline at end of file diff --git a/test.rhai b/test.rhai deleted file mode 100644 index 7f67856..0000000 --- a/test.rhai +++ /dev/null @@ -1,47 +0,0 @@ -// Create client to communicate with Hetzner API -let client = new_hetzner_client(HETZNER_API_TOKEN); - -// List all servers and print in table -print("Listing all servers..."); -let servers = client.list_servers(); -print(servers.show_table()); - -// List all SSH keys and print in table -print("Listing all SSH keys..."); -let ssh_keys = client.list_ssh_keys(); -print(ssh_keys.show_table()); - -// List all images -let params = new_list_images_params_builder() - // .with_type("snapshot") - .with_status("available"); -let images = client.list_images(params); -print(images.show_table()); - -// Get server through ID and print details in table -print("Listing details from server with ID 104301883..."); -let test_server = client.get_server(104301883); -print(test_server.show_details()); - -// Enable rescue mode flag on server -// print(`Enabling rescue mode on server with ID: ${test_server.id}`); -// let root_password = client.enable_rescue_mode(test_server.id); -// print(`Root password is: ${root_password}`); - -// Enable rescue mode with multiple keys from array -let ssh_keys = [100324992, 100325001]; -let root_password = client.enable_rescue_mode(test_server.id, ssh_keys); - -// Read SSH key from env var and use it for rescue mode -// let ssh_key_from_env = get_env("SSH_KEY_ID"); -// if ssh_key_from_env != "" { -// client.enable_rescue_mode(test_server.id, ssh_key_from_env.parse_int()); -// } - -// Disable rescue mode flag on server -print(`Disabling rescue mode on server with ID: ${test_server.id}`); -client.disable_rescue_mode(test_server.id); - -// Reboot server -print(`Rebooting server with ID: ${test_server.id}`); -client.reboot(test_server.id); \ No newline at end of file