Kubernetes: How to delete PODs based on age/creation time

☆樱花仙子☆ 提交于 2019-12-09 00:13:27

问题


Is it possible to delete POD in kubernetes based on creation time or age?

Example : I would like to delete all PODs which are older than 1 day. These PODs are orphaned , therefore no new PODs will be created.


回答1:


This command will delete all PODs older than one day :

kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}} {{.metadata.creationTimestamp}}{{"\n"}}{{end}}' | awk '$2 <= "'$(date -d 'yesterday' -Ins --utc | sed 's/+0000/Z/')'" { print $1 }' | xargs --no-run-if-empty kubectl delete pod

This command will delete all PODs older than 4 hours :

kubectl get pods -o go-template --template '{{range .items}}{{.metadata.name}} {{.metadata.creationTimestamp}}{{"\n"}}{{end}}' | awk '$2 <= "'$(date -d'now-4 hours' -Ins --utc | sed 's/+0000/Z/')'" { print $1 }' | xargs --no-run-if-empty kubectl delete pod



回答2:


We could this with only awk by doing a regex [0-9]+d directly on the AGE ($5, 5th column) column and then printing the corresponding NAME ($1, first column) column

kubectl delete pod $(kubectl get pod | awk 'match($5,/[0-9]+d/) {print $1}')

Test first to see what's matching:

kubectl get pod | awk 'match($5,/[0-9]+d/) {print $0}'

$0 means all columns




回答3:


You can either add a liveness probe to track how long the pod alive and kill it when it's longer a certain period. Or you can schedule a CronJob



来源:https://stackoverflow.com/questions/48934491/kubernetes-how-to-delete-pods-based-on-age-creation-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!