Mascot Blog

Just another HTMLy blog

Proxmox hookscript to shutdown proxmox server when all VM shutdown

- Posted in DevOps by

Goal is to use proxmox hookscript to shutdown Proxmox server when all the VMs are shutdown.

Hook Scripts

Hook scripts allow you to run a script based on a VMs execution phase .

This feature is not extensively documented (that I could find). From what I can gather the supported phases are:

pre-start post-start pre-stop post-stop An example hook script can be found in the onboard docs at the following location:

/usr/share/pve-docs/examples/guest-example-hookscript.pl

For my purposes, I will be using the bash script from the previous post with a couple of alterations to make it more portable and useable for multiple guests.

Hook Script Location

Hook scripts need to be stored in a snippets/ directory on a storage pool that Proxmox knows about. I will place my scripts in the /var/lib/vz/ directory that maps to the local storage pool.

Hook Script

Create a file named exrun.sh in the /var/lib/vz/snippets/ directory with the following contents.

#!/bin/bash
VM_ID=$1;
EXECUTION_PHASE=$2
LOGGING=/var/log/myhook.log;

if [[ $EXECUTION_PHASE == "post-stop" ]]
then

#/usr/bin/echo "EXE : $EXECUTION_PHASE" >> $LOGGING;

ALVMS="OFF"
current_date_time=$(date)

# get list of VMs on the node
VMIDs=$(qm list| awk '/[0-9]/ {print $1}')
for VM in $VMIDs
do
        if [[ $(qm status $VM) =~ running ]]
        then
                ALVMS="ON";
        fi
done

if [ $ALVMS == "OFF" ]
then
        shutdown -h now;
        /usr/bin/echo "SERVER SHUTTING DOWN : $current_date_time" >> $LOGGING;
else
echo ""
fi

fi

When Proxmox executes this script, it does so with 2 arguments.

VM_ID EXECUTION_PHASE These arguments can be mapped to variables in the script. In my case I am mapping them as follows.

VM_ID=$1 EXECUTION_PHASE=$2

The other thing that is required, is to make the script executable.

chmod +x /var/lib/vz/snippets/exrun.sh

Connect Hook Script

Now that the hook script is created, we need to connect it to a VM. Connect the hookscript to both the eda01 and eta01 VMs with the following command.

qm set 201 --hookscript local:snippets/exrun.sh
qm set 204 --hookscript local:snippets/exrun.sh

# Output
update VM 201: -hookscript local:snippets/exrun.sh
update VM 204: -hookscript local:snippets/exrun.sh

That's it! Now when the VM or host shuts down, the Proxmox server will shutdown automagically.

How to Disconnect Hook a Script

If for some reason you want to disconnect a hook script from a VM, use the following command.

qm set 201 --delete hookscript

# Output
update VM 201: -delete hookscript