forked from costela/hetzner-ip-floater
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.go
51 lines (45 loc) · 1.35 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package main
import (
"context"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"time"
"github.com/hetznercloud/hcloud-go/hcloud"
)
func main() {
log.Println("starting")
apikey, err := ioutil.ReadFile(os.Getenv("API_KEY_FILE"))
if err != nil {
log.Fatalf("could not read API_KEY_FILE ('%s'): %s", os.Getenv("API_KEY_FILE"), err)
}
client := hcloud.NewClient(hcloud.WithToken(strings.TrimSpace(string(apikey))))
targetHost := os.Getenv("TARGET_HOST")
targetServer, _, err := client.Server.GetByName(context.Background(), targetHost)
if err != nil {
log.Fatalf("could not find target server '%s': %s", targetHost, err)
}
floatingIPID, err := strconv.Atoi(os.Getenv("FLOATING_IP_ID"))
if err != nil {
log.Fatalf("FLOATING_IP_ID not an int: %s", err)
}
// make first tick immediate
ticker := time.Tick(30 * time.Second)
for ; true; <-ticker {
fip, _, err := client.FloatingIP.GetByID(context.Background(), floatingIPID)
if err != nil {
log.Fatalf("could not get floating IP %d: %s", floatingIPID, err)
}
if fip.Server != nil && fip.Server.ID == targetServer.ID {
log.Printf("already set to %s", targetServer.Name)
} else {
log.Printf("updating to %s", targetServer.Name)
_, _, err = client.FloatingIP.Assign(context.Background(), fip, targetServer)
if err != nil {
log.Printf("ERROR assigning floating IP: %s", err)
}
}
}
}