kubectl: Retrieve a list of object names

2 min read | by Jordi Prats

If we need to write some script to retrieve a certain information that kubectl can provide, we can always add the option to remove headers and use something like awk to narrowit down. There's also a better way than doing this:

kubectl get ns --no-headers | awk '{ print $1 }'

With kubectl we can use the jsonpath output to select a certain element of the object definition, for example the name of the object it is within it's metadata. Since in this example we want to retrieve the name of all the objects it's going to be contained in a list thus the need of using .items[*]. With the following command we'll get the name of all the objects (in this case namespaces):

kubectl get ns -o jsonpath='{ .items[*].metadata.name }'

This way we don't need to have awk (or any other tool like sed...) to be able to retrieve the information we need.


for ns in $(kubectl get ns -o jsonpath='{ .items[*].metadata.name }');
  echo "== $ns =="
  kubectl get pods -n $ns

Posted on 31/08/2022