Search code examples
kuberneteseventstoredb

Using "kubectl delete pods X" from inside Kubernetes


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?


Solution

  • 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?