Skip to content

Instantly share code, notes, and snippets.

@icicimov
Created November 1, 2018 02:09
Show Gist options
  • Save icicimov/e80adec9bbbfa84444a78d2fe86dcf26 to your computer and use it in GitHub Desktop.
Save icicimov/e80adec9bbbfa84444a78d2fe86dcf26 to your computer and use it in GitHub Desktop.
Use EC2 ephemeral drive as swap
#!/bin/bash
TGTDEV="/dev/xvdb"
# Umount/Cleanup
[[ $(grep -wc "$TGTDEV" /proc/mounts) -eq 1 ]] && { fuser -km $TGTDEV; umount -f ${TGTDEV} 2>/dev/null || { echo "Can't unmount ${TGTDEV}"; exit 1; } }
[[ -e "${TGTDEV}2" ]] && [[ $(grep -wc "${TGTDEV}2" /proc/mounts) -eq 1 ]] && { fuser -km "${TGTDEV}2"; { umount -f "${TGTDEV}2" 2>/dev/null || { echo "Can't unmount ${TGTDEV}2"; exit 1; } } }
[[ -e "${TGTDEV}1" ]] && { swapoff "${TGTDEV}1" 2>/dev/null || { echo "Can't remove swap on ${TGTDEV}1 device"; exit 1; } }
# Partition the ephemeral disk
sed -e 's/\s*\([\+0-9a-zA-Z]*\).*/\1/' << EOF | fdisk ${TGTDEV}
o # clear the in memory partition table
n # new partition
p # primary partition
1 # partition number 1
# default - start at beginning of disk
+10G # 10GB swap partition
n # new partition
p # primary partition
2 # partion number 2
# default, start immediately after preceding partition
# default, extend partition to end of disk
t # change partition lable
1 # of the first partition
82 # to swap
p # print the in-memory partition table
w # write the partition table
q # done
EOF
# Inform the os about new partitions
partprobe -s $TGTDEV
# Make swap
mkswap -f -L SWAP "${TGTDEV}1"
swapon "${TGTDEV}1"
swapon -s
# Make the second partition
mkfs -t ext4 "${TGTDEV}2"
# Setup fstab
sed -i -e "/^[^#]/ s/\(^.*\/dev\/xvdb[[:space:]]\+.*$\)/#\1/" /etc/fstab
grep -c "${TGTDEV}2" /etc/fstab &&
sed -i '/^[^#]/ s/\(^.*\/dev\/xvdb2.*$\)/\/dev\/xvdb2 \/mnt auto defaults,nobootwait,comment=cloudconfig 0 2/' /etc/fstab ||
cat << EOF >> /etc/fstab
${TGTDEV}2 /mnt auto defaults,nobootwait,comment=cloudconfig 0 2
EOF
grep -c "${TGTDEV}1" /etc/fstab &&
sed -i '/^[^#]/ s/\(^.*\/dev\/xvdb1.*$\)/\/dev\/xvdb1 none swap sw 0 0/' /etc/fstab ||
cat << EOF >> /etc/fstab
${TGTDEV}1 none swap sw 0 0
EOF
mount -a
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment