Friday, May 3, 2024
101
rated 0 times [  101] [ 0]  / answers: 1 / hits: 117362  / 3 Years ago, thu, june 3, 2021, 7:32:56

I use vagrant for development. I forget to shut down a few of the VMs. When I go to log out of my host machine, the Ubuntu shutdown process appears to hang.



Might there be a way to script a close of all vagrant boxes with a bit of commandline-fu? Something like the following, but something that, well, works.



for f in $HOME/vagrant;
do;
cd $f
vagrant halt
done;

More From » command-line

 Answers
4

For a scriptable control of Virtual Box machines we can make use of the VBoxManage commands:




  • List running machines (returns name and UUID):



    VBoxManage list runningvms

  • Stop running VMs by "hibernating" them (reommended to avoid data loss)



    VBoxManage controlvm <name|uuid> savestate

  • Poweroff running VMs (not recommended because we may lose data in the guest)



    VBoxManage controlvm <name|uuid> poweroff

  • Use ACPI in an ACPI-aware guest OS (preferable to poweroff for graceful shutdown of guests)



    VBoxManage controlvm <name|uuid> acpipowerbutton



Also see: How to safely shutdown Guest OS in VirtualBox using command line



Update from OP



Based on this selected correct answer below, I've added this bash script "$HOME/bin/stop-vagrant.sh". So now I have something that can safely begin a stop of all vagrant VMs that I might have turned on yet forgotten about in a session.



vboxmanage list runningvms | sed -r 's/.*{(.*)}/1/' | xargs -L1 -I {} VBoxManage controlvm {} savestate


Command Explained:



vboxmanage list runningvms | -- gets a list of all running vms under VirtualBox



sed -r 's/.*{(.*)}/1/' | -- strips the string down to id number



xargs -L1 -I {} VBoxManage controlvm {} savestate -- runs the save state command on each box that's open.



On xargs




  • -L1 - take one line at a time

  • -I {} - uses {} as a place holder for the next command


[#25576] Saturday, June 5, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
looweets

Total Points: 52
Total Questions: 114
Total Answers: 111

Location: Turkmenistan
Member since Sat, Apr 16, 2022
2 Years ago
looweets questions
Fri, Apr 29, 22, 09:47, 2 Years ago
Thu, Nov 3, 22, 03:32, 2 Years ago
Sun, Mar 5, 23, 00:43, 1 Year ago
;