From 6505dfad6249a6c84022d953f48d80b90295c37b Mon Sep 17 00:00:00 2001 From: Kyle Bai Date: Thu, 4 Jul 2019 12:20:06 +0800 Subject: [PATCH] Delete kubeconfig when a machine has been deleted --- cmd/minikube/cmd/delete.go | 6 ++++++ pkg/util/kubeconfig.go | 26 ++++++++++++++++++++++++++ pkg/util/kubeconfig_test.go | 24 ++++++++++++++++++++++++ 3 files changed, 56 insertions(+) diff --git a/cmd/minikube/cmd/delete.go b/cmd/minikube/cmd/delete.go index 754ad7c550..e774c173cf 100644 --- a/cmd/minikube/cmd/delete.go +++ b/cmd/minikube/cmd/delete.go @@ -31,6 +31,7 @@ import ( "k8s.io/minikube/pkg/minikube/constants" "k8s.io/minikube/pkg/minikube/exit" "k8s.io/minikube/pkg/minikube/machine" + pkgutil "k8s.io/minikube/pkg/util" ) // deleteCmd represents the delete command @@ -94,6 +95,11 @@ func runDelete(cmd *cobra.Command, args []string) { exit.WithError("Failed to remove profile", err) } console.OutStyle(console.Crushed, "The %q cluster has been deleted.", profile) + + machineName := pkg_config.GetMachineName() + if err := pkgutil.DeleteKubeConfigContext(constants.KubeconfigPath, machineName); err != nil { + exit.WithError("update config", err) + } } func init() { diff --git a/pkg/util/kubeconfig.go b/pkg/util/kubeconfig.go index a8f0fc38de..429fb928d8 100644 --- a/pkg/util/kubeconfig.go +++ b/pkg/util/kubeconfig.go @@ -344,3 +344,29 @@ func SetCurrentContext(kubeCfgPath, name string) error { } return nil } + +// DeleteKubeConfigContext deletes the specified machine's kubeconfig context +func DeleteKubeConfigContext(kubeCfgPath, machineName string) error { + kcfg, err := ReadConfigOrNew(kubeCfgPath) + if err != nil { + return errors.Wrap(err, "Error getting kubeconfig status") + } + + if kcfg == nil || api.IsConfigEmpty(kcfg) { + glog.V(2).Info("kubeconfig is empty") + return nil + } + + delete(kcfg.Clusters, machineName) + delete(kcfg.AuthInfos, machineName) + delete(kcfg.Contexts, machineName) + + if kcfg.CurrentContext == machineName { + kcfg.CurrentContext = "" + } + + if err := WriteConfig(kcfg, kubeCfgPath); err != nil { + return errors.Wrap(err, "writing kubeconfig") + } + return nil +} diff --git a/pkg/util/kubeconfig_test.go b/pkg/util/kubeconfig_test.go index cdccd60631..31e8c74165 100644 --- a/pkg/util/kubeconfig_test.go +++ b/pkg/util/kubeconfig_test.go @@ -370,6 +370,30 @@ func TestGetIPFromKubeConfig(t *testing.T) { } } +func TestDeleteKubeConfigContext(t *testing.T) { + configFilename := tempFile(t, fakeKubeCfg) + if err := DeleteKubeConfigContext(configFilename, "la-croix"); err != nil { + t.Fatal(err) + } + + cfg, err := ReadConfigOrNew(configFilename) + if err != nil { + t.Fatal(err) + } + + if len(cfg.AuthInfos) != 0 { + t.Fail() + } + + if len(cfg.Clusters) != 0 { + t.Fail() + } + + if len(cfg.Contexts) != 0 { + t.Fail() + } +} + // tempFile creates a temporary with the provided bytes as its contents. // The caller is responsible for deleting file after use. func tempFile(t *testing.T, data []byte) string {