To interact with the Hetzner Cloud API, initialize a client using hcloud.NewClient with functional options like hcloud.WithToken. You can then use the client.Server service to create, retrieve, or manage servers.
Important: Many API operations are asynchronous. When an operation returns an Action, you should use client.Action.WaitFor (often combined with actionutil.AppendNext) to ensure the process completes before proceeding with the result.
package main
import (
"context"
"fmt"
"log"
"github.com/hetznercloud/hcloud-go/v2/hcloud"
"github.com/hetznercloud/hcloud-go/v2/hcloud/exp/actionutil"
)
func main() {
ctx := context.Background()
client := hcloud.NewClient(
hcloud.WithToken("token"),
hcloud.WithApplication("my-tool", "v1.0.0"),
)
result, _, err := client.Server.Create(ctx, hcloud.ServerCreateOpts{
Name: "Foo",
Image: &hcloud.Image{Name: "ubuntu-24.0"},
ServerType: &hcloud.ServerType{Name: "cpx22"},
Location: &hcloud.Location{Name: "hel1"},
})
if err != nil {
log.Fatalf("error creating server: %s\n", err)
}
// Always await any returned actions, to make sure the async process is completed before you use the result:
err = client.Action.WaitFor(ctx, actionutil.AppendNext(result.Action, result.NextActions)...)
if err != nil {
log.Fatalf("error creating server: %s\n", err)
}
server, _, err := client.Server.GetByID(ctx, result.Server.ID)
if err != nil {
log.Fatalf("error retrieving server: %s\n", err)
}
if server != nil {
fmt.Printf("server is called %q\n", server.Name) // prints 'server is called "Foo"'
} else {
fmt.Println("server not found")
}
}