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?

3/14/2019

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
-- rohit rocckz
google-kubernetes-engine
jobs
kubectl
kubernetes
kubernetes-cronjob

1 Answer

3/14/2019

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
-- cgcgbcbc
Source: StackOverflow