Skip to content

Commit

Permalink
Merge pull request #4678 from kairen/delete-kubeconfig
Browse files Browse the repository at this point in the history
Delete kubeconfig context when a machine has been deleted
  • Loading branch information
medyagh authored Jul 5, 2019
2 parents b1648ca + 6505dfa commit 11f8c61
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
6 changes: 6 additions & 0 deletions cmd/minikube/cmd/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand Down
26 changes: 26 additions & 0 deletions pkg/util/kubeconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
24 changes: 24 additions & 0 deletions pkg/util/kubeconfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 11f8c61

Please sign in to comment.