-
-
Save phenri00/ceb45e61e3f63d9402b68da90c2bd6cb to your computer and use it in GitHub Desktop.
Migrate EBS Volume based PVs across AWS availability zones
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 -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