...
1
16
17 package config
18
19 import (
20 "fmt"
21 "io"
22
23 "github.com/spf13/cobra"
24 "k8s.io/client-go/tools/clientcmd"
25 cmdutil "k8s.io/kubectl/pkg/cmd/util"
26 "k8s.io/kubectl/pkg/util/completion"
27 "k8s.io/kubectl/pkg/util/i18n"
28 "k8s.io/kubectl/pkg/util/templates"
29 )
30
31 var (
32 deleteContextExample = templates.Examples(`
33 # Delete the context for the minikube cluster
34 kubectl config delete-context minikube`)
35 )
36
37
38 func NewCmdConfigDeleteContext(out, errOut io.Writer, configAccess clientcmd.ConfigAccess) *cobra.Command {
39 cmd := &cobra.Command{
40 Use: "delete-context NAME",
41 DisableFlagsInUseLine: true,
42 Short: i18n.T("Delete the specified context from the kubeconfig"),
43 Long: i18n.T("Delete the specified context from the kubeconfig."),
44 Example: deleteContextExample,
45 ValidArgsFunction: completion.ContextCompletionFunc,
46 Run: func(cmd *cobra.Command, args []string) {
47 cmdutil.CheckErr(runDeleteContext(out, errOut, configAccess, cmd))
48 },
49 }
50
51 return cmd
52 }
53
54 func runDeleteContext(out, errOut io.Writer, configAccess clientcmd.ConfigAccess, cmd *cobra.Command) error {
55 config, err := configAccess.GetStartingConfig()
56 if err != nil {
57 return err
58 }
59
60 args := cmd.Flags().Args()
61 if len(args) != 1 {
62 cmd.Help()
63 return nil
64 }
65
66 configFile := configAccess.GetDefaultFilename()
67 if configAccess.IsExplicitFile() {
68 configFile = configAccess.GetExplicitFile()
69 }
70
71 name := args[0]
72 _, ok := config.Contexts[name]
73 if !ok {
74 return fmt.Errorf("cannot delete context %s, not in %s", name, configFile)
75 }
76
77 if config.CurrentContext == name {
78 fmt.Fprint(errOut, "warning: this removed your active context, use \"kubectl config use-context\" to select a different one\n")
79 }
80
81 delete(config.Contexts, name)
82
83 if err := clientcmd.ModifyConfig(configAccess, *config, true); err != nil {
84 return err
85 }
86
87 fmt.Fprintf(out, "deleted context %s from %s\n", name, configFile)
88
89 return nil
90 }
91
View as plain text