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

3

18

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
Juglandaceous answered 30/9, 2020 at 7:41 Comment(2)
If you want to scale up immediately after scale down, kubectl rollout restart is the better option.Liselisetta
eberz wrote an Answer saying "I have implemented a bash script for this. Please check it out: gist.github.com/evertonberz/93ec7c445fbd13ae9e0abc585eabd2d2"Discredit
T
31

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
Titanomachy answered 5/10, 2020 at 12:8 Comment(1)
@Emre Oodabaş care to explain how does it work?Scully
P
2

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
Peplum answered 30/9, 2020 at 11:33 Comment(0)
K
2

First get a list of all deployments, this is important, because you need it to scale back up when needed:

kubectl get deploy -A --no-headers | grep -v 'kube' > deploy_state_before_scale.txt

Scale all non k8s system related deployments to 0:

kubectl get deploy --no-headers -A | grep -v 'kube' | awk '{print $1}' | while read  DEPLOY; do kubectl scale --replicas=0 deployment/$DEPLOY -n $DEPLOY; done

To scale cluster back to how it was before you scaled to 0. Make sure to use 'deploy_state_before_scale.txt' that was created before scaling to 0:

awk '{print $1,$4}' deploy_state_before_scale.txt | while read DEPLOY SCALE; do kubectl scale --replicas=$SCALE deployment/$DEPLOY -n $DEPLOY; done
Kyl answered 16/10, 2021 at 21:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.