Amazon ephemeral: swap on boot.


With AWS you can add ephemeral storage to an EC2 instance. The downside of this storage is that it’s gone once you reboot the machine. This makes it perfectly suitable for swapspace. However you can’t add this swap to your /etc/fstab file. It will block the booting of your EC2 instance, as ephemeral storage will always reset. Any swap partitions assigned will vanish.

My way of coping with this is creating a little service that creates the swap at boot time.


Let’s create a service named ‘swapon’.

sudo nano /etc/init.d/swapon

And add the following content:

# chkconfig: 2345 95 20
# description: Adding swap to ephemeral0
# Adding swap to ephemeral0
# processname: swap
dd if=/dev/zero of=/media/ephemeral0/swap bs=1024 count=8M
mkswap /media/ephemeral0/swap
chown root:root /media/ephemeral0/swap
chmod 600 /media/ephemeral0/swap
swapon /media/ephemeral0/swap

This service will generate a swap file of 8GB (hence the 8M * 1024byte). If you need less or more, change the ‘count’ parameter.

Now last step: let’s assign execute rights and enable this script/service at boot time.

sudo chmod +x /etc/init.d/swapon
sudo chkconfig --level 345 swapon on

Now your swap will be created every time you boot (or reboot) your EC2 instance. The only drawback of this method is that it will run in the background and your swap won’t be immediately available. But adding swap won’t block your machine boot process.

Example: my m1.small instance it takes about 5 minutes to create an 8GB swap file.

One thought on “Amazon ephemeral: swap on boot.

Leave a Reply