Automate Vagrant Suspend on Logout or Shutdown

So you have your local BOSH-Lite, and you have your Cloud Foundry release on there, your Etcd, PostgreSQL, MySQL, Redis. You name it; it’s on there.

Then you go and install the latest MacOS update and "Oh Gods, no!", You forgot to suspend that Vagrant instance, and you might be looking at an aborted state that means rebuilding it all. Not fun.

Apple has recommended not using login and logout scripts for some years now. Instead, you should be using Launchd scripts to manage your background applications and services. I decided it was time to look into how I’d automatically suspend Vagrant instances on shutdown.

The short version: Use Launchd to run a BASH script that waits until it is told to shut down, which runs a logout script.

The Launchd script, place this in $HOME/Library/LaunchAgents/org.$USER.logOut.plist:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "">
<plist version="1.0">

Now we need to create the script that does the work. I created this in my ~/scripts/ folder, but place it wherever suits you and change the path in the plist file above.

onLogout() {
    # Suspend vagrant
    osascript -e 'display notification "Suspending Vagrant containers" with title "Please hold..."'
    /usr/local/bin/VBoxManage list runningvms | /usr/bin/sed -E 's/.*\{(.*)\}/\1/' | xargs -L1 -I {} /usr/local/bin/VBoxManage controlvm {} savestate >> /var/log/org.YOUR_NAME.log 2>&1
echo "INFO - Watching ${HOME}" >> /var/log/org.YOUR_NAME.log
while true; do
    sleep 86400 &
    wait $!

Change YOUR_NAME to be your username, and any paths you would like to be different. Also, be sure to create the log file and make the script executable with the following:

sudo touch /var/log/org.$USER.log
sudo chown $USER /var/log/org.$USER.log
chmod +x $HOME/scripts/

Now we have our Launchd launch script and the script that will run when we log out. We need to load the Launchd script so it runs on startup.

launchd load -w $HOME/Library/LaunchAgents/org.$USER.logOut.plist

There we have it. You can test it works without logging out by just running the script from your shell. You can use this script for anything else you’d like to do on logout or shutdown. Enjoy! Hah, hah, hah, hah. Stayin’ alive!

Credit to Pepijn Bruienne, who had some scripts that helped me along the way.

Spread the word

twitter icon facebook icon linkedin icon