Skip to content

Instantly share code, notes, and snippets.

@icaromh
Last active August 29, 2015 14:07
Show Gist options
  • Save icaromh/3769b8a88773f0d7dc80 to your computer and use it in GitHub Desktop.
Save icaromh/3769b8a88773f0d7dc80 to your computer and use it in GitHub Desktop.
Vagrant Halt before shutdown
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment