...
1
16
17 package config
18
19 import (
20 "errors"
21 "fmt"
22 "io"
23
24 "github.com/spf13/cobra"
25
26 "k8s.io/client-go/tools/clientcmd"
27 clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
28 cmdutil "k8s.io/kubectl/pkg/cmd/util"
29 "k8s.io/kubectl/pkg/util/completion"
30 "k8s.io/kubectl/pkg/util/i18n"
31 "k8s.io/kubectl/pkg/util/templates"
32 )
33
34 var (
35 useContextExample = templates.Examples(`
36 # Use the context for the minikube cluster
37 kubectl config use-context minikube`)
38 )
39
40 type useContextOptions struct {
41 configAccess clientcmd.ConfigAccess
42 contextName string
43 }
44
45
46 func NewCmdConfigUseContext(out io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
47 options := &useContextOptions{configAccess: configAccess}
48
49 cmd := &cobra.Command{
50 Use: "use-context CONTEXT_NAME",
51 DisableFlagsInUseLine: true,
52 Short: i18n.T("Set the current-context in a kubeconfig file"),
53 Aliases: []string{"use"},
54 Long: `Set the current-context in a kubeconfig file.`,
55 Example: useContextExample,
56 ValidArgsFunction: completion.ContextCompletionFunc,
57 Run: func(cmd *cobra.Command, args []string) {
58 cmdutil.CheckErr(options.complete(cmd))
59 cmdutil.CheckErr(options.run())
60 fmt.Fprintf(out, "Switched to context %q.\n", options.contextName)
61 },
62 }
63
64 return cmd
65 }
66
67 func (o useContextOptions) run() error {
68 config, err := o.configAccess.GetStartingConfig()
69 if err != nil {
70 return err
71 }
72
73 err = o.validate(config)
74 if err != nil {
75 return err
76 }
77
78 config.CurrentContext = o.contextName
79
80 return clientcmd.ModifyConfig(o.configAccess, *config, true)
81 }
82
83 func (o *useContextOptions) complete(cmd *cobra.Command) error {
84 endingArgs := cmd.Flags().Args()
85 if len(endingArgs) != 1 {
86 return helpErrorf(cmd, "Unexpected args: %v", endingArgs)
87 }
88
89 o.contextName = endingArgs[0]
90 return nil
91 }
92
93 func (o useContextOptions) validate(config *clientcmdapi.Config) error {
94 if len(o.contextName) == 0 {
95 return errors.New("empty context names are not allowed")
96 }
97
98 for name := range config.Contexts {
99 if name == o.contextName {
100 return nil
101 }
102 }
103
104 return fmt.Errorf("no context exists with the name: %q", o.contextName)
105 }
106
View as plain text