Recently I’ve been using Amazon’s Cloud Computing services in the form of EC2 and S3. I’ve set up several scripts that make life easier by automating some of the tasks that need to be done regularly when administering EC2 virtual instances. In the hope that they will be useful to other people, I’ll be posting here some of them. Here is the first in the series.
The script “reallocate_volume” moves an EBS volume from an instance to another. It gets both instance ids as arguments on the command line. It is useful, for example, when your main production machine (first argument) fails for some reason, and you need to give control to the second machine. Below, the SLEEP_TIME is in seconds and MAX_TRIES is a number specifying delays for retries when detaching & attaching the volumes.
reallocate_volume:
#!/bin/bash
#Replaces volume in instance given as argument $1, with the volume taken from instance in argument $2
# {insert your commands that stop your servers here, e.g. apache & mysql}
umount /mnt/vol #make sure no-one else uses this, otherwise this will fail with inability to umount
volume1=`/root/bin/ec2get_volume_id $1`
ec2-detach-volume $volume1 –force #note that it uses force to ensure this gets detached
STATUS=`ec2-describe-volumes $volume1 | tail -1 | awk ‘{print $5}’ 2> /dev/null`
SLEEP_TIME=10
MAX_TRIES=15
while [ "$STATUS" != "available " ]
do
CTR=`expr $CTR + 1`
if [ $CTR -eq $MAX_TRIES ]
then
/bin/echo “WARNING: Cannot force detach volume $VOL to $DEV — Giving up after $MAX_TRIES attempts. Please try to use snapshot”
exit 1
fi
/bin/sleep $SLEEP_TIME
STATUS=`ec2-describe-volumes $volume1 | tail -1 | awk ‘{print $5}’ 2> /dev/null`
done
#attaching to the new machine
ec2-attach-volume $volume1 -i $2 -d /dev/sda2
STATUS=`ec2-describe-volumes $volume1 | tail -1 | awk ‘{print $5}’ 2> /dev/null`
SLEEP_TIME=10
MAX_TRIES=15
while [ "$STATUS" != "attached" ]
do
CTR=`expr $CTR + 1`
if [ $CTR -eq $MAX_TRIES ]
then
/bin/echo “WARNING: Cannot attach volume $VOL to $DEV — Giving up after $MAX_TRIES attempts”
exit 1
fi
/bin/sleep $SLEEP_TIME
STATUS=`ec2-describe-volumes $volume1 | tail -1 | awk ‘{print $5}’ 2> /dev/null`
done
mkdir -p /mnt/vol
mount /mnt/vol
# {insert your commands that start your servers here, e.g. apache & mysql}
Now this depends on one other script called ec2get_volume_id which gets the volume that corresponds to the instance id given as argument to it:
ec2get_volume_id
#!/bin/bash
#gets the volume for the instance id specified in the argument $1
ec2-describe-volumes | grep $1 | awk ‘{print $2}’