List pods per namespace in kubernetes

Viewed 3913

I have several namespaces in my cluster and would like a log like:

NAMESPACE            NAME                                          PODS  
MY_NAMESPACE         my_ns6446f67599-25g7f                         10   
3 Answers

You can also try this one liner:

kubectl get pods --all-namespaces | awk '{print $1}' | sort | uniq -c | sort -k1 -n -r

Which will yield:

136 some-ns
133 kube-system
119 other-ns

Explaining a bit:

  • kubectl get pods --all-namespaces will list all pods with namespace in the first column.
  • awk { print $1 } will "filter out" the first column which is the namespace
  • sort will sort the name of namespaces alphabetically
  • uniq -c will count how many times each namespace appeared and aggregate with a count as the first column (e.g. 136 some-ns means that some-ns appeared 136 times).
  • sort -k1 -n -r this one will sort from the namespace which appeared the most (i.e. had most pods) to the one that appeared the least. -k1 means that I am using the first column to sort, -n I am using numeric comparison and -r and I am doing a reverse ordering.

You can use --all-namespaces flag to get pods.

kubectl get pods --all-namespaces

From your output, it looks like you are trying to print the replicasets as there is a PODs count column in the output.

kubectl get replicaset --all-namespaces

If you want to limit the resulting columns, we can use the --0 custom-columns= parameter as below.

$ kubectl get replicaset --all-namespaces -o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name,PODS:.status.replicas     
NAMESPACE            NAME                                          PODS  
MY_NAMESPACE         my_ns6446f67599-25g7f                         10  

This solution combines the json output of kubectl get pods and kubectl get namespaces in order to also display the namespaces where no pods are deployed.

kubectl get pods -o json --all-namespaces | jq --argjson ns "$(kubectl get namespaces -o json)" '.items | group_by(.metadata.namespace) | map({namespace: .[].metadata.namespace, count: . | length}) | . += ($ns.items | map({namespace: .metadata.name, count: 0})) | unique_by(.namespace) | sort_by(.count)'

The solution provides an array of json objects sorted by number of pods in ascending order and can be easily extended to obtain the desired output.

The "magic" happens when we add the contents of the $ns variable -which contains the namespaces- to the end of the array with count=0. These entries will be discarded by unique_by if the namespace was already found before -which means it contains pods-.

Note: the solution relies on jq's unique_by function to discard the second appearance of an object with the same key value, which as for the documentation it is not granted but it happens to be implemented in this way.

Related