Skip to content

Instantly share code, notes, and snippets.

@kirankulkarni
Last active August 29, 2015 14:06
Show Gist options
  • Save kirankulkarni/177b61205267ead36561 to your computer and use it in GitHub Desktop.
Save kirankulkarni/177b61205267ead36561 to your computer and use it in GitHub Desktop.
A set of helper functions to suspend/resume your vagrant boxes from shellscript
#!/bin/bash
function vagrant_get_status()
{
cd "$1"
local status_op=$(vagrant status --machine-readable)
echo "$status_op" | while read line
do
local status_line=(${line//,/ })
local vagrant_type=${status_line[2]}
local vagrant_data=${status_line[3]}
if [ "$vagrant_type" = "state-human-short" ]; then
echo "$vagrant_data";
return;
fi
done
cd - > /dev/null
}
function vagrant_force_resume()
{
cd "$1"
local status_op=$(vagrant --machine-readable resume)
if [ -z "$status_op" ]; then
echo "$(tput setaf 2)Successfully resumed the machine$(tput sgr 0)";
else
echo "$status_op" | while read line
do
local status_line=(${line//,/ })
local vagrant_type=${status_line[1]}
local vagrant_data=${status_line[2]}
if [ "$vagrant_type" = "error-exit" ]; then
echo "$(tput setaf 1)Failed to resume machine$(tput sgr 0)";
echo "$vagrant_data"
return;
fi
done
fi
cd - > /dev/null
}
function vagrant_resume()
{
vg_status=$(vagrant_get_status "$1")
if [ "$vg_status" = "saved" ]; then
res=$(vagrant_force_resume "$1")
echo "$res"
return;
elif [ "$vg_status" = "running" ]; then
echo "$(tput setaf 2)[Skipping] Machine is already running $(tput sgr 0)";
return;
else
echo "$(tput setaf 1)Invalid state: $vg_status $(tput sgr 0)";
return;
fi
}
function vagrant_force_suspend()
{
cd "$1"
local status_op=$(vagrant --machine-readable suspend)
if [ -z "$status_op" ]; then
echo "$(tput setaf 2)Successfully suspended the machine$(tput sgr 0)";
fi
cd - > /dev/null
}
function vagrant_suspend()
{
vg_status=$(vagrant_get_status "$1")
if [ "$vg_status" = "running" ]; then
res=$(vagrant_force_suspend "$1")
echo "$res"
return;
elif [ "$vg_status" = "saved" ]; then
echo "$(tput setaf 2)[Skipping] Machine is already suspended $(tput sgr 0)";
return;
else
echo "$(tput setaf 1)Invalid state: $vg_status $(tput sgr 0)";
return;
fi
}
function vagrant_status()
{
vg_status=$(vagrant_get_status "$1")
if [ "$vg_status" = "running" ]; then
echo "$(tput setaf 2)Running$(tput sgr 0)";
else
echo "$(tput setaf 1)Not Running $(tput sgr 0)";
fi
}
@vedang
Copy link

vedang commented Sep 23, 2014

Thanks, these will be super handy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment