Last active
October 12, 2017 09:00
-
-
Save grrywlsn/6e3fb1760db99275f0010dfa86d35fff to your computer and use it in GitHub Desktop.
Cycle through worker nodes to terminate and renew instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
# set -x | |
RED='\033[0;31m' | |
BLUE='\033[0;34m' | |
GREEN='\033[1;32m' | |
NC='\033[0m' # No Color | |
IFS=$'\n' | |
CONTEXT=`kubectl config current-context` | |
RETIRE_TIME=$(date +"%Y-%m-%dT%H-%M-%SZ") | |
log() { | |
ts=$(date +"%Y-%m-%dT%H:%M:%SZ") | |
printf "${1}${ts} ${2}${NC}\n" | |
} | |
if [[ ! -n "${CONTEXT}" ]]; then | |
log $RED "Your kubectl is not set with a current-context. Please set the cluster you want to update." | |
exit 1 | |
fi | |
log $GREEN "Current Kubernetes cluster is $CONTEXT" | |
WORKERS=(`kubectl get nodes -l type=worker -o json | jq '.items[] | .status .addresses[] | select(.type=="InternalDNS") | .address' | sed 's/\"//g'`) | |
log $NC "$CONTEXT cluster is made up of ${#WORKERS[@]} workers" | |
log $BLUE "Labelling workers for retirement..." | |
for worker in "${WORKERS[@]}" | |
do | |
worker="$worker.eu-west-1.compute.internal" | |
kubectl label node $worker retiring-worker=$RETIRE_TIME --overwrite=true | |
done | |
log $GREEN "Retiring workers in Kubernetes $CONTEXT" | |
for worker in "${WORKERS[@]}" | |
do | |
worker="$worker.eu-west-1.compute.internal" | |
log $BLUE "draining $worker..." | |
kubectl drain $worker --ignore-daemonsets --force --delete-local-data | |
sleep 30 | |
INSTANCE_ID=`aws ec2 describe-instances --filters "Name=network-interface.private-dns-name,Values=$worker" | jq '.Reservations[].Instances[].InstanceId' | sed 's/\"//g'` | |
log $BLUE "terminating $worker with instance-id $INSTANCE_ID..." | |
TERMINATE=`aws ec2 terminate-instances --instance-ids=$INSTANCE_ID` | |
sleep 60 | |
ACTIVE_WORKERS=`kubectl get nodes -l type=worker | grep "Ready" | wc -l | xargs` | |
while [[ $ACTIVE_WORKERS != ${#WORKERS[@]} ]]; do | |
echo "Waiting for new worker to join $CONTEXT cluster ($ACTIVE_WORKERS active / ${#WORKERS[@]} desired)" | |
sleep 5 | |
ACTIVE_WORKERS=`kubectl get nodes -l type=worker | grep "Ready" | wc -l | xargs` | |
done | |
REMAINING_WORKERS=(`kubectl get nodes -l retiring-worker=$RETIRE_TIME -o json | jq '.items[] | .status .addresses[] | select(.type=="InternalDNS") | .address' | sed 's/\"//g'`) | |
log $GREEN "Currently $ACTIVE_WORKERS active worker instances. We started with ${#WORKERS[@]}. ${#REMAINING_WORKERS[@]} still to retire." | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment