VMWare ESXI – restart VM automatically
Not sure this still applies in 2021 - switched vm to bhyve... buy migrating this post anyway!
Last week, I experienced my first issue on a VMWare ESXI 5.1 server: the host we rent has a 99.9% uptime, and it was gone for it’s 0.1% downtime.
Usually this shouldn’t be an issue, this was without counting that
A few Google searches lead me to the writing of a small script, that uses ESXI native tools to detect VM and their state on a ESXI host and start the VM if it is down. This first version does it blindly for all VM on the host… it doesn’t check a list for some VM to start.
First of all, put the file following script on the server – for example as /esxi_autoup.sh
for i in $(/bin/vim-cmd vmsvc/getallvms|cut -f 1 -d" "|grep -v "Vmid") do echo "testing $i" if [ "$(/bin/vim-cmd vmsvc/power.getstate $i|grep "Powered on")" = "" ]; then echo "$i is down... --> Restarting" /bin/vim-cmd vmsvc/power.on $i else echo "$i is Running... --> Not restarting" fi done
# chmod 500 /esxi_autoup.sh # ./esxi_autoup testing 10 10 is Running... --> Not restarting testing 12 12 is down... --> Restarting
~ # ./esxi_autoup.sh testing 10 10 is Running... --> Not restarting testing 12 12 is Running... --> Not restarting
# vi /var/spool/cron/crontabs/root * * * * * /esxi_autoup.sh
When saving the file, if told it is read-only, use vi’s :w! to override – and your VM’s should now be up all the time – for free, even when you’re not at home \o/.
The used ESXI commands where found on VMWare knowledge base