-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.go
74 lines (62 loc) · 1.57 KB
/
main.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"context"
"flag"
"fmt"
"log"
"os"
"github.com/hetznercloud/hcloud-go/hcloud"
)
func main() {
apiKey := flag.String("key", "HCloud API Key", "-key xaxaxaxax")
floatIP := flag.String("ip", "Name of Floating IP", "-ip voip")
flag.Parse()
// Check for API Key
if *apiKey == "" {
log.Fatalf("No API Key specified!")
}
// Check for FloatingIP
if *floatIP == "" {
log.Fatalf("No Floating IP specified!")
}
// Get System Hostname
name, err := os.Hostname()
if err != nil {
panic(err)
}
// Initialize HCloud Client
client := hcloud.NewClient(hcloud.WithToken(*apiKey))
// Try Get Server by Name
server, _, err := client.Server.GetByName(context.Background(), name)
if err != nil {
// Request Error
log.Fatalf("error retrieving server: %s\n", err)
}
if server != nil {
// Server Found
response := fmt.Sprintf("Server called %v was found\n", server.Name)
fmt.Println(response)
ip, _, err := client.FloatingIP.Get(context.Background(), *floatIP)
if err != nil {
// Request Error
log.Fatalf("error retrieving floating ip: %s\n", err)
}
// IP Found
if ip != nil {
// Assign IP
_, res, err := client.FloatingIP.Assign(context.Background(), ip, server)
if err != nil {
// Request Error
log.Fatalf("error assigning floating ip: %s\n", res.Body)
}
} else {
// IP Not Found
response := fmt.Sprintf("ip with name %v was not found!", *floatIP)
fmt.Println(response)
}
} else {
// Server Not Found
response := fmt.Sprintf("server with name %v was not found!", name)
fmt.Println(response)
}
}