How do I list all pods that were not created by a controller

10/29/2019

I need to get a list of all pods that were not created by a controller so I can decide how to handle them before doing a drain on a node.

Otherwise I get the message:

error: cannot delete Pods not managed by ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet (use --force to override) while running the drain.

I can find the information by running kubectl describe <pod> and looking to see if the Controlled By: is missing but I want to programmatically search all pods on the node and since kubectl describe is not designed for that. I need to find an alternative method.

-- Tom Crozier
kubectl
kubernetes

1 Answer

10/29/2019

You can relly on the ownerReferences API object to find this:

$ kubectl explain pod.metadata.ownerReferences

KIND: Pod

VERSION: v1

RESOURCE: ownerReferences <[]Object>

DESCRIPTION: List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.

Bare pods (i.e., pods without controllers/owners) will not contain the ownerReferences field, so you can use the --custom-columns to find out which pods are controlled or not:

$ kubectl get pods --all-namespaces -o custom-columns=NAME:.metadata.name,CONTROLLER:.metadata.ownerReferences[].kind,NAMESPACE:.metadata.namespace
NAME                               CONTROLLER   NAMESPACE
nginx-85ff79dd56-tvpts             ReplicaSet   default
static-pod1                        <none>       default
static-pod2                        <none>       default
coredns-5644d7b6d9-6hg82           ReplicaSet   kube-system
coredns-5644d7b6d9-wtph7           ReplicaSet   kube-system
etcd-minikube                      <none>       kube-system
kube-addon-manager-minikube        <none>       kube-system
kube-apiserver-minikube            <none>       kube-system
kube-controller-manager-minikube   <none>       kube-system
kube-proxy-fff5c                   DaemonSet    kube-system
kube-scheduler-minikube            <none>       kube-system
storage-provisioner                <none>       kube-system
tiller-deploy-55c9c4b4df-hgzwm     ReplicaSet   kube-system

If you want only the pod names that are not owned by a controller manager, you can process the output of kubectl get -o json with jq (very useful for post script processing):

$ kubectl get pods --all-namespaces -o json | jq -r '.items | map(select(.metadata.ownerReferences == null ) | .metadata.name) | .[]'
static-pod1
static-pod1
etcd-minikube
kube-addon-manager-minikube
kube-apiserver-minikube
kube-controller-manager-minikube
kube-scheduler-minikube
storage-provisioner
-- Eduardo Baitello
Source: StackOverflow