diff --git a/README.md b/README.md index 65fde7e..623791f 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ Q&A: * What if I like doing things the long way? - You can combine `kubectl config get-clusters` with `kubectl config use-context` and `kubectl get nodes`, followed by `kubectl config delete-cluster` and `kubectl config delete-context` for each. + You can combine `kubectl config get-clusters` with `kubectl config use-context` and `kubectl get nodes`, followed by `kubectl config delete-cluster` and `kubectl config delete-context` for each. `kubectx -d` will remove a context, but leaves the cluster in your kubeconfig file, so requires additional steps. * Doesn't [my favourite tool] have an option to do this? @@ -35,6 +35,10 @@ Q&A: Yes, you can add `kubetrim &` to your `.bashrc`, `.bash_profile` or `.zshrc` file, which will run in the background, and not slow down your terminal session from starting up. +* What if my WiFi is down and I run this tool? + + If all clusters show as unavailable, kubetrim will not delete any clusters, in this case add `--force` to the command. + ## Usage ```bash @@ -62,6 +66,20 @@ default kind-2 ``` +What if the Internet is unavailable, and all clusters report as unavailable? + +```bash +# Take down WiFi/Ethernet + +$ kubetrim + +No contexts are working, the Internet may be down, use --force to delete all contexts anyway. + +# Force the deletion, even if all clusters are unavailable. + +$ kubetrim --force +``` + Try out kubetrim without writing changes to the kubeconfig file: ```bash diff --git a/main.go b/main.go index 6229bf8..78c1d31 100644 --- a/main.go +++ b/main.go @@ -24,6 +24,7 @@ import ( var ( writeFile bool + force bool ) func main() { @@ -44,6 +45,7 @@ func main() { } flag.BoolVar(&writeFile, "write", true, "Write changes to the kubeconfig file") + flag.BoolVar(&force, "force", false, "Force delete all contexts, even if all are unreachable") flag.Parse() // Load the kubeconfig file @@ -102,11 +104,18 @@ func main() { } if writeFile { - // Save the modified kubeconfig - if err = clientcmd.WriteToFile(*config, kubeconfig); err != nil { - fmt.Printf("Error saving updated kubeconfig: %v\n", err) + + if len(contextsToDelete) == len(config.Contexts) && !force { + fmt.Println("No contexts are working, the Internet may be down, use --force to delete all contexts anyway.") os.Exit(1) } + if len(contextsToDelete) > 0 { + // Save the modified kubeconfig + if err = clientcmd.WriteToFile(*config, kubeconfig); err != nil { + fmt.Printf("Error saving updated kubeconfig: %v\n", err) + os.Exit(1) + } + } fmt.Printf("Updated: %s (in %s).\n", kubeconfig, time.Since(st).Round(time.Millisecond)) } }