How to Resize an AWS EBS Volume in Bash

If you need to resize an EBS volume in AWS, you can do so using bash.

Step 1 – Create a bash file

Create a bash file called resize.sh:

#!/bin/bash SIZE=${1:-20} INSTANCEID=$(curl http://169.254.169.254/latest/meta-data/instance-id) REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/\(.*\)[a-z]/\1/') VOLUMEID=$(aws ec2 describe-instances \ --instance-id $INSTANCEID \ --query "Reservations[0].Instances[0].BlockDeviceMappings[0].Ebs.VolumeId" \ --output text \ --region $REGION) aws ec2 modify-volume --volume-id $VOLUMEID --size $SIZE while [ \ "$(aws ec2 describe-volumes-modifications \ --volume-id $VOLUMEID \ --filters Name=modification-state,Values="optimizing","completed" \ --query "length(VolumesModifications)"\ --output text)" != "1" ]; do sleep 1 done if [[ -e "/dev/xvda" && $(readlink -f /dev/xvda) = "/dev/xvda" ]] then sudo growpart /dev/xvda 1 STR=$(cat /etc/os-release) SUB="VERSION_ID=\"2\"" if [[ "$STR" == *"$SUB"* ]] then sudo xfs_growfs -d / else sudo resize2fs /dev/xvda1 fi else sudo growpart /dev/nvme0n1 1 STR=$(cat /etc/os-release) SUB="VERSION_ID=\"2\"" if [[ "$STR" == *"$SUB"* ]] then sudo xfs_growfs -d / else sudo resize2fs /dev/nvme0n1p1 fi fi
Code language: Bash (bash)

Step 2 – Run the bash file specifying the new size

Now that you have the bash file, you can run the bash file along with specifying the new size of the desired volume:

bash resize.sh 50
Code language: Bash (bash)

The above command will attempt to resize the EBS volume to 50GB.

Additional Enhancements

As an alternative execution method, you can also change the bash file to be executable. This will allow you to call it directly without having to pass bash to the preceding command.

First you need to make the script and executable:

chmod +x resize.sh
Code language: Bash (bash)

Now you can simply run the file with the parameters required:

./resize.sh 20
Code language: Bash (bash)

This is possible because the first line of the file specifies the hashbang required to execute the code:

#!/bin/bash
Code language: Bash (bash)

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments