hetzner_rhai/examples/01_create_server.rhai
2025-07-17 14:03:49 +02:00

56 lines
2.5 KiB
Plaintext

// 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)");
}