Wednesday, May 6, 2009

VMware storage migration script

We're moving from SAN attached to NFS storage on our vmware environment, (and vSphere4 isn't out yet) so I wrote a script that will migrate VMs from current location to the new one (I had to hard-code the new location in, since when using sed the path with vmfs/ messed up sed due to the s/).

Warning: if you have VMs with 2 disks with the same name (if they were created in different directories) then this won't work. It will work for up to 3 disks, and should be easy to make support more.

#!/bin/bash
HOMEDIR=/vmfs/volumes/d42ddbc9-93beeb73
for VMNAME in `vmware-cmd -l | awk -F/ '{print $5}'`
do
mkdir $HOMEDIR/$VMNAME/
VMPATH=`vmware-cmd -l | grep $VMNAME | awk -F. '{print $1}'`
for VMDK in `grep scsi0:.*fileName $VMPATH.vmx | awk -F\" '{print $2}'`
do
vmkfstools -i $VMPATH.vmdk $HOMEDIR/$VMNAME/$VMDK -d 'thin' -a lsilogic
done

vmware-cmd -s unregister $VMPATH.vmx

sleep 2

cp $VMPATH.vmx $HOMEDIR/$VMNAME/$VMNAME.vmx.new

sed "s/scsi0:0.fileName.*/scsi0:0.fileName = \/vmfs\/volumes\/d42ddbc9-93beeb73\/${VMNAME}\/${VMNAME}.vmdk/" $HOMEDIR/$VMNAME/$VMNAME.vmx.new > $HOMEDIR/$VMNAME/$VMNAME.vmx.new2
sed "s/scsi0:1.fileName.*/scsi0:1.fileName = \/vmfs\/volumes\/d42ddbc9-93beeb73\/${VMNAME}\/${VMNAME}_1.vmdk/" $HOMEDIR/$VMNAME/$VMNAME.vmx.new2 > $HOMEDIR/$VMNAME/$VMNAME.vmx.new3
sed "s/scsi0:2.fileName.*/scsi0:2.fileName = \/vmfs\/volumes\/d42ddbc9-93beeb73\/${VMNAME}\/${VMNAME}_2.vmdk/" $HOMEDIR/$VMNAME/$VMNAME.vmx.new3 > $HOMEDIR/$VMNAME/$VMNAME.vmx

rm -rf $HOMEDIR/$VMNAME/*.new*
chmod +x $HOMEDIR/$VMNAME/$VMNAME.vmx
vmware-cmd -s register $HOMEDIR/$VMNAME/$VMNAME.vmx
done