Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scale down kubernetes deployments to 0 and scale back to original number of replica sets

I have written a bash script to get all deployments on a kubernetes cluster. I have a command to scale all the deployments to zero. The challenge I am having is that, I want to be able to loop through all the deployments and save their name and number of replicas so I scale them back to the original after scaling down.

How do I achieve that? this is what I have done so far.

$ kubectl get deployments
$ kubectl scale deploy -n default  --replicas=0 --all
like image 436
Clement Okyere Avatar asked Dec 10 '22 00:12

Clement Okyere


2 Answers

You could annotate resources for the previous state of replications. Then you could use the below commands to change replicas.

   #annotate first 
   kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl annotate --overwrite deploy "}{@.metadata.name}{" previous-size="}{@.spec.replicas}{" \n"}{end}' | sh

   #scale to 0
   kubectl scale --replicas=0 $(kubectl get deploy -o name) 

   ## scaleback 
   kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl scale deploy "}{@.metadata.name}{" --replicas="}{.metadata.annotations.previous-size}{"\n"}{end}' | sh
like image 143
Emre Odabaş Avatar answered Dec 31 '22 18:12

Emre Odabaş


You could save the output into a bash array:

declare -A arr
for i in $(kubectl get deployment -o name)
do
  arr+=( [$i]="$(kubectl get $i -o=jsonpath='{.spec.replicas}')")
done

And then use that again to scale up:

for key in ${!arr[@]}
do
  kubectl scale deploy $key --replicas=${arr[${key}]}
done
like image 23
char Avatar answered Dec 31 '22 17:12

char