Search code examples
kuberneteskubectl

How to get a list of kube-contexts using cli


I am trying to get a list of kube-contexts (and filtering for gke clusters) and with some tools ended up with that:

kubectl config get-contexts | tr -s ' ' | cut -d ' ' -f 2 | grep gke

output:

gke_dev-redacted
gke_prod-redacted

Is there an easier way to do that (which does not depend on the fact that the command output does not use tabs, but multiple whitespaces). yaml or json output is not supported by that command:

--output yaml is not available in kubectl config get-contexts; resetting to default output format

Solution

  • You can provide the --output flag to display only the contexts' names, for example:

    $ kubectl config get-contexts --output=name
    minikube
    

    It's then easy to grep for GKE contexts:

    $ kubectl config get-contexts --output=name | grep "gke_*"