Suspend/resume all Vagrant boxes on system shutdown/startup

So, we’ve been using Vagrant a lot lately at work, and one thing that bugged me was whenever i shutdown my computer, it wouldn’t because I forgot to suspend or halt my running Vagrant boxes before shutting down.

So, I wrote a simple init script that suspends all running boxes, nice and easy. It should handle multiple users also (I have not tested this thou).

#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          something warm and fuzzy 
# Required-Start:    vboxdrv
# Required-Stop:     vboxdrv
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts suspended vagrant boxes and suspends running vagrant boxes
# Description:       
### END INIT INFO

# presumably only users with valid login shells are running vagrant boxes
validShells=$(cat /etc/shells | grep -v "#" | sed ':a;N;$!ba;s/\n/|/g')
userList=$(grep -E "$validShells" /etc/passwd | awk -F ':' ' { print $1 } ' | tr "\\n" " ")

case $1 in
  start)
    # loop thru every user
    for user in $userList; do
      # loop thru users suspended boxes
      for vm in $(su -c "vagrant global-status" $user 2>/dev/null | grep saved | awk ' { print $5 } '); do
        cd $vm >/dev/null
        su -c "vagrant up" $user
        su -c "vagrant status" $user > /dev/null # update global-status cache
      done
    done
  ;;
  stop)
    for user in $userList; do
      for vm in $(su -c "vagrant global-status" $user 2>/dev/null | grep running | awk ' { print $5 } '); do
        cd $vm > /dev/null
        su -c "vagrant suspend" $user
        su -c "vagrant status" $user > /dev/null # update global-status cache
      done
    done
  ;;
  status)
    for user in $userList; do
      echo "$user's vagrant box status"
      echo "------------------------------------------------------------------------"
      su -c "vagrant global-status 2> /dev/null" $user
      echo
      echo
    done
  ;;
  *)
    echo "Usage: $0 {start|stop|status}" >&2
    exit 1
  ;;
esac

exit 0

Installation

Edit /etc/init.d/vagrant-boxes and paste the above script and save (or download it from here and save it to /etc/init.d/vagrant-boxes). On debian/ubuntu etc, run

# update-rc.d vagrant-boxes defaults 99 01

Number 99 is the sequence number and should be larger than (in my case Virtualbox number 20, which by the way is the default on Debian distros). The second number is the sequence when shutting down the computer. So, it might be good to do first of all.