top of page
Writer's picturevP

Kubernetes Field Selectors

Field selectors allow you to choose Kubernetes resources based on the contents of one or more resource fields.


Here are some examples of field selector queries:

  • metadata.name=my-service

  • metadata.namespace!=default

  • status.phase=Pending

Let's assume, you want to choose all pods that are currently running in the default namespace. To do so, use the following command:


kubectl get pods --field-selector status.phase=Running

The -n flag can be used to select all objects in a namespace, but what if you want to select all objects in the cluster except the namespace? Field selectors can assist you.


kubectl get pods --all-namespaces --field-selector metadata.namespace!=default

Chained selectors

You can also use multiple field selectors in your command if you need a highly specific selection. Below kubectl command selects all Pods for which the status.phase does not equal Running and the spec.restartPolicy field equals Always:


kubectl get pods --field-selector=status.phase!=Running,spec.restartPolicy=Always

Supported operators

You can use the =, ==, and != operators with field selectors (= and == mean the same thing). Below kubectl command selects all Kubernetes Services that aren't in the default namespace:


kubectl get services  --all-namespaces --field-selector metadata.namespace!=default

Multiple resource types

You can use field selectors across multiple resource types. The below kubectl command selects all Statefulsets and Services that are not in the default namespace:


kubectl get statefulsets,services --all-namespaces --field-selector metadata.namespace!=default

I'll end this post here to keep it brief.


Thank you for reading!


*** Explore | Share | Grow ***

126 views0 comments
vp1.2_23.png

vPundit

Explore | Share | Grow

Thanks for submitting!

vPundit

bottom of page