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

3. Replace ‘testvm’ with the appropriate vmName.

4. Save the content and quit (:wq).
5. Change the file permission to executable

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:

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

  • cron

    Perfect, exactly what I needed!