package hetzner import ( "context" "fmt" "io" "os" "strings" "time" "git.stinnesbeck.com/go/jynx/backend/common" "git.stinnesbeck.com/go/log" "github.com/hetznercloud/hcloud-go/hcloud" ) func connect() *hcloud.Client { token := os.Getenv("HCLOUD_API_TOKEN") if token == "" { log.PrintError("please specify HCLOUD_API_TOKEN") os.Exit(1) } return hcloud.NewClient(hcloud.WithToken(token)) } func DestroyServer(s *hcloud.Server) error { client := connect() serverResponse, response, err := client.Server.DeleteWithResult(context.Background(), s) if err != nil { return err } log.PrintInfo(*serverResponse, *response) return nil } func ListServers() ([]common.Server, error) { client := connect() servers, err := client.Server.All(context.Background()) if err != nil { return nil, err } var managedServers []common.Server for i := range servers { // only look at servers, that we created if !strings.HasPrefix(servers[i].Name, os.Getenv("HCLOUD_PREFIX")) { continue } // append this server to our managed servers managedServers = append(managedServers, common.Server{ Name: servers[i].Name, Created: servers[i].Created, Deployed: true, }) } return managedServers, nil } func AddServer(s common.Server) error { client := connect() woodpeckerHost := os.Getenv("WOODPECKER_HOSTNAME") agentSecret := os.Getenv("WOODPECKER_AGENT_SECRET") AgentCMD := fmt.Sprintf("docker run -d -v /var/run/docker.sock:/var/run/docker.sock -e WOODPECKER_GRPC_SECURE=false -e WOODPECKER_SERVER=%s -e WOODPECKER_AGENT_SECRET=%s -e WOODPECKER_MAX_PROCS=%d -e WOODPECKER_HOSTNAME=%s", woodpeckerHost, agentSecret, 1, s.Name) userdata := fmt.Sprintf("#cloud-config\nruncmd:\n\t- %s", AgentCMD) fmt.Println(userdata) labels := make(map[string]string) labels["created_by"] = "jynx" labels["created"] = fmt.Sprintf("%d", time.Now().Unix()) // sshkeys, err := client.SSHKey.All(context.Background()) // if err != nil { // return err // } var sshkeys []*hcloud.SSHKey sshkeys, err := getSSHKeys("stefan", "nils") if err != nil { return nil } serverOpts := hcloud.ServerCreateOpts{ Name: s.Name, StartAfterCreate: hcloud.Ptr(true), SSHKeys: sshkeys, Image: &hcloud.Image{Name: "docker-ce"}, ServerType: &hcloud.ServerType{Name: "cax11"}, Location: &hcloud.Location{Name: "fsn1"}, UserData: userdata, PublicNet: &hcloud.ServerCreatePublicNet{EnableIPv4: true}, Labels: labels, } os.Exit(0) result, response, err := client.Server.Create(context.Background(), serverOpts) if err != nil { return err } io.ReadAll(response.Body) log.PrintInfo(fmt.Sprintf("%+v\n%+v\n", result, response.Response.Body)) return nil }