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}"
CodePudding user response:
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