Reputation: 9915
We're using a >1.8 version of k8s on gcloud. Unfortunately EventStore stops pushing data until it is rebooted. Thus we'd like to run kubectl --namespace=$NAMESPACE delete pod eventstore-0
every 6 hours. Thus we have a cron job like:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: eventstore-restart
spec:
# Run every full hour, 15 past, 30 past, 45 past every other time-unit.
schedule: "0,15,30,45 * * * *"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 1
failedJobsHistoryLimit: 5
jobTemplate:
spec:
template:
spec:
containers:
- name: eventstore-restart
image: eu.gcr.io/$PROJECT_ID/kubectl:latest
imagePullPolicy: Always
command: [ "/bin/sh", "-c" ]
args:
- 'set -x; kubectl --namespace=$NAMESPACE get pods
| grep -ho "eventstore-\d+"
| xargs -n 1 -I {} kubectl --namespace=$NAMESPACE delete pod {}'
env:
- name: NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
restartPolicy: OnFailure
serviceAccount: restart-eventstore
However, this seems to expand to kubectl get pods ...
, piped with | { ... }
, which causes "/bin/sh: syntax error: unexpected end of file (expecting "}")
to fail the script.
How do I write the command to delete a pod on a schedule?
Upvotes: 5
Views: 5625
Reputation: 10695
I found a way to do it like this:
kubectl get pods -n your-namespace | grep eventstore | awk '{print $1,$2}' | xargs kubectl delete pod $2 -n $1
You can replace the word eventstore
by some other search criteria in the grep command to fit your needs. You can also modify the kubectl get
filters.
Upvotes: 0
Reputation: 13420
@suren answer is good, but it won't work in all the cases when you want to delete multiple specific pods. For example, if you have: pod1, pod2, pod3, pod4, and you want to delete only pod2 and pod4, you can't do it with grep (grep pod
will catch all of them).
In that case, you can delete them like that:
kubectl delete pods -n $NAMESPACE $(echo -e 'pod2\npod4')
Upvotes: 0
Reputation: 8776
I would do this:
kubectl delete po $(kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep eventstore) -n $NAMESPACE
or (your way)
kubectl get pods -n $NAMESPACE -o go-template --template '{{range .items}}{{.metadata.name}}{{"\n"}}{{end}}' | grep eventstore | xargs -n 1 -I {} kubectl delete po {}
Now, if you know you want to delete pod "eventstore-0", why to not do directly kubectl delete pod eventstore-0
?
Upvotes: 4
Reputation: 8026
I suggest to use label selectors to filter results of kubectl get
, and jsonpath output to get just the name of the pod.
Assuming that your pod is labeled with app=eventstore
and that you want to delete every pod with this label, you could use the following command:
k get po --namespace=$NAMESPACE --selector app=eventstore -o jsonpath="{.items[*].metadata.name}" | xargs -n 1 -I {} kubectl --namespace=$NAMESPACE delete po {}
If you want to delete just the first pod, use jsonpath="{.items[0].metadata.name}"
Upvotes: 2