Kubernetes: How do I delete clusters and contexts from kubectl config?

KubernetesGoogle Kubernetes-EngineKubectl

Kubernetes Problem Overview


kubectl config view shows contexts and clusters corresponding to clusters that I have deleted.

How can I remove those entries?

The command

kubectl config unset clusters

appears to delete all clusters. Is there a way to selectively delete cluster entries? What about contexts?

Kubernetes Solutions


Solution 1 - Kubernetes

kubectl config unset takes a dot-delimited path. You can delete cluster/context/user entries by name. E.g.

kubectl config unset users.gke_project_zone_name

kubectl config unset contexts.aws_cluster1-kubernetes

kubectl config unset clusters.foobar-baz

Side note, if you teardown your cluster using cluster/kube-down.sh (or gcloud if you use Container Engine), it will delete the associated kubeconfig entries. There is also a planned kubectl config rework for a future release to make the commands more intuitive/usable/consistent.

Solution 2 - Kubernetes

For clusters and contexts you can also do

kubectl config delete-cluster my-cluster

kubectl config delete-context my-cluster-context

There's nothing specific for users though, so you still have to do

kubectl config unset users.my-cluster-admin

Solution 3 - Kubernetes

Run command below to get all contexts you have:

$ kubectl config get-contexts

CURRENT   NAME             CLUSTER     AUTHINFO                                NAMESPACE

*         Cluster_Name_1   Cluster_1   clusterUser_resource-group_Cluster_1

Delete context:

 $ kubectl config delete-context Cluster_Name_1

Solution 4 - Kubernetes

Unrelated to question, but maybe a useful resource.

Have a look at kubectx + kubens: Power tools for kubectl.

They make it easy to switch contexts and namespace + have the option to delete

e.g.,

kubectx -d my-context

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy LewiView Question on Stackoverflow
Solution 1 - KubernetesjeffmlView Answer on Stackoverflow
Solution 2 - KubernetesEverett ToewsView Answer on Stackoverflow
Solution 3 - KubernetesKhoaView Answer on Stackoverflow
Solution 4 - Kuberneteshpl002View Answer on Stackoverflow