Find out all the pods that are using default service account

Viewed 309

We have a k8s cluster with 10 workers. we run hundreds of pods in the cluster. we want to avoid running pods with default service account. Need to find out the pods that are running with default service account. am able to find the number of pods using default service account with grep command but also need the pod name and the image it is using. Let us know your thoughts

3 Answers

I used the below command to identify the pods from each namespace that is using default service account

kubectl get pods --all-namespaces -o json | jq '.items[] | select(.spec.serviceAccountName?=="default") | "\(.metadata.namespace) \(.metadata.name)"' | cut -d'"' -f2 | sort
  • In Case if you want to use just kubectl without jq :

needed to print both namespace and the pod name

kubectl get pods --all-namespaces -o jsonpath='{range .items[?(@.spec.serviceAccountName == "default")]}{.metadata.namespace} {.metadata.name}{"\n"}{end}' 2>/dev/null
  • i have added 2>/dev/null to avoid printing whole json template in case if no field was found

if you are using k9s you can also :pod then e the pod to see which service account it is associated with

Related