Resize a VM when running out of memory

Using the Glesys API you can automatically resize a VM when it starts running low on memory.


The Glesys API can be used for many things, including upgrading the memory of a virtual server.

These scripts are ideally run from crontab every minute (adjust the scripts as needed). With a little extension, it’s easy to implement multi‑step upgrades and downgrades, send email notifications to the sysadmin on changes, upgrade the number of CPU cores, and so on.

If you modify these scripts or create completely different solutions, feel free to submit them to us so we can showcase them. Well‑crafted scripts are rewarded with nice discounts!

More information about the Glesys API can be found on GitHub.

Increase the memory using Bash

Below, we show you how to create a script that checks how much memory is being used on the virtual server. When usage reaches 90%, the memory is upgraded to 4096 MB. If you schedule this as a cron job, you’ll get an automatic memory increase on your server whenever the memory limit is reached.

/root/adjust-memory.sh
#!/bin/bash
TOTAL=`cat /proc/meminfo |grep "MemTotal" |awk {'print $2'}`
FREE=`cat /proc/meminfo |grep -E "MemFree|Cached"| awk '{s+=$2} END {print s}'`
USAGE=$((100-FREE*100/TOTAL));

if [ $USAGE -gt 90 ]; then
       /usr/bin/curl -X POST -d serverid=wps123456&memorysize=4096 -k --basic -u cl12345:API-KEY https://api.glesys.com/server/edit/
fi

Increase the memory using Ruby

Below is a slightly more advanced script. When the usage goes above 90%, the memory is increased to 4096 MB. When the usage goes below 20%, the memory is decreased to 2048 MB. If you schedule this as a cron job, you’ll get automatic memory increase and decrease on your virtual server based on its usage.

Running the Ruby script in a cron job

Make the script executable with chmod +x /root/adjust-memory.rb. Then, add the script to the crontab using crontab -e. To run the script every minute, add the following line to the crontab:

Last updated

Was this helpful?