Issue
I want to run a loop on the pods in specific namespace, however the trick is to do it in a cronJob,is it possible inline?
kubectl get pods -n foo
The trick here is after you get the list of the pods, I need to loop on then and delete each one by one with timeout of 15 seconde, is it possible to do it in cronJob?
apiVersion: batch/v1
kind: CronJob
metadata:
name: restart
namespace: foo
spec:
concurrencyPolicy: Forbid
schedule: "*/1 * * * *"
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 600
template:
spec:
serviceAccountName: pod-exterminator
restartPolicy: Never
containers:
- name: kubectl
image: bitnami/kubectl:1.22.3
command:
- 'kubectl'
- 'get'
- 'pods'
- '--namespace=foo'
When running the above script it works, but when you want to run loop its get complicated, how can I do it inline?
Solution
In your case you can use something like this:
apiVersion: batch/v1
kind: CronJob
metadata:
name: restart
namespace: foo
spec:
concurrencyPolicy: Forbid
schedule: "*/1 * * * *"
jobTemplate:
spec:
backoffLimit: 2
activeDeadlineSeconds: 600
template:
spec:
serviceAccountName: pod-exterminator
restartPolicy: Never
containers:
- name: kubectl
image: bitnami/kubectl:1.22.3
command:
- /bin/sh
- -c
- kubectl get pods -o name | while read -r POD; do kubectl delete "$POD"; sleep 15; done
However, do you really need to wait 15 seconds? If you want to be sure that pod is gone before deleting next one, you can use --wait=true
, so the command will become:
kubectl get pods -o name | while read -r POD; do kubectl delete "$POD" --wait; done
Answered By - Andrew Answer Checked By - David Marino (WPSolving Volunteer)