hcloud-go

repository·main·Indexed 19 days ago

https://github.com/hetznercloud/hcloud-go

A Go library for interacting with the Hetzner Cloud API, providing typed access to cloud resources such as servers and networks. It includes a client for managing resources, a metadata client for accessing server metadata endpoints, and support for paginated resource listing, custom retry/polling strategies, and asynchronous action handling.

Tokens
7.4K
Snippets
20
Records
28
Agent score
67%

What's inside hcloud-go

  1. Understand experimental features

    main

    Experimental features are included in regular releases but may undergo breaking changes within minor releases. They are categorized by maturity levels (e.g., experimental, alpha, beta) based on the maturity of the upstream Hetzner Cloud API.

    To identify experimental features in the source code, look for the following comment pattern:

    // Experimental: $PRODUCT is $MATURITY, breaking changes may occur within minor releases.
    // See https://docs.hetzner.cloud/changelog#$SLUG for more details.
  2. Use experimental features in hcloud-go

    main

    The exp namespace contains experimental features of the hcloud-go library. These features are subject to breaking changes without notice and should not be used in production. Once a feature reaches sufficient stability, it may be moved out of the exp namespace into the main library.

    Within the experimental namespace, the exp/kit sub-namespace is reserved for utility features that are not directly related to the core hcloud-go library (for example, the sshutil package for generating SSH keys).

  3. Migrate from v1 to v2

    main

    Version 2.0.0 introduced a breaking change where all ID fields were changed from int to int64.

    To migrate:

    1. Update your imports to use the v2 module path: github.com/hetznercloud/hcloud-go/v2/hcloud
    2. Update integer parsing and formatting logic:
      • Replace strconv.Atoi(idString) with strconv.ParseInt(idString, 10, 64)
      • Replace strconv.Itoa(id) with strconv.FormatInt(id, 10)
     import (
    -  "github.com/hetznercloud/hcloud-go/hcloud"
    +  "github.com/hetznercloud/hcloud-go/v2/hcloud"
     )
  4. Understand Server status values

    main

    A Server has a Status field of type ServerStatus. Common statuses include:

    • ServerStatusInitializing: Server is being provisioned.
    • ServerStatusRunning: Server is active.
    • ServerStatusOff: Server is powered off.
    • ServerStatusStarting / ServerStatusStopping: Transitionary states.
    • ServerStatusMigrating: Server is being moved between hosts.
    • ServerStatusRebuilding: Server is undergoing a rebuild.
    • ServerStatusDeleting: Server is being removed.
  5. Server networking schemas

    main

    The Server resource manages networking through two primary interfaces: PublicNet for internet-facing traffic and PrivateNet for internal network communication.

    Public Networking

    • ServerPublicNet: Contains IPv4, IPv6, Floating IPs, and attached Firewalls.
    • ServerPublicNetIPv4: Details for an IPv4 address, including IP, Blocked status, and DNSPtr.
    • ServerPublicNetIPv6: Details for an IPv6 address, including a slice of ServerPublicNetIPv6DNSPtr for reverse DNS.

    Private Networking

    • ServerPrivateNet: Represents a private network interface, including the Network ID, IP, AliasIPs, and MACAddress.
    type ServerPublicNet struct {
    	IPv4        ServerPublicNetIPv4 `json:"ipv4"`
    	IPv6        ServerPublicNetIPv6 `json:"ipv6"`
    	FloatingIPs []int64             `json:"floating_ips"`
    	Firewalls   []ServerFirewall    `json:"firewalls"`
    }
    
    type ServerPrivateNet struct {
    	Network    int64    `json:"network"`
    	IP         string   `json:"ip"`
    	AliasIPs   []string `json:"alias_ips"`
    	MACAddress string   `json:"mac_address"`
    }
  6. Perform server actions (Power, Reboot, Rebuild, etc.)

    main

    Server actions are asynchronous operations performed on a server. Each action has a corresponding Request struct and a Response struct that contains an Action object to track progress.

    Common Actions

    • Power Management: ServerActionPoweronRequest, ServerActionPoweroffRequest, ServerActionRebootRequest, ServerActionResetRequest, ServerActionShutdownRequest.
    • Image & Recovery: ServerActionCreateImageRequest (creates a snapshot), ServerActionRebuildRequest (reinstalls an image), ServerActionEnableRescueRequest (enables rescue mode).
    • Configuration: ServerActionChangeTypeRequest (resizes server), ServerActionChangeProtectionRequest (toggles delete/rebuild protection), ServerActionAttachISORequest (mounts an ISO).
    • Networking: ServerActionAttachToNetworkRequest, ServerActionDetachFromNetworkRequest, ServerActionChangeDNSPtrRequest.
    • Console: ServerActionRequestConsoleRequest (returns a WebSocket VNC URL and password).
    // Example: Rebuild request
    type ServerActionRebuildRequest struct {
    	Image    IDOrName `json:"image"`
    	UserData *string  `json:"user_data,omitempty"`
    }
    
    // Example: Console request
    type ServerActionRequestConsoleRequest struct{}
    
    type ServerActionRequestConsoleResponse struct {
    	Action   Action `json:"action"`
    	WSSURL   string `json:"wss_url"`
    	Password string `json:"password"`
    }
  7. Server network configuration

    main

    Servers interact with networks via PublicNet and PrivateNet:

    Public Network

    Managed via ServerPublicNet. It contains:

    • IPv4: ServerPublicNetIPv4 (ID, IP, Blocked status, and DNSPtr).
    • IPv6: ServerPublicNetIPv6 (ID, IP, Network subnet, Blocked status, and a DNSPtr map).
    • FloatingIPs: A list of attached *FloatingIP resources.
    • Firewalls: A list of *ServerFirewallStatus showing which firewalls are applied.

    Private Network

    Managed via ServerPrivateNet. A server can be attached to multiple private networks. Each attachment includes:

    • Network: The *Network resource.
    • IP: The assigned IP address.
    • Aliases: Additional IP aliases.
    • MACAddress: The hardware address on that network.

    Use PrivateNetFor(network *Network) on a Server instance to find the specific attachment details for a given network.

  8. Understand API Response Metadata

    main

    Every response from the Do method includes a Meta object containing critical API state:

    Pagination

    Found in Meta.Pagination. Helps navigate large result sets.

    • Page, PerPage: Current page context.
    • PreviousPage, NextPage: Links to adjacent pages.
    • LastPage: The final page number.
    • TotalEntries: Total number of items matching the query.

    Ratelimit

    Found in Meta.Ratelimit. Helps prevent 429 errors.

    • Limit: Total allowed requests in the current window.
    • Remaining: Requests left in the current window.
    • Reset: The time when the rate limit window resets.
  9. Initialize a new hcloud Client

    main

    Use hcloud.NewClient to create a new client for interacting with the Hetzner Cloud API. You can pass several ClientOption functions to configure authentication, endpoints, and behavior.

    Common options include:

    • hcloud.WithToken(token string): Sets the API token for authentication.
    • hcloud.WithEndpoint(endpoint string): Sets a custom Cloud API endpoint.
    • hcloud.WithHetznerEndpoint(endpoint string): Sets a custom Hetzner API endpoint (experimental, used for Storage Boxes).
    • hcloud.WithDebugWriter(io.Writer): Directs debug information to a writer (e.g., os.Stderr).
    • hcloud.WithHTTPClient(httpClient *http.Client): Provides a custom HTTP client.
    • hcloud.WithApplication(name, version string): Sets a custom User-Agent for the library.
    import "github.com/hetznercloud/hcloud-go/v2/hcloud"
    
    client := hcloud.NewClient(
    	hcloud.WithToken("YOUR_API_TOKEN"),
    	hcloud.WithDebugWriter(os.Stderr),
    )
  10. Create a client and manage servers

    main

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