Skip to content

Instantly share code, notes, and snippets.

@gsaslis
Created May 31, 2017 09:47
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gsaslis/1f76790c02a9cfdc0803e49cb5278c7a to your computer and use it in GitHub Desktop.
Save gsaslis/1f76790c02a9cfdc0803e49cb5278c7a to your computer and use it in GitHub Desktop.
Bash script to cleanup Virtualbox VMs you might have lying around.
#!/usr/bin/env bash
SAVEIFS=$IFS # save old IFS value
IFS=$'\n' # make newlines the only separator
echo "Powering off all running VMs"
for vm in $(VBoxManage list runningvms | awk '{print substr($2, 2, length($2) - 2)}') # you might want to limit your search by `| grep 'some vm name here' ` *before* the pipe to awk
do
echo "Powering off VM ${vm}"
VBoxManage controlvm ${vm} poweroff
echo "VM ${vm} powered off"
done
echo "Getting rid of any left over CI vagrant VMs"
for vvm in $(VBoxManage list vms) # you might want to limit your search by `| grep 'some vm name here' `
do
echo "Cleaning up VM ${vvm}"
vm_id=$(echo "${vvm}" | awk '{print substr($2, 2, length($2) - 2)}')
vm_name=$(echo "${vvm}" | awk '{print substr($1, 2, length($1) - 2)}')
echo "powering off vm id ${vm_id}"
VBoxManage controlvm ${vm_id} poweroff
echo "unregistering vm id ${vm_id}"
VBoxManage unregistervm ${vm_id}
echo "deleting vm ${vm_name} from disk"
rm -rf ~jenkins/VirtualboxVMs/${vm_name}
echo "VM ${vm} powered off and deleted"
done
IFS=$SAVEIFS # restore IFS value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment