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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With