2011年12月12日 星期一

Want to add a cron into ESXi?

Recently our IT have one requirement to let ESXi automatic shutdown.
I do some study, and write a very simple script to finish this task.

Step1:
Add one script file in /bin/cshutdown.sh
The content is as follow.
#!/bin/ash
VMLIST=/tmp/vms
/bin/vim-cmd vmsvc/getallvms |awk '{print $1}' > /tmp/vms
while read VMID; do
if [[ $VMID == "Vmid" ]]; then
echo "Not a valid VMID"
else
/bin/vim-cmd vmsvc/power.shutdown ${VMID}
fi
done < ${VMLIST}
#Wait for 2 mins time for VM shutdown
sleep 120
busybox halt

Step2
Add this script into /var/spool/cron/crontabs/root
The content is below
30 20 12 12 * /bin/cshutdown.sh

The time format must be used UTC timezone, since VMware KB suggest don't suggest to use local timezone, so you must convert your localtime to UTC time.

Step3
Do following command to restart cron daemon
#kill `cat /var/run/crond.pid`
#busybox crond

This script still need to improve to double check the VM status is already shutdown well.
Maybe add this feature into next version.