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?
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
?
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}"