1

Anyone know or can point me to where i could find how one can delete kuberenets resources based on Age? I’m trying to build a cron job that would delete old services, pods, jobs, configmaps of a specific namespace. So for example something that would get all pods that are 2 days old of a specific namespace and run a kubectl delete pods command based on that list? the below command will sort the pods based on the creation timestamp but what i really need is the ability to list & delete resources that are greater than a specified date.

kubectl get pods -n k6 --sort-by=.metadata.creationTimestamp -o jsonpath="{.items[0].metadata.name}"
Adiii
  • 54,482
  • 7
  • 145
  • 148
MSa'ad
  • 13
  • 2
  • 1
    Does this answer your question? [Kubernetes: How to delete PODs based on age/creation time](https://stackoverflow.com/questions/48934491/kubernetes-how-to-delete-pods-based-on-age-creation-time) – Adiii Aug 02 '22 at 15:20

1 Answers1

0

You will have to take the aid of some scripting, like bash:

kubectl get pods -n k6 -o jsonpath="{range .items[*]}{.metadata.name} {.metadata.creationTimestamp}{'\n'}{end}"  |\
while read pod_name pod_creation_time; do
    pod_creation_time_epoch=$(date +%s -d "$pod_creation_time");
    current_time_epoch=$(date +%s) ;
    #172800 = 24hours x 60minutes x 60seconds x 2days
    if [ $((current_time_epoch - pod_creation_time_epoch)) -gt 172800 ];then
        echo "$pod_name is older than 2 days";
        #uncomment the below line to cause deletion
        #kubectl delete pod $pod_name -n k6
    else
        #remove the else condition unless you really require it
        echo "$pod_name is younger than two days";
    fi ;
done
P....
  • 17,421
  • 2
  • 32
  • 52
  • Thinking about it is it possible to extend this script to also get pods with status completed only? I can do this by running the below command kubectl get pods -n test --field-selector=status.phase!=Running | grep Completed – MSa'ad Aug 03 '22 at 11:39
  • I think i found something which i can plug in to the previous jsonpath Found something on this {.items[?(@.status.phase=="Running")]} – MSa'ad Aug 03 '22 at 11:48