ESXi bash script to automate Power ON VM if its Powered OFF

This script with the help of crontab will enable ESXi 5.1 to poll the VM state every hour to check if it is ON and if not power it ON.

1. SSH to the host.
2. Copy and paste the following content to the shell script (auto-poweron.sh) which is placed in a vmfs volume.

Eg :-
Having enabled ssh access to your ESXi server, ssh in as root.
~ #vi /vmfs/volumes/datastore1/auto-poweron.sh

[crayon lang=”shell”]
vmname=”testvm”
vmid=$(vim-cmd vmsvc/getallvms | grep “$vmname” | awk ‘{print $1}’)
stat1=$(vim-cmd vmsvc/power.getstate “$vmid” | grep “off”)
if [ “$stat1” == “Powered off” ]
then
vim-cmd vmsvc/power.on “$vmid”
fi
[/crayon]

3. Replace ‘testvm’ with the appropriate vmName.

4. Save the content and quit (:wq).
5. Change the file permission to executable
[crayon lang=”shell” escaped=”true”]
chmod 755 /vmfs/volumes/datastore1/auto-poweron.sh
[/crayon]
6. Create a cron job to execute this script every one hour.

Add cron Job to ESXi 5.1

1. Edit /var/spool/cron/crontabs/root using VI.
2. Add the line (all on one line) at the bottom and save (:wq!).
0    */5    *    *    *     /vmfs/volumes/datastore1/auto-poweron.sh
3. Run the command “cat /var/run/crond.pid”
4. That will print the process number of the running crond, such as 12345
5. Run the command “kill 12345”
where “12345” should be replaced with the number output by the previous command

The above changes on ESXi do not persist across reboots. To make sure the cron job is consistant across reboot follow these steps.

Add commands to /etc/rc.local.d/local.sh to re-generate the cron job when ESX/ESXi reboots
1. Edit /etc/rc.local.d/local.sh, using a command such as “vi /etc/rc.local.d/local.sh“.
2. At the end of the file just above ‘exit 0’, add following 3 lines. The first kills crond, the second adds the new cron job to the root crontab file, and the third restarts crond:
[crayon lang=”shell” escaped=”true”]
/bin/kill $(cat /var/run/crond.pid)
/bin/echo ‘0 */5 * * * /vmfs/volumes/datastore1/auto-poweron.sh’ >> /var/spool/cron/crontabs/root
crond
[/crayon]
3. Save and exit the editor (Press the “Esc” key then “:wq” then press “Return” in vi)
4. Run the command “auto-backup.sh” so that the change to /etc/rc.local.d/local.sh survives a reboot.

-SD