Skip to content

Instantly share code, notes, and snippets.

@dale-c-anderson
Last active August 29, 2020 01:30
Show Gist options
  • Save dale-c-anderson/fe4ca8eee8e6f8cd97e16d5f06de3f82 to your computer and use it in GitHub Desktop.
Save dale-c-anderson/fe4ca8eee8e6f8cd97e16d5f06de3f82 to your computer and use it in GitHub Desktop.
Create an ad-hoc swap file for AWS nano / micro servers
#!/bin/bash -ue
####################
# For small AWS EC2 instances that have no swap space by default.
# A tiny, slow swap file may be preferable to having the server's OOM killer shutting down processes.
# A real swap on ephemeral storage is better, but this will do in a pinch.
# The disadvantage is that if a server starts using swap, it will burn through it's EBS disk burst credits very quickly.
# Works on Ubuntu 14,16,18, LTS. Not tested on any other platform.
####################
SWAP_FILE="/swapfile"
function main () {
test -e "$SWAP_FILE" && {
echo "Swap file already exists."
exit 0
}
grep swap /etc/fstab && {
echo "Not running because I found the word 'swap' in /etc/fstab."
exit 1
}
set -x
dd if=/dev/zero of="$SWAP_FILE" bs=1M count=1024
chmod 600 "$SWAP_FILE"
mkswap "$SWAP_FILE"
swapon "$SWAP_FILE"
echo "$SWAP_FILE swap swap defaults 0 0" >> /etc/fstab
}
main
@dale-c-anderson
Copy link
Author

Not working on OpenVZ

@SalimF it wasn't designed for or tested on OpenVZ. I've updated the header to include where the script works.

See also:
https://www.softwaretestinghelp.com/how-to-write-good-bug-report/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment