-
Notifications
You must be signed in to change notification settings - Fork 20
/
sshkey_list.go
88 lines (70 loc) · 1.83 KB
/
sshkey_list.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
package cmd
import (
"fmt"
"strings"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
type sshkeyListItemOutput struct {
Name string `json:"name"`
Fingerprint string `json:"fingerprint"`
}
type sshkeyListOutput []sshkeyListItemOutput
func (o *sshkeyListOutput) toJSON() { outputJSON(o) }
func (o *sshkeyListOutput) toText() { outputText(o) }
func (o *sshkeyListOutput) toTable() { outputTable(o) }
func init() {
sshkeyCmd.AddCommand(&cobra.Command{
Use: "list [filter ...]",
Short: "List SSH Keys",
Long: fmt.Sprintf(`This command lists existing SSH Keys.
Optional patterns can be provided to filter results by name or fingerprint.
Supported output template annotations: %s`,
strings.Join(outputterTemplateAnnotations(&sshkeyListOutput{}), ", ")),
Aliases: gListAlias,
RunE: func(cmd *cobra.Command, args []string) error {
return output(listSSHKey(args))
},
})
}
func listSSHKey(filters []string) (outputter, error) {
sshKeys, err := getSSHKeys(cs)
if err != nil {
return nil, err
}
out := sshkeyListOutput{}
for _, k := range sshKeys {
keep := true
if len(filters) > 0 {
keep = false
s := strings.ToLower(fmt.Sprintf("%s#%s", k.Name, k.Fingerprint))
for _, filter := range filters {
substr := strings.ToLower(filter)
if strings.Contains(s, substr) {
keep = true
break
}
}
}
if !keep {
continue
}
out = append(out, sshkeyListItemOutput{
Name: k.Name,
Fingerprint: k.Fingerprint,
})
}
return &out, nil
}
func getSSHKeys(cs *egoscale.Client) ([]egoscale.SSHKeyPair, error) {
sshKeys, err := cs.ListWithContext(gContext, &egoscale.SSHKeyPair{})
if err != nil {
return nil, err
}
res := make([]egoscale.SSHKeyPair, len(sshKeys))
for i, key := range sshKeys {
k := key.(*egoscale.SSHKeyPair)
res[i] = *k
}
return res, nil
}