forked from hetznercloud/cli
/
floatingip_create.go
87 lines (74 loc) · 2.42 KB
/
floatingip_create.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
75
76
77
78
79
80
81
82
83
84
85
86
87
package cli
import (
"errors"
"fmt"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/spf13/cobra"
)
func newFloatingIPCreateCommand(cli *CLI) *cobra.Command {
cmd := &cobra.Command{
Use: "create FLAGS",
Short: "Create a Floating IP",
Args: cobra.NoArgs,
TraverseChildren: true,
DisableFlagsInUseLine: true,
PreRunE: chainRunE(validateFloatingIPCreate, cli.ensureToken),
RunE: cli.wrap(runFloatingIPCreate),
}
cmd.Flags().String("type", "", "Type (ipv4 or ipv6)")
cmd.Flag("type").Annotations = map[string][]string{
cobra.BashCompCustom: {"__hcloud_floatingip_types"},
}
cmd.MarkFlagRequired("type")
cmd.Flags().String("description", "", "Description")
cmd.Flags().String("home-location", "", "Home location")
cmd.Flag("home-location").Annotations = map[string][]string{
cobra.BashCompCustom: {"__hcloud_location_names"},
}
cmd.Flags().String("server", "", "Server to assign Floating IP to")
cmd.Flag("server").Annotations = map[string][]string{
cobra.BashCompCustom: {"__hcloud_server_names"},
}
return cmd
}
func validateFloatingIPCreate(cmd *cobra.Command, args []string) error {
typ, _ := cmd.Flags().GetString("type")
if typ == "" {
return errors.New("type is required")
}
homeLocation, _ := cmd.Flags().GetString("home-location")
server, _ := cmd.Flags().GetString("server")
if homeLocation == "" && server == "" {
return errors.New("one of --home-location or --server is required")
}
return nil
}
func runFloatingIPCreate(cli *CLI, cmd *cobra.Command, args []string) error {
typ, _ := cmd.Flags().GetString("type")
description, _ := cmd.Flags().GetString("description")
homeLocation, _ := cmd.Flags().GetString("home-location")
serverNameOrID, _ := cmd.Flags().GetString("server")
opts := hcloud.FloatingIPCreateOpts{
Type: hcloud.FloatingIPType(typ),
Description: &description,
}
if homeLocation != "" {
opts.HomeLocation = &hcloud.Location{Name: homeLocation}
}
if serverNameOrID != "" {
server, _, err := cli.Client().Server.Get(cli.Context, serverNameOrID)
if err != nil {
return err
}
if server == nil {
return fmt.Errorf("server not found: %s", serverNameOrID)
}
opts.Server = server
}
result, _, err := cli.Client().FloatingIP.Create(cli.Context, opts)
if err != nil {
return err
}
fmt.Printf("Floating IP %d created\n", result.FloatingIP.ID)
return nil
}