I need a bash script to delete only pods on specific node before shutdown or reboot using Kubernetes API.
Found a solution that works for what I'm trying to achieve:
for each in $(curl -XGET https://URL/api/v1/namespaces | jq -r '.items[].metadata.name');
do arr=($(curl -XGET https://URL/api/v1/namespaces/$each/pods | jq --arg node `hostname` -r '.items[] | select(.spec.nodeName == $node) | .metadata.name'));
for i in ${arr[@]};
do curl -XDELETE https://URL/api/v1/namespaces/$each/pods/$i ;
done
done
This is a script present on each Worker node and it's executed before each reboot or shutdown and deletes all the pods from all namespaces that are present on that node only. Before this, there is another command that marks the node as "unschedulable". If anyone is interested in this, I can post the complete solution
If your goal is to remove all pods from a particular node and stop new pods from being scheduled on that node, then kubectl drain is what you probably want: It stops sending pods to the node and kills any existing ones.
It's as simple as invoking
kubectl drain NODE
and comes with a few extra switches to tweak the behavior (such as defining a graceful termination period).