Skip to content

Instantly share code, notes, and snippets.

@geberl
Created October 15, 2022 11:37
Show Gist options
  • Save geberl/b144456cc88a33dedd30c6d79256ccce to your computer and use it in GitHub Desktop.
Save geberl/b144456cc88a33dedd30c6d79256ccce to your computer and use it in GitHub Desktop.
Using hcloud-go to enumerate locations in a network zone and pick a random one
package main
import (
"context"
"fmt"
"math/rand"
"time"
"github.com/hetznercloud/hcloud-go/hcloud"
)
func main() {
client := hcloud.NewClient(
hcloud.WithToken("super-secret"),
hcloud.WithApplication("hcloud-go-experiment", ""),
)
ctx := context.Background(
networkZone := hcloud.NetworkZoneEUCentral
// networkZone := hcloud.NetworkZoneUSEast
locations, err := client.Location.All(ctx)
if err != nil {
fmt.Printf("unable to query locations, %v\n", err)
return
}
locationsInZone := []*hcloud.Location{}
for _, location := range locations {
fmt.Printf("got location %s\n", location.Name)
if location.NetworkZone == networkZone {
locationsInZone = append(locationsInZone, location)
}
}
fmt.Printf("len locationsInZone %d\n", len(locationsInZone))
rand.Seed(time.Now().UnixNano())
randomIndex := rand.Intn(len(locationsInZone))
randomZone := locationsInZone[randomIndex]
fmt.Printf("randomly selected location in zone %s\n", randomZone.Name)
var nameStr string
nameStr = (*randomZone).Name
fmt.Printf("type '%T', name '%s'\n", nameStr, nameStr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment