Thursday, August 31, 2017

Scripted Cron Shutdown Guest VM's & ESXi Server

By customer request I had to find a way to setup a solution to do a automated shutdown all guests on a ESXi server gracefully. After that the ESXi host had also to be shutdown. 

On an ESXi server you can't access the crontab via crontab -e, but you can edit the config file and kill & restart the crond.

What it took to get this running:
Login to ESXi as root and execute these steps

Kill crond
[root@esxi1:~]/bin/kill $(cat /var/run/crond.pid)
Edit crontab

[root@esxi1:~] vi  /var/spool/cron/crontabs/root
#min hour day mon dow command
1    1    *   *   *   /sbin/tmpwatch.py
1    *    *   *   *   /sbin/auto-backup.sh
0    *    *   *   *   /usr/lib/vmware/vmksummary/log-heartbeat.py
*/5  *    *   *   *   /sbin/hostd-probe ++group=host/vim/vmvisor/hostd-probe
00   1    *   *   *   localcli storage core device purge

# My added lines
0    13   30  8   *   /sbin/vmware-autostart.sh stop
15   13   30  8   *   /sbin/shutdown.sh && /sbin/poweroff

Start crond


[root@esxi1:~]/usr/lib/vmware/busybox/bin/busybox crond
Above added lines in the crontab will result in the guests to be shutdown on 30th of August at 13:30 UTC time. The last line will shutdown the ESXi host 15 min later. So, check your system time via date.
[root@esxi1:~] date
Thu Aug 30 16:38:36 UTC 2017
The gracefull guest shutdown will only work if the guests are configured for autostart in ESXi. The original crontab will be restored automatically with the next system boot.
If you want your changes to be permanent you could archieve this by editing
/etc/rc.local.d/local.sh to readd your changes at every system startup.
Example:
#!/bin/sh 
#Kill crond
/bin/kill $(cat /var/run/crond.pid) 
#Your added lines
/bin/echo "0    13   30  8   *   /sbin/vmware-autostart.sh stop" >> /var/spool/cron/crontabs/root
/bin/echo "15   13   30  8   *   /sbin/shutdown.sh && /sbin/poweroff" >> /var/spool/cron/crontabs/root
#Start crond
/usr/lib/vmware/busybox/bin/busybox crond 
exit 0
Keep in mind that all these changes are not officially supported by VMware. Use at your own risk.