From 13f5f1ac6a8dce566775b31530bd79dbac36a4d2 Mon Sep 17 00:00:00 2001 From: Uzair Ali <72073401+uzaxirr@users.noreply.github.com> Date: Mon, 9 Sep 2024 14:42:45 +0530 Subject: [PATCH] rm kubeconfig after deleting cluster --- cmd/kubernetes/kubernetes.go | 1 + cmd/kubernetes/kubernetes_remove.go | 34 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/cmd/kubernetes/kubernetes.go b/cmd/kubernetes/kubernetes.go index 5789bff3..32673132 100644 --- a/cmd/kubernetes/kubernetes.go +++ b/cmd/kubernetes/kubernetes.go @@ -100,6 +100,7 @@ func init() { kubernetesCreateCmd.Flags().StringVarP(&clusterType, "cluster-type", "", "k3s", "optional, possible options: k3s,talos.") kubernetesRenameCmd.Flags().StringVarP(&kubernetesNewName, "name", "n", "", "the new name for the cluster.") + kubernetesRemoveCmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the kubectl config after deleting the cluster") kubernetesUpgradeCmd.Flags().StringVarP(&kubernetesNewVersion, "version", "v", "", "change the version of the cluster.") kubernetesUpgradeCmd.MarkFlagRequired("version") diff --git a/cmd/kubernetes/kubernetes_remove.go b/cmd/kubernetes/kubernetes_remove.go index d9959079..4952ee8e 100644 --- a/cmd/kubernetes/kubernetes_remove.go +++ b/cmd/kubernetes/kubernetes_remove.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "os" + "os/exec" + "path/filepath" "strings" pluralize "github.com/alejandrojnm/go-pluralize" @@ -15,6 +17,7 @@ import ( ) var kuberneteList []utility.ObjecteList +var keepConfig bool var kubernetesRemoveCmd = &cobra.Command{ Use: "remove", Aliases: []string{"rm", "delete", "destroy"}, @@ -89,6 +92,13 @@ var kubernetesRemoveCmd = &cobra.Command{ utility.Error("error deleting the kubernetes cluster: %s", err) os.Exit(1) } + + if !keepConfig { + err = removeKubectlConfig(v.Name) + if err != nil { + utility.Warning("Failed to remove kubectl config for cluster %s: %s", v.Name, err) + } + } } ow := utility.NewOutputWriter() @@ -115,3 +125,27 @@ var kubernetesRemoveCmd = &cobra.Command{ } }, } + +func removeKubectlConfig(clusterName string) error { + kubeConfigPath := os.Getenv("KUBECONFIG") + if kubeConfigPath == "" { + kubeConfigPath = filepath.Join(os.Getenv("HOME"), ".kube", "config") + } + + cmd := exec.Command("kubectl", "config", "delete-context", clusterName) + if err := cmd.Run(); err != nil { + return fmt.Errorf("failed to delete context: %w", err) + } + + cmd = exec.Command("kubectl", "config", "delete-cluster", clusterName) + if err := cmd.Run(); err != nil { + return fmt.Errorf("failed to delete cluster: %w", err) + } + + cmd = exec.Command("kubectl", "config", "unset", fmt.Sprintf("users.%s", clusterName)) + if err := cmd.Run(); err != nil { + return fmt.Errorf("failed to unset user: %w", err) + } + + return nil +}