Skip to content

Instantly share code, notes, and snippets.

@fruit
Last active August 29, 2015 14:17
Show Gist options
  • Save fruit/d60a9cb82e11d6c123ba to your computer and use it in GitHub Desktop.
Save fruit/d60a9cb82e11d6c123ba to your computer and use it in GitHub Desktop.
Automatically shutdown VirtualBox/Vagrant VM's on system restart or halt (Ubuntu 14.04)
#!/bin/sh
# Author: Ilya Sabelnikov <fruit.dev@gmail.com>
# Version: 1.0.0
### BEGIN INIT INFO
# Provides: vmboxcontrol
# Required-Start: $local_fs $remote_fs
# Required-Stop: $local_fs $remote_fs
# Default-Start:
# Default-Stop: 0 1 6
# Short-Description: Start VM shutdown jobs on halt and restart
### END INIT INFO
# update-rc.d vmboxcontrol stop 44 0 1 6 .
set -e
PATH=/bin:/usr/bin:/sbin:/usr/sbin
# Set your user here, which runs VMs on this machine
# (e.g. VM_USER=john)
VM_USER=
. /lib/lsb/init-functions
log() {
echo $1
log_progress_msg $1
}
run_command_under() {
if [ -z "$1" ] || [ -z "$2" ]; then
log "Invalid usage of run_command_under() func in $0"
exit 0
fi
output=$(sudo -H -u $1 bash -c "$2")
}
shutdown_virtualbox_vms() {
if ! hash VBoxManage 2> /dev/null; then
log "VBoxManage not installed"
return;
fi;
run_command_under $VM_USER "VBoxManage list runningvms"
VMS=$(echo $output | awk '{ print $2; }')
if [ -z $VMS ]; then
log "All VirtualBoxes are already powered off"
fi;
for VM in $VMS; do
log "Stopping VirtualBox VM with UID $VM"
run_command_under $VM_USER "VBoxManage controlvm $VM acpipowerbutton"
until $(run_command_under $VM_USER "VBoxManage showvminfo --machinereadable $VM | grep -q ^VMState=.poweroff."); do
echo -n "."
sleep 1
done
echo
done
}
shutdown_vagrant_vms() {
if ! hash vagrant 2> /dev/null; then
log "Vagrant is not installed"
return;
fi;
run_command_under $VM_USER "vagrant global-status | awk '/running/'"
VMS=$(echo $output | awk '{ print $1 }')
if [ -z "$VMS" ]; then
log "All Vagrant Boxes are already powered off"
fi;
for VM in $VMS; do
log "Stopping Vagrant VM with UID $VM"
run_command_under $VM_USER "vagrant halt $VM"
done;
}
case "$1" in
start)
;;
stop)
if [ -z $VM_USER ]; then
echo "\$VM_USER variable was not provided (set) in file $0"
exit 1
fi
log_daemon_msg "Stopping running VM machnes before STOP" "vmboxcontrol"
shutdown_vagrant_vms
shutdown_virtualbox_vms
log_end_msg 0
;;
*)
echo "Usage: /etc/init.d/vmboxcontrol stop"
exit 1
;;
esac
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment