Skip to content

Instantly share code, notes, and snippets.

@ConorShore
Last active November 30, 2020 17:11
Show Gist options
  • Save ConorShore/5508f9a181ca3a03c0d778cea0cbaf14 to your computer and use it in GitHub Desktop.
Save ConorShore/5508f9a181ca3a03c0d778cea0cbaf14 to your computer and use it in GitHub Desktop.
A script that boots a VM, waits till it reports that it is on, then forces iSCSI rescans until a target devices is only. Very useful for iSCSI from internal VM
#Originally inspired by this script https://jc-lan.org/2020/02/05/script-to-automatically-rescan-and-mount-software-iscsi-datastores-on-startup-for-esxi/
#This original script didn't work for me, as it didn't wait until the vm was confirmed on, so would boot loop if the vm didn't boot first time
#Designed to go in the ESXI host's local.sh file. This will mean vm autostart will not occur till after this script has executed
#Establish our timer
count=0
#Power on the guest VM with the specified Vmid
#use the command vim-cmd vmsvc/getallvms to find which Vmid to use
# the number '1' is the vmid in this example
vim-cmd vmsvc/power.on 1
#loop until the vm is actually powered on
while ! vim-cmd vmsvc/power.getstate 1 | grep on
do
logger "local.sh: attempting to power on vm 1"
vim-cmd vmsvc/power.on 1 2>&1 | logger &
sleep 30
done
logger "local.sh: VM 1 should be on now"
#Now continuously rescan for the iSCSI device until it is found
#or the maximum time of 10 minutes is reached.
#This command will search all Logical Devices for one that has "Vendor_Name" in the Display Name (e.g., FreeNAS, TrueNAS)
while ! esxcfg-scsidevs -c | grep -q 'Vendor_Name'
#Alternatively if you have multiple iSCSI targets that share the same Display Name
#(iSCSI Vendor) then you may want to instead search by Volume Name.
#This method allows you to single out a specific server since Volume Name is user configurable.
#The command below will search for the volume name 'Your_custom_volume_name' and that Mounted status is true.
#while ! esxcli storage filesystem list | grep -q "Your_custom_volume_name.*true"
do
#print some debugging info to the syslog
logger "local.sh: Forcing rescan since iSCSI target is not yet available..."
#Rescan SCSI HBAs to search for new Devices, remove DEAD paths and update path state.
#This operation will also run an claim operation equivalent to the claimrule run command and a filesystem rescan.
esxcli storage core adapter rescan --all
#Now wait (in seconds) before checking again
sleep 30
#Increase the timer
count=`expr $count + 30`
#Check if maximum time has been reached (in seconds)
if [ $count -ge 600 ]
then
logger "local.sh: Aborting, maximum time reached while searching for iSCSI target."
break
fi
done
logger "local.sh: Search time for iSCSI target was" $count "seconds."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment