Skip to content

Instantly share code, notes, and snippets.

@stoshiya
Last active May 31, 2018 00:53
Show Gist options
  • Save stoshiya/4cafa50b34223aaa2a70c588abbede89 to your computer and use it in GitHub Desktop.
Save stoshiya/4cafa50b34223aaa2a70c588abbede89 to your computer and use it in GitHub Desktop.
EBS Resizing Script
#!/bin/sh
#
# $ sudo yum install jq
# $ sudo pip install -U awscli
# # sh ./ebs-resize.sh -d /dev/xvdf -v ebs-volume-name
#
usage() {
echo "Usage: $0 -d device-name -v ebs-volume-name" 1>&2
exit 1
}
while getopts d:v:h OPT
do
case $OPT in
'd')
DEVICE_NAME=$OPTARG
;;
'v')
VOLUME_NAME=$OPTARG
;;
'h')
usage
;;
\?)
usage
;;
esac
done
shift $((OPTIND - 1))
if test ${#DEVICE_NAME} -eq 0 -o ${#VOLUME_NAME} -eq 0; then
usage
fi
df -k $DEVICE_NAME 1> /dev/null
if test "$?" -ne 0; then
echo "$DEVICE_NAME is not found."
exit 1
fi
export THRESHOLD_PERCENT=95
export EXPAND_RATE=1.25
export USED_PERCENT=`df -k $DEVICE_NAME | grep -v Filesystem | awk '{print $5}' | awk -F% '{print $1}'`
export CURRENT_SIZE=`df -k $DEVICE_NAME | grep -v Filesystem | awk '{print $2}'`
export NEW_SIZE=`echo "scale=0; $CURRENT_SIZE * $EXPAND_RATE / 1024 / 1024 + 1" | bc -l`
export AWS_DEFAULT_REGION=`curl --silent http://169.254.169.254/latest/meta-data/placement/availability-zone | sed -e 's/.$//g'`
export INSTANCE_ID=`curl --silent http://169.254.169.254/latest/meta-data/instance-id`
export VOLUME_ID=`aws ec2 describe-volumes --filter "Name=attachment.instance-id,Values=$INSTANCE_ID" "Name=tag:Name,Values=$VOLUME_NAME" | jq -r '.Volumes[].VolumeId'`
if test ${#VOLUME_ID} -eq 0; then
echo "$VOLUME_NAME is not found."
exit 1
fi
if test $USED_PERCENT -ge $THRESHOLD_PERCENT; then
aws ec2 modify-volume --volume-id $VOLUME_ID --size $NEW_SIZE
sleep 30
/sbin/resize2fs $DEVICE_NAME
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment