Monday, January 11, 2021

Script to Rebuild a Kubernetes Pod



 

Many developers that work in a kubernetes environment, run the kubernetes cluster on the local development machine, as it simplifies the development process, and it is faster and cheaper than using a remote kubernetes on the cloud, or on VMs.

Usually when you change a source of one of the pods, you want to replace it, so you need to follow the next steps:

  • build the changed container image from the sources
  • delete the existing pod
  • wait for the new pod (which uses the new built container) to start
I used to do these steps manually, until I took one more step, and automate it, with the following script:



#!/usr/bin/env bash
set -e
cd "$(dirname "$0")"
IMAGE=$1

function podReady(){
count=$(kubectl get pods -l configid=${IMAGE}-container | grep Running | wc -l)
if [[ "${count}" == "0" ]]; then
return 1
else
return 0
fi
}

echo "replace image ${IMAGE}"
./images/${IMAGE}/build.sh
kubectl delete pod -l configid=${IMAGE}-container&
sleep 2

until podReady
do
echo "waiting for pod ${IMAGE}"
sleep 1
done

kubectl get pods -l configid=${IMAGE}-container

echo "done"


The script receives the container name as argument, and locates the related pod according to a label with this name.

Then it kills the existing pod, and completes once the new pod is running. It does not keep you busy waiting until the old pod is fully deleted, so it saves more of your time.


Whenever I use this script I feel great for the saved time. 
Very recommended to use similar script for your own development...



No comments:

Post a Comment