/
list_cluster.go
88 lines (78 loc) · 2.04 KB
/
list_cluster.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 main
import (
"fmt"
"github.com/chanwit/ekz/pkg/constants"
"k8s.io/client-go/tools/clientcmd"
"text/tabwriter"
"github.com/chanwit/script"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/util/sets"
)
var listClusterCmd = &cobra.Command{
Use: "cluster",
Aliases: []string{"clusters"},
Short: "List clusters",
Long: "List cluster command list all EKS-D clusters.",
Example: ` # List all EKS-D clusters
ekz list clusters
# List all EKS-D clusters (shorter syntax)
ekz ls
`,
RunE: listClusterCmdRun,
}
func init() {
listCmd.AddCommand(listClusterCmd)
}
func listClusters(clusterLabelKey string) ([]string, error) {
output := script.Var()
err := script.Exec("docker", "ps",
"-a", // show stopped nodes
// filter for nodes with the cluster label
"--filter", "label="+clusterLabelKey,
// format to include the cluster name
"--format", fmt.Sprintf(`{{.Label "%s"}}`, clusterLabelKey)).
To(output)
if err != nil {
return nil, errors.Wrap(err, "failed to list clusters")
}
return sets.NewString(output.Lines()...).List(), nil
}
func listClusterCmdRun(cmd *cobra.Command, args []string) error {
config, err := clientcmd.LoadFromFile(clientcmd.RecommendedHomeFile)
if err != nil {
return err
}
eksClusters, err := listClusters(constants.EKZClusterLabel)
if err != nil {
return err
}
kindClusters, err := listClusters(constants.KINDClusterLabel)
if err != nil {
return err
}
w := tabwriter.NewWriter(script.Stdout(), 0, 2, 3, ' ', 0)
fmt.Fprintf(w, "NAME\tPROVIDER\tCONTEXT-NAME\tACTIVE\n")
for _, c := range eksClusters {
context := "ekz-" + c
fmt.Fprintf(w, "%s\tekz\t", c)
active := " "
if config.CurrentContext == context {
active = " *"
}
fmt.Fprintf(w, "%s\t", context)
fmt.Fprintf(w, "%s\n", active)
}
for _, c := range kindClusters {
context := "kind-" + c
fmt.Fprintf(w, "%s\tkind\t", c)
active := " "
if config.CurrentContext == context {
active = " *"
}
fmt.Fprintf(w, "%s\t", context)
fmt.Fprintf(w, "%s\n", active)
}
w.Flush()
return nil
}