I have a total of 2030 pvc's and I want to delete 2000 pvc's form them and keep the 30.
Those 30 pvc's are latest and only less that 2 days old.. so that is why I do not want to delete them. The other all 2000 pvc are more than 2 days old.
I want to create a script that runs automatically to delete the pvc's which are more than 2 days old.
some example of my pvcs:
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
data-14353-postgresql-0 Bound pvc-1a6 8Gi RWO gp2 2d15h
data-14354-postgresql-0 Bound pvc-2d6 8Gi RWO gp2 16d
data-14358-postgresql-0 Bound pvc-9dc 8Gi RWO gp2 127m
data-14367-postgresql-0 Bound pvc-2eb 8Gi RWO gp2 65h
data-14370-postgresql-0 Bound pvc-90d 8Gi RWO gp2 56d
now as u can see I have a mixed AGE label.
They can be deleted using:
kubectl delete pvc
but this will delete all.. and I do not want to delete all!
TL:DR;
kubectl get pvc --sort-by=.metadata.creationTimestamp --no-headers | tac | cut -d ' ' -f 1 | sed -n 31,2000p | xargs kubectl delete pvc
Let's explain in pieces:
kubectl get pvc --sort-by=.metadata.creationTimestamp --no-headers
:
This part lists the PVCs in descending order without the header row
tac
reverse the output and produce ascending order
cut -d ' ' -f 1
Get's the first column which have the PVCs names
sed -n 31,2000p
Prints all the PVCs after line 30 which will contain your 30 PVCs which are less that 2 days old
p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.
n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands.
xargs kubectl delete pvc
Deletes your PVCs.
There is no easy way to do this by just using a kubectl
command, its only easy to operate that way when you can use labels in a good way.
But you can do this programmatically, by using a programming or scripting language against the Kubernetes API Server.
Perhaps, you can in this case, manually add a label to the 30 PVCs that you want to keep, and then delete the PVCs which does not have this label.
If you have managed to label the PVCs that you want to keep, you can use e.g.
kubectl delete pvc -l !keep
See more about how to add labels and select resources using labels on Labels and Selectors