Skip to content

Instantly share code, notes, and snippets.

@noxdafox
Created March 18, 2020 15:56
Show Gist options
  • Save noxdafox/68834000ee46dd1abd09a35c1897d19f to your computer and use it in GitHub Desktop.
Save noxdafox/68834000ee46dd1abd09a35c1897d19f to your computer and use it in GitHub Desktop.
AverageWebServices is so bad it requires you to attach EBS volumes to its crappy EC2 instances
#!/bin/bash
#
# Attach AverageWebServices EBS volume to EC2 instance.
#
# Usage: attach_ebs_volume.sh <region> <instance-name> <device-name> <mount-point>
# Example: attach_ebs_volume.sh eu-west-1 my-ec2-instance /dev/xvdc /data
#
aws_region=$1
instance_name=$2
device_name=$3
mount_point=$4
# Attach Volume to instance
instance_id=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
volume_id=$(aws ec2 describe-volumes --region="$aws_region" \
--filters Name=tag-key,Values="Name" Name=tag-value,Values="$instance_name*" \
| jq --raw-output .Volumes[0].VolumeId) # The instance has a single volume
echo "Attaching $volume_id to instance $instance_id.. "
aws ec2 attach-volume --region="$aws_region" --volume-id "$volume_id" \
--instance-id "$instance_id" --device "$device_name"
echo "Done"
echo "Waiting for $volume_id to be attached to instance $instance_id.. "
blkname=$(basename "$device_name")
while ! lsblk | grep -q "$blkname"; do
echo "Volume $volume_id not attached yet.. "
sleep 3
done
echo "Volume $volume_id successfully attached to instance $instance_id"
# Format Volume if not EXT4
echo "Formatting device ${device_name}.. "
if blkid --match-token TYPE=ext4 "$device_name" > /dev/null; then
echo "Device $device_name is already a valid EXT4 filesystem."
else
mkfs.ext4 "$device_name"
fi
echo "Done"
# Mount Volume
echo "Adding mountpoint $mount_point to /etc/fstab and mounting.. "
echo "$device_name $mount_point ext4 defaults,nofail 0 0" >> /etc/fstab
mount -a
echo "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment