Reputation: 321
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
Upvotes: 20
Views: 50404
Reputation: 499
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
Upvotes: 33
Reputation: 31
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
Upvotes: 3
Reputation: 2147
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
Upvotes: 2