Create a swap partition on ephemeral storage on Azure VM

by James McDonald | Jun 13, 2025 | IT Tips | 0 comments

My VM has an 8G ephemeral volume and it seems to be wasted so why not put the swapfile on there

You need the cloud-init service:

sudo systemctl is-enabled cloud-init.service
enabled

The instructions with a couple of options are here: https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/linux/create-swap-file-linux-vm

Just in case the above link goes away:

Create a SWAP creation script named swap.sh under /var/lib/cloud/scripts/per-boot with the following script:

#!/bin/sh

# Percent of space on the ephemeral disk to dedicate to swap. Here 30% is being used. Modify as appropriate.
PCT=0.3

# Location of the swap file. Modify as appropriate based on the location of the ephemeral disk.
LOCATION=/mnt

if [ ! -f ${LOCATION}/swapfile ]
then

    # Get size of the ephemeral disk and multiply it by the percent of space to allocate
    size=$(/bin/df -m --output=target,avail | /usr/bin/awk -v percent="$PCT" -v pattern=${LOCATION} '$0 ~ pattern {SIZE=int($2*percent);print SIZE}')
    echo "$size MB of space allocated to swap file"

     # Create an empty file first and set correct permissions
    /bin/dd if=/dev/zero of=${LOCATION}/swapfile bs=1M count=$size
    /bin/chmod 0600 ${LOCATION}/swapfile

    # Make the file available to use as swap
    /sbin/mkswap ${LOCATION}/swapfile
fi

# Enable swap
/sbin/swapon ${LOCATION}/swapfile
/sbin/swapon -a

# Display current swap status
/sbin/swapon -s

The script will be executed on every boot and allocates 30% of the available space in the resource disk. You can customize the values based on your situation.

Make the script executable:

chmod +x /var/lib/cloud/scripts/per-boot/swap.sh

Stop and start the VM. Stopping and starting the VM is only necessary the first time after you create the SWAP file.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.