I want to delete every running pod automatically using the Commandline without having to type kubectl delete pod <pod_name> -n <namespace>
for each pod.
Here is a shellscript I made to achieve the task,
i=0 && for pod in $(kubectl get pods | grep 'Running')
do
if [ `expr $i % 5` == 0 ]
then kubectl delete pod $pod
fi
i=`expr $i + 1`
done
I found that when we loop over kubectl get pods | grep 'Running'
, every 5th word is a pod name.
So I basically wrote the script to take every 5th-word from the loop and execute whatever command I want on it.
Still, this feels like a naive approach. Feel free to share a better one.
You can use awk
to filter pod names based on their STATUS==RUNNING
. Below code will delete all(in Running state) the pods from $NAMESPACE
namespace.
kubectl get pod -n $NAMESPACE|awk '$3=="Running"{print $1}'
Example:
for pod in $(kubectl get pod -n $NAMESPACE |awk '$3=="Running"{print $1}'); do
kubectl delete pod -n $NAMESPACE $pod
done
OR
You may use jsonpath
,
NAMESPACE=mynamespace
for pod in $(kubectl get pod -n $NAMESPACE -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}{"\n"}'); do
kubectl delete pod -n $NAMESPACE "$pod"
done
NOTE: Above code will cause deletion of all the pods in $NAMESPACE
variable.
Example:
kubectl get pod -n mynamespace
NAME READY STATUS RESTARTS AGE
foo-mh6j7 0/1 Completed 0 5d3h
nginx 1/1 Running 2 7d10h
mongo 2/2 Running 12 57d
busybox 1/1 Running 187 61d
jsonpath
query to print all pods in Running
state:
kubectl get pod -n mynamespace -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}{"\n"}'
nginx mongo busybox
Although, you have not asked for ready
state, but following query can be used to list pods in ready state.
kubectl get pod -n mynamespace -o jsonpath='{range .items[*]}{.status.containerStatuses[*].ready.true}{.metadata.name}{ "\n"}{end}'
foo-mh6j7
nginx
mongo
busybox
Similarly, this can be done via grep
:
kubectl get pod -n $NAMESPACE |grep -P '\s+([1-9]+)\/\1\s+'
NOTE: Either of the solution will not prevent pods
from getting respawned if they are created via replicaset
or deployment
or statefulset
etc. This means, they will get deleted and respawned.
You could filter and delete running pods by:
kubectl delete pods -n <NAMESPACE> --field-selector=status.phase=Running