To delete all old ReplicaSets in Kubernetes, you can use the following one-liner:
kubectl get rs -A -o wide | tail -n +2 | awk '{if ($3 + $4 + $5 == 0) print "kubectl delete rs -n "$1, $2 }' | sh
What it does:
kubectl get rs -A -o wide
tail -n +2
skips the very first line with the table header;awk '{if ($3 + $4 + $5 == 0) print "kubectl delete rs -n "$1, $2 }'
constructs thedelete
command if the value ofDESIRED + CURRENT + READY
is zero. The generated commands will look like this:kubectl delete rs -n kubernetes-dashboard kubernetes-dashboard-7448ffc97b kubectl delete rs -n kube-system coredns-66c464876b kubectl delete rs -n kube-system metrics-server-7b4f8b595 kubectl delete rs -n kube-system local-path-provisioner-7ff9579c6
- Finally, the last
sh
runs the prepared script.
displays all available ReplicaSets, like this:
NAMESPACE NAME DESIRED CURRENT READY AGE CONTAINERS IMAGES SELECTOR kubernetes-dashboard kubernetes-dashboard-7448ffc97b 0 0 0 124d kubernetes-dashboard kubernetesui/dashboard:v2.1.0 k8s-app=kubernetes-dashboard,pod-template-hash=7448ffc97b kube-system coredns-66c464876b 0 0 0 124d coredns rancher/coredns-coredns:1.6.9 k8s-app=kube-dns,pod-template-hash=66c464876b kube-system metrics-server-7b4f8b595 0 0 0 124d metrics-server rancher/metrics-server:v0.3.6 k8s-app=metrics-server,pod-template-hash=7b4f8b595 kube-system local-path-provisioner-7ff9579c6 0 0 0 124d local-path-provisioner rancher/local-path-provisioner:v0.0.14 app=local-path-provisioner,pod-template-hash=7ff9579c6 kubernetes-dashboard dashboard-metrics-scraper-79c5968bdc 1 1 1 124d dashboard-metrics-scraper kubernetesui/metrics-scraper:v1.0.6 k8s-app=dashboard-metrics-scraper,pod-template-hash=79c5968bdc kube-system metrics-server-86cbb8457f 1 1 1 123d metrics-server rancher/metrics-server:v0.3.6 k8s-app=metrics-server,pod-template-hash=86cbb8457f
How to Delete Old ReplicaSets in Kubernetes