Kubectl Scale down All pods/deployments in namespace - Kubernetes

How to Scaledown all the pods and deployments in a namespace. or across namespaces in your current Kubernetes cluster context.

At times, you might want to just hibernate your namespace and deployments by scaling down the pods to 0

For some cost savings, let's say you want to keep your namespaces with zero pods over the weekend.

kubectl list containers inside pod

Kubectl Command to scale down all deployments in the namespace

You cannot keep scaling down each deployment in a namespace.

You can instead use the following command  to scale down all the pods and deployments in your namespace to 0

kubectl scale deployment -n <namespace> – replicas 0 – all

while this might work for one or two namespaces what if you want to bulk scale down (hibernate) many namespaces in your cluster?

we have a solution.


Python script to scale down all the namespaces in your cluster ( with exclusion)

In your Kubernetes cluster, there could be 100s of namespaces and you might not want to execute this command manually every time ( weekend)

You can use this simple python program that does that for you

The Following Python program when run with the proper kubectl context set in your terminal, would get all the namespaces in your current context ( or k8s cluster)

Go through all of them and hibernate them ( scale the deployments to 0 replicas)

This is also specially designed to exclude some namespaces as we might want to keep some namespaces running.

All we have to do is to update the exclusionlist variable

import command

namespaces=command.run(["kubectl","get","namespaces","-o","jsonpath={.items[*].metadata.name}"]).output.decode('utf-8').split(" ")

exclusionlist=["default","grafana", "kube-system","karpenter","kube-logging","kube-monitor","traefik","velero"]

for name in namespaces:

        if name not in exclusionlist:
                        print("Scaling down all the deployments in",name)
                        print("-" * 10)

                except Exception as e:
                        print("Skipping due to error",e)

If you look at the preceding script, you can see we are excluding some of the system and important namespaces.

Hope this helps.


Sarav AK