-
Notifications
You must be signed in to change notification settings - Fork 20
/
eip_dissociate.go
91 lines (75 loc) · 1.91 KB
/
eip_dissociate.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
88
89
90
91
package cmd
import (
"fmt"
"net"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
var eipDissociateCmd = &cobra.Command{
Use: "dissociate IP-ADDRESS INSTANCE-NAME|ID",
Short: "Dissociate an Elastic IP from a Compute instance",
Aliases: gDissociateAlias,
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 2 {
return cmd.Usage()
}
force, err := cmd.Flags().GetBool("force")
if err != nil {
return err
}
tasks := make([]task, 0, len(args[1:]))
ipAddr := args[0]
ip := net.ParseIP(ipAddr)
if ip == nil {
return fmt.Errorf("invalid IP address %q", ipAddr)
}
for _, arg := range args[1:] {
vm, err := getVirtualMachineByNameOrID(arg)
if err != nil {
return err
}
if !force {
if !askQuestion(fmt.Sprintf("Are you sure you want to dissociate %q EIP from %q?", ip.String(), vm.Name)) {
continue
}
}
cmd, err := prepareDissociateIP(vm, ip)
if err != nil {
return err
}
tasks = append(tasks, task{
cmd,
fmt.Sprintf("dissociate %q EIP", cmd.ID.String()),
})
}
resps := asyncTasks(tasks)
errs := filterErrors(resps)
if len(errs) > 0 {
return errs[0]
}
return nil
},
}
func prepareDissociateIP(vm *egoscale.VirtualMachine, ip net.IP) (*egoscale.RemoveIPFromNic, error) {
defaultNic := vm.DefaultNic()
if defaultNic == nil {
return nil, fmt.Errorf("the instance %q has no default NIC", vm.ID)
}
eipID, err := getSecondaryIP(defaultNic, ip)
if err != nil {
return nil, err
}
return &egoscale.RemoveIPFromNic{ID: eipID}, nil
}
func getSecondaryIP(nic *egoscale.Nic, ip net.IP) (*egoscale.UUID, error) {
for _, sIP := range nic.SecondaryIP {
if sIP.IPAddress.Equal(ip) {
return sIP.ID, nil
}
}
return nil, fmt.Errorf("Elastic IP %q not found", ip) // nolint
}
func init() {
eipDissociateCmd.Flags().BoolP("force", "f", false, cmdFlagForceHelp)
eipCmd.AddCommand(eipDissociateCmd)
}