Skip to content

Commit

Permalink
rm kubeconfig after deleting cluster
Browse files Browse the repository at this point in the history
  • Loading branch information
uzaxirr committed Sep 9, 2024
1 parent 2711c1d commit 3571a12
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
34 changes: 34 additions & 0 deletions cmd/kubernetes/kubernetes_remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"

pluralize "github.com/alejandrojnm/go-pluralize"
Expand All @@ -15,6 +17,7 @@ import (
)

var kuberneteList []utility.ObjecteList
var keepConfig bool
var kubernetesRemoveCmd = &cobra.Command{
Use: "remove",
Aliases: []string{"rm", "delete", "destroy"},
Expand Down Expand Up @@ -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()
Expand All @@ -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
}

0 comments on commit 3571a12

Please sign in to comment.