'Clean up "Replica Sets" when updating deployments?
Every time a deployment gets updated, a new replica set is added to a long list. Should the old rs be cleaned?
Solution 1:[1]
Removing old replicasets is part of the Deployment object, but it is optional. You can set .spec.revisionHistoryLimit
to tell the Deployment how many old replicasets to keep around.
Here is a YAML example:
apiVersion: apps/v1
kind: Deployment
# ...
spec:
# ...
revisionHistoryLimit: 0 # Default to 10 if not specified
# ...
Solution 2:[2]
If you want to clean it manually you can just paste that in your console
kubectl delete $(kubectl get all | grep replicaset.apps | grep "0 0 0" | cut -d' ' -f 1)
This only works because of the way kubectl get all
displays resources. It's a cheap solution but it's not that big an issue either.
Edit
Look at Joe Eaves's solution, it's similar but less dependent on the syntax (ignores white spaces at least)
Solution 3:[3]
A revision on Kévin's post above as I can't comment yet :D
AWK lets us ignore the spacing!
kubectl delete $(kubectl get all | grep replicaset.apps | awk '{if ($2 + $3 + $4 == 0) print $1}')
Solution 4:[4]
Here's a way to do it without AWK, using only kubectl and the built-in jsonpath functionality:
kubectl delete replicaset $(kubectl get replicaset -o jsonpath='{ .items[?(@.spec.replicas==0)].metadata.name }')
This should be more stable because it processes the replica count directly instead of trying to parse the output of kubectl
which might change.
Solution 5:[5]
on k8s v1.19.6 i had to modify Joe Eaves' command as below to make it work:
kubectl -n <namespace> delete rs $(kubectl -n <namespace> get rs | awk '{if ($2 + $3 + $4 == 0) print $1}' | grep -v 'NAME')
Solution 6:[6]
A short way:
kubectl delete rs $(kubectl get rs | grep "0 0 0" | cut -d' ' -f 1)
Solution 7:[7]
One-Liner using awk and xargs deleting all ReplicaSets from all Namespaces:
kubectl get replicaset --all-namespaces -o=jsonpath='{range .items[?(@.spec.replicas==0)]}{.metadata.name}{"\t"}{.metadata.namespace}{"\n"}{end}' | awk '{print $1 " --namespace=" $2}' | xargs -n 2 -d '\n' bash -c 'kubectl delete replicaset $0 $1'
Solution 8:[8]
I do this way:
kubectl get replicasets.apps -n namespace | awk '{if ($2 + $3 + $4 == 0) print $1}' | xargs kubectl delete replicasets.apps -n namespace
first get all replicaset, then parse it with conditional and then, delete it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Gian Marco |
Solution 2 | fearphage |
Solution 3 | Joe Eaves |
Solution 4 | Mike Matera |
Solution 5 | mkumar118 |
Solution 6 | hejeroaz |
Solution 7 | Christian Knell |
Solution 8 | hiddenrebel |