Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 385
Henrik Avatar asked Jun 01 '18 09:06

Henrik


2 Answers

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?

like image 65
suren Avatar answered Nov 01 '22 20:11

suren


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

like image 28
Ignacio Millán Avatar answered Nov 01 '22 21:11

Ignacio Millán