Restarting vm/containers if they get swapped out

It is quite easy to over demand on the capabilities of you machine when you’re running proxmox. The most claimed resource is definately memory. If you’re really squeezing every bit of memory out of your machine, you will encounter the situation that a vm will be swapped out. So you suddenly see that your host being down, without really a clear indication. Sometimes the vm that is swapped out is a crucial one and it would really be helpful if it would be started automatically. That’s where this script comes in. It can restart virtual machines if the script detects that it is not running. It will also send a notification to Ntfy in case it had to restart a vm.

#!/bin/bash

VMIDLIST=(100 102) # list of VMIDs that should always be running
HOSTNAME=`hostname`
APITOKEN="tk_XxntfyApiToken"
NTFYHOST="https://ntfy.sh"
TOPIC="ntfy-topic"

for vmid in "${VMIDLIST[@]}"; do
    status=$(/usr/sbin/qm status $vmid)

    if [ "$status" == "status: stopped" ]; then
        /usr/sbin/qm start $vmid
 curl \
    -s \
    -H prio:high \
    -H tags:warning \
    -H "Authorization: Bearer ${APITOKEN}" \
    -d "PVE start: ${vmid} on ${HOSTNAME}" \
    ${NTFYHOST}/${TOPIC}  2>&1 >/tmp/curl
    fi
done

It should suffice if you just change the variables at the beginning of the script.