Adding Swap from Instance Store (Amazon Linux)

Below is the procedure to add a swap from instance-store volumes to Amazon Linux instance.
In this example the instance-store device is /dev/xvdb. Feel free to change it according to your instance-store device.

a. Ensure the Instance includes instance-store volumes or add one instance-store volume to your instance during launch time.

b. SSH into the instance and query for the instance-store:
# df -ah | grep ephemeral
The above command should return output like the following (note this may be different based on your AMI and you have to manually test to see which device is mounted as ephemeral storage):
/dev/xvdb 37G 177M 35G 1% /media/ephemeral0

c. Unmount the mounted instance-store:
# umount /media/ephemeral0

d. Create swap partition:
# mkswap /dev/xvdb

e. Comment out the line for /media/ephemeral0 within /etc/fstab:
#/dev/sdb /media/ephemeral0 auto defaults,nofail,comment=cloudconfig 0 2

f. Activate the swap space:
# swapon /dev/xvdb

g. Check that the swap space is active:
# cat /proc/meminfo | grep Swap
The above command should return output like the following:
SwapCached: 0 kB
SwapTotal: 39313404 kB
SwapFree: 39313404 kB

Should you stop start the instance to move underlying hosts, you will need to re-do the above procedure in order to ensure that you have instance-store configured as swap. You can bypass this by creating a script to prepare swap space so that if the instance is shutdown and then moved to a different underlying host, a pristine instance-store will be converted to swap space again. Adding it inside /etc/fstab will not work as the volume will not be prepared for swap when an instance is stopped and started. Invoking the script within /etc/rc.local would be ideal to perform this. For example:

cat << EOF >> /etc/rc.d/rc.local

# Create swap space – /dev/xvdb
if file /dev/xvdb | grep -q block; then
umount /dev/xvdb;
mkswap /dev/xvdb;
swapon -a /dev/xvdb;
fi

EOF

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s