loop on output and delete in bash

11/27/2018

Team, I need to delete 10s of pods on k8s cluster that has error. I am getting them as below:

kubectl get pods --all-namespaces | grep -i -e Evict -e Error | awk -F ' ' '{print $1, $2, $4}'
test-asdfasdf asdfasdf2215251 Error
test-asdfasdf asdfasdf2215252 Error
test-asdfasdf asdfasdf2215253 Error
test-asdfasdf asdfasdf2215254 Error
test-asdfasdf asdfasdf2215255 Error
test-asdfasdf asdfasdf2215256 Error

manually am deleting them like this:

kubectl delete pod asdfasdf2215251 -n test-asdfasdf

but can I write a script that just looks for error on any pod and deletes all of them? I am working on script myself but new to this hence getting late..

-- AhmFM
bash
kubectl
kubernetes

1 Answer

11/27/2018

Start point:

kubectl get pods --all-namespaces |
grep -i -e Evict -e Error |
awk -F ' ' '{print $1, $2}' |

will produce a stream of:

test-asdfasdf asdfasdf2215251
test-asdfasdf asdfasdf2215252
test-asdfasdf asdfasdf2215253
test-asdfasdf asdfasdf2215254
test-asdfasdf asdfasdf2215255
test-asdfasdf asdfasdf2215256

we can go here:

while IFS=' ' read -r arg1 arg2; do
    kubectl delete pod "$arg2" -n "$arg1"
done

we can go here:

xargs -l1 -- sh -c 'kubectl delete pod "$2" -n "$1"' --

or use parallel or any kind of other tools to do that.

-- KamilCuk
Source: StackOverflow