Delete oldest deployment in a namespace

8/2/2019

I have two deployments running in one namespace with name deployment-A and deployment-B.

Currently, it is configured in such a way that if A is running then my Jenkins job will deploy B and vice-versa. But the job fails when both A and B are running. Now I want it to modify a bit so that if both A and B are running then the job should delete the oldest one (based on their deployment time).

I know it can be achieved with some shell script but not able to figure out the exact command.

-- vivek
kubernetes

1 Answer

8/2/2019

Here is command for you:

kubectl delete deployment $(kubectl get deployments --sort-by=.metadata.creationTimestamp -o json | jq -r .items[0].metadata.name)

Explanation: get all deployments sorted by timestamp, lower timestamp = older deployment, so first element is the oldest deployment. Than using json output and jq linux tool just get name of that deployment and pass it to delete deployment command.

-- Jakub Bujny
Source: StackOverflow