Automatically Cleaning Kubernetes Namespace
If you are working with Kubernetes, then chances are that you must have used namespaces to isolate your services or environments. Namespaces are a powerful way to organise your services or environments and have different policies like access control, ingress or telemetry configured for them. However, there might be scenarios where you have to clean these namespaces at specified time or interval. For example, if you have multiple developers working in your team and you want to provide them an isolated environment within your cluster (instead on their local setup, could be due to any reason like external dependency) you can use Kubernetes namespaces in this scenario.
Now, when your developers want to test their code in K8s cluster, they can simply deploy their code to specific namespace(manually or through automated setup) and never worry about conflicting changes from other team members. You can have different namespaces with developer name or each git branch name. However, with this kind of setup you will end up consuming lot of resources in your cluster as against a single deployment.
To mitigate this scenario, you can have automatic periodic cleanup of kubernetes namespaces either by creating a cronJob or by using out of the box tool like Kube-Janitor by Hennings Jacobs. I have used this tool in the past and it gets the job done very efficiently. You can use it to delete any Kubernetes resource and it provides multiple options to schedule the clean up of a resource. For example, you can either set an absolute expiry to delete or you can set a ttl value which starts from the first time the resource is created. Please visit this link for more details to use kube-janitor.
Kubernetes is very powerful container orchestration tool which has completely changed the way we used to deploy our applications. I hope you enjoyed reading the post and I will share more tips in the future as i keep on learning.