Mount an S3 Bucket to an EC2 Instance in Sixty Seconds or Less
Have you ever wanted to mount an S3 bucket to an EC2 instance? AWS doesn't support this out of the box, but there are some tools about there that will help you.
This is my goto script to mount an S3 bucket to the file system. Once it's mounted you can read and write to it just as if it were a local directory.
###########################################################################################
# S3 Mounting
# install epel (a required package for 3sfs-fuse)
sudo amazon-linux-extras install epel -y
# install s3fs-fuse to mount s3 drives to our instance
sudo yum install s3fs-fuse -y
# check to see if we have directory defined in an environment var
if [ -z $S3_MEDIA_DIR ]
then
# we didnt' find out so set the variable to one of your choosing
export S3_MEDIA_DIR="/app/s3/media"
# (optional) write it out to the file to persist on reboots
# it's nice to know if we need to trouble shoot anything
echo "export S3_MEDIA_DIR=${S3_MEDIA_DIR}" >> /etc/profile.d/export_instance_tags.sh
fi
# make a directory for the media files, we're going to map to S3
sudo mkdir -p $S3_MEDIA_DIR
# get the role name bound to the EC2 instance
# THIS ROLE NEEDS TO HAVE ACCESS TO THE BUCKET YOU ARE MOUNTING
role_name=$( curl -s http://169.254.169.254/latest/meta-data/iam/security-credentials/ )
# mount the bucket to the directory
sudo s3fs $BUCKET_NAME $S3_MEDIA_DIR -o iam_role=$role_name -o allow_other -o nonempty
# / S3 Mounting
###########################################################################################
Main Image Credit: Joel Muniz on Unsplash