Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Migrate EBS Volume based PVs across AWS availability zones
#!/bin/bash
set -eu
NAMESPACE=$1
PVCNAME=$2
TARGETZONE=$3
DEPLOYMENTOBJ=$4
PVNAME=$(oc -n $NAMESPACE get pvc $PVCNAME --template={{.spec.volumeName}})
VOLUMEID=$(oc -n $NAMESPACE get pv $PVNAME --template={{.spec.awsElasticBlockStore.volumeID}} | cut -d/ -f 4)
REPLICAS=$(oc -n $NAMESPACE get $DEPLOYMENTOBJ --template={{.spec.replicas}})
cat <<EOF
Summary
Namespace ---------- $NAMESPACE
Deployment object -- $DEPLOYMENTOBJ
PVC Name ----------- $PVCNAME
PV Name ------------ $PVNAME
Target Zone -------- $TARGETZONE
Volume Id ---------- $VOLUMEID
Original Replicas -- $REPLICAS
EOF
read -p 'Press ENTER to continue'
echo
if [ $REPLICAS -gt 0 ]; then
echo -n "Scaling down $DEPLOYMENTOBJ: $REPLICAS -> 0"
oc -n $NAMESPACE scale --replicas=0 $DEPLOYMENTOBJ
while [ "$(oc -n $NAMESPACE get $DEPLOYMENTOBJ --template={{.status.replicas}})" != "0" ]; do
echo
done
while sleep 0.1; do
echo
oc -n $NAMESPACE get pod
read -p "Press ENTER to continue" -t 3 || continue
break
done
fi
DESCRIPTION="snapshot-migration-${NAMESPACE}_${PVCNAME}_${VOLUMEID}"
echo -n "Creating snapshot... "
SNAPSHOTID=$(aws ec2 create-snapshot --volume-id $VOLUMEID --description $DESCRIPTION --output text --query SnapshotId)
aws ec2 wait snapshot-completed --filter Name=snapshot-id,Values=$SNAPSHOTID
echo $SNAPSHOTID
echo -n "Creating volume... "
TAGSPEC="ResourceType=volume,Tags=[{Key=Name,Value=kubernetes-dynamic-$PVNAME},{Key=kubernetes.io/created-for/pv/name,Value=$PVNAME},{Key=kubernetes.io/created-for/pvc/name,Value=$PVCNAME},{Key=kubernetes.io/created-for/pvc/namespace,Value=$NAMESPACE}]"
VOLUMEID=$(aws ec2 create-volume \
--availability-zone $TARGETZONE \
--snapshot-id $SNAPSHOTID \
--volume-type gp2 \
--output text \
--query VolumeId \
--tag-specifications "$TAGSPEC")
echo $VOLUMEID
echo Updating $DEPLOYMENTOBJ...
oc label pv/$PVNAME failure-domain.beta.kubernetes.io/zone=$TARGETZONE --overwrite
oc patch -p "{\"spec\":{\"awsElasticBlockStore\":{\"volumeID\":\"aws://$TARGETZONE/$VOLUMEID\"}}}" pv/$PVNAME
if [ $REPLICAS -gt 0 ]; then
echo "Scaling back $DEPLOYMENTOBJ: 0 -> $REPLICAS"
oc -n $NAMESPACE scale --replicas=$REPLICAS $DEPLOYMENTOBJ
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment