Skip to content

Commit

Permalink
Generate random name for HCloud server
Browse files Browse the repository at this point in the history
  • Loading branch information
arnarg committed Mar 7, 2021
1 parent bab5cbf commit 2beeaf9
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 4 additions & 0 deletions doc/providers/hcloud.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ target "<address>" "hcloud" {
# The API token to use. (Required)
token = "9vx8w..."
# The name of the server to launch. Will be
# suffixed by a random string. (Required)
name = "lazyssh-ubuntu"
# The image to launch. (Required)
image = "ubuntu-20.03"
Expand Down
17 changes: 16 additions & 1 deletion providers/hcloud/impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package hcloud
import (
"fmt"
"log"
"math/rand"
"net"
"strings"
"time"
Expand All @@ -24,6 +25,7 @@ func init() {
type Factory struct{}

type Provider struct {
Name string
Image string
ServerType string
SSHKey string
Expand All @@ -43,6 +45,7 @@ type state struct {

type hclTarget struct {
Token string `hcl:"token,attr"`
Name string `hcl:"name,attr"`
Image string `hcl:"image,attr"`
ServerType string `hcl:"server_type,attr"`
SSHKey string `hcl:"ssh_key,attr"`
Expand Down Expand Up @@ -70,6 +73,7 @@ func (factory *Factory) NewProvider(target string, hclBlock hcl.Body) (providers

prov := &Provider{
HCloud: client,
Name: parsed.Name,
Image: parsed.Image,
ServerType: parsed.ServerType,
SSHKey: parsed.SSHKey,
Expand Down Expand Up @@ -174,7 +178,7 @@ func (prov *Provider) start(mach *providers.Machine) bool {
}

opts := hcloud.ServerCreateOpts{
Name: "lazyssh",
Name: randomName(prov.Name),
ServerType: serverType,
Image: image,
SSHKeys: []*hcloud.SSHKey{sshKey},
Expand Down Expand Up @@ -221,6 +225,17 @@ func (prov *Provider) start(mach *providers.Machine) bool {
return true
}

func randomName(p string) string {
var n = 5
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

s := make([]rune, n)
for i := range s {
s[i] = letters[rand.Intn(len(letters))]
}
return fmt.Sprintf("%s-%s", p, string(s))
}

func serverIsStarting(server *hcloud.Server) bool {
return server.Status == hcloud.ServerStatusInitializing ||
server.Status == hcloud.ServerStatusStarting ||
Expand Down

0 comments on commit 2beeaf9

Please sign in to comment.