forked from MusicDin/kubitect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmd_export_kubeconfig.go
99 lines (72 loc) · 2.18 KB
/
cmd_export_kubeconfig.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
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"os"
"github.com/MusicDin/kubitect/pkg/app"
"github.com/MusicDin/kubitect/pkg/utils/file"
"github.com/spf13/cobra"
)
var (
exportKcShort = "Export cluster kubeconfig file"
exportKcLong = LongDesc(`
Command export kubeconfig outputs cluster's kubeconfig file to standard output.`)
exportKcExample = Example(`
To save a kubeconfig to the specific file, redirect command output to that file:
> kubitect export kubeconfig --cluster lake > lake.yaml
Use kubeconfig with kubectl to access cluster:
> kubectl --kubeconfig lake.yaml get nodes`)
)
type ExportKcOptions struct {
ClusterName string
app.AppContextOptions
}
func NewExportKcCmd() *cobra.Command {
var o ExportKcOptions
cmd := &cobra.Command{
SuggestFor: []string{"kubecfg", "kube", "kc"},
Use: "kubeconfig",
GroupID: "main",
Short: exportKcShort,
Long: exportKcLong,
Example: exportKcExample,
RunE: func(cmd *cobra.Command, args []string) error {
return o.Run()
},
}
cmd.PersistentFlags().StringVar(&o.ClusterName, "cluster", "", "specify the cluster to be used")
cmd.MarkPersistentFlagRequired("cluster")
cmd.RegisterFlagCompletionFunc("cluster", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var names []string
clusters, err := AllClusters(o.AppContext())
if err != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
for _, c := range clusters {
if c.ContainsKubeconfig() {
names = append(names, c.Name)
}
}
return names, cobra.ShellCompDirectiveNoFileComp
})
return cmd
}
func (o *ExportKcOptions) Run() error {
cs, err := AllClusters(o.AppContext())
c := cs.FindByName(o.ClusterName)
if c == nil {
return fmt.Errorf("cluster '%s' does not exist", o.ClusterName)
}
count := cs.CountByName(o.ClusterName)
if count > 1 {
return fmt.Errorf("multiple clusters (%d) have been found with the name '%s'", count, o.ClusterName)
}
if !c.ContainsKubeconfig() {
return fmt.Errorf("cluster '%s' does not have a Kubeconfig file", o.ClusterName)
}
kc, err := file.Read(c.KubeconfigPath())
if err != nil {
return err
}
fmt.Fprint(os.Stdout, kc)
return nil
}