forked from hetznercloud/cli
/
server_enable_rescue.go
71 lines (61 loc) · 1.94 KB
/
server_enable_rescue.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
package cli
import (
"fmt"
"github.com/hetznercloud/hcloud-go/hcloud"
"github.com/spf13/cobra"
)
func newServerEnableRescueCommand(cli *CLI) *cobra.Command {
cmd := &cobra.Command{
Use: "enable-rescue [FLAGS] SERVER",
Short: "Enable rescue for a server",
Args: cobra.ExactArgs(1),
TraverseChildren: true,
DisableFlagsInUseLine: true,
PreRunE: cli.ensureToken,
RunE: cli.wrap(runServerEnableRescue),
}
cmd.Flags().String("type", "linux64", "Rescue type")
cmd.Flag("type").Annotations = map[string][]string{
cobra.BashCompCustom: {"__hcloud_rescue_types"},
}
cmd.Flags().StringSlice("ssh-key", nil, "ID or name of SSH key to inject (can be specified multiple times)")
cmd.Flag("ssh-key").Annotations = map[string][]string{
cobra.BashCompCustom: {"__hcloud_sshkey_names"},
}
return cmd
}
func runServerEnableRescue(cli *CLI, cmd *cobra.Command, args []string) error {
idOrName := args[0]
server, _, err := cli.Client().Server.Get(cli.Context, idOrName)
if err != nil {
return err
}
if server == nil {
return fmt.Errorf("server not found: %s", idOrName)
}
var (
opts hcloud.ServerEnableRescueOpts
)
rescueType, _ := cmd.Flags().GetString("type")
opts.Type = hcloud.ServerRescueType(rescueType)
sshKeys, _ := cmd.Flags().GetStringSlice("ssh-key")
for _, sshKeyIDOrName := range sshKeys {
sshKey, _, err := cli.Client().SSHKey.Get(cli.Context, sshKeyIDOrName)
if err != nil {
return err
}
if sshKey == nil {
return fmt.Errorf("SSH key not found: %s", sshKeyIDOrName)
}
opts.SSHKeys = append(opts.SSHKeys, sshKey)
}
result, _, err := cli.Client().Server.EnableRescue(cli.Context, server, opts)
if err != nil {
return err
}
if err := cli.ActionProgress(cli.Context, result.Action); err != nil {
return err
}
fmt.Printf("Rescue enabled for server %s with root password: %s\n", server.Name, result.RootPassword)
return nil
}