0
votes

kubernetes cron job which should run every 10mins and should delete the pods which are in "Terminating" state in all the namespaces in the cluster? please help me out....am struggling with the bash one liner shell script

  apiVersion: batch/v1
  kind: Job
  metadata:
  name: process-item-$ITEM
  labels:
  jobgroup: jobexample
  spec:
  template:
  metadata:
  name: jobexample
  labels:
    jobgroup: jobexample
spec:
  containers:
  - name: c
    image: busybox
    command: ["sh", "-c", "echo Processing item $ITEM && sleep 5"]
  restartPolicy: Never
1
Why you want this?cgcgbcbc
in my cluster for some reason pods are going to terminating state and not really terminating it is juts staying in there so i dont want to go to manually each pod and delete the pods which are in terminating state so i am looking for a cron which does that @cgcgbcbcrohit rocckz
Do you set pod.Spec.TerminationGracePeriodSeconds on your pod template so that the terminating pods get killed after a periodcgcgbcbc
@cgcgbcbc if you dont mind can you post a sample yaml which has this feature?rohit rocckz
@cgcgbcbc i should add this in deployment?rohit rocckz

1 Answers

1
votes

List all terminating pods in all namespace with the format {namespace}.{name}

kubectl get pods --field-selector=status.phase=Terminating --output=jsonpath='{range .items[*]}{.metadata.namespace}{"."}{.metadata.name}{"\n"}{end}' --all-namespaces=true

Given a pod's name and its namespace, it can be force deleted by

kubectl delete pods <pod> --grace-period=0 --force --ns=<namespace>

In one line

for i in `kubectl get pods --field-selector=status.phase=Terminating --output=jsonpath='{range .items[*]}{.metadata.namespace}{"."}{.metadata.name}{"\n"}{end}' --all-namespaces=true`; do kubectl delete pods ${i##*.} --grace-period=0 --force --ns=${i%%.*}; done