0

I have an EC2 instance for which I want to configure a swap instance volume.

I can do this relatively easily, by launching the instance with the instance store volume attached, and then running the following commands...

$ sudo mkswap /dev/xvdb
$ sudo swapon -p 1 /dev/xvdb

I can then run the following command to verify that it has worked...

$ sudo swapon -s
Filename                                Type            Size    Used    Priority
/dev/xvdb                               partition       335515644       0 1

I can make this persist after a reboot by adding a line like so in the /etc/fstab

/dev/xvdb swap swap pri=1 0 0

The issue is that if I stop the instance, and then start it again. The swap disapears. I have to re-create it with mkswap and swapon.

What is the correct way to configure an instance to automatically attach the instance volume as swap space?

I tried adding the following to the instance user-data...

#!/bin/sh

mkswap /dev/xvdb
swapon -p 1 /dev/xvdb

However this didn't do anything. I still need to manually re-create the swap each time I start the instance.

user1751825
  • 313
  • 5
  • 13
  • This isn't what you asked, but how about using a swap file on the main volume? One larger volume gets higher IOPS than two smaller volumes, though if it's very highly used you could run into some kind of limit. There are probably advantages and disadvantages, I don't know what they are, but a swap file works well on my t2.nano. – Tim May 09 '19 at 06:57
  • Thanks @Tim for the suggestion. This is what I was using previously. I'd like to use the instance store though, firstly because it doesn't cost any extra, and it should be much faster than EBS, as it's physically attached to the host server. It will be a very heavy utilisation instance, so we need the best possible performance from it. – user1751825 May 09 '19 at 07:03
  • Yes, you're absolutely right, I missed that you were talking about ephemeral volumes. Someone may be able to help here, but if not get an AWS support contract and ask them. Their support is excellent. – Tim May 09 '19 at 07:56

1 Answers1

1

via user-data executed after stop then start as described in this AWS document

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
DISK=/dev/nvme1n1

mkswap $DISK
swapon -p 1 $DISK
--//

or via rc.local on init configured systems, append to /etc/rc.local:

DISK=/dev/xvdb
mkswap $DISK
swapon -p 1 $DISK