How to move VMware ESXi VM to new datastore using vmkfstools
After replacing or upgrading some storage on your VMware ESXi server it could be useful or mandatory to move some VM to a new datastore.
The process is not too complex but it requires some explanation:
- Power off VM
- (Optional) Consolidate snapshots if needed.
- Remove VM from vCenter inventory
- Right click VM and click “Remove from Inventory"
- Enable SSH on the ESXi machine
- In the vSphere client go to: Configuration -> Security profile -> Properties (next to Services) -> SSH (in the list) -> Options -> Start
- Log in via SSH as root
- Prepare a directory on the destination datastore
mkdir "/vmfs/volumes/destination_datastore/Some VM"
- Clone the .vmdk files using thin provisioning
vmkfstools -i "/vmfs/volumes/source_datastore/Some VM/Some VM.vmdk" -d thin "/vmfs/volumes/destination_datastore/Some VM/Some VM.vmdk"
- Copy any remaining files (avoiding overwriting the .vmdk files)
find "/vmfs/volumes/source_datastore/Some VM" -maxdepth 1 -type f -print0 | grep -v ".vmdk" | while read file; do cp "$file" "/vmfs/volumes/destination_datastore/Some VM"; done
- If you did not consolidate snapshots in step 2, there may be snapshot .vmdk delta files, we also need to copy these (this may take some time):
find "/vmfs/volumes/source_datastore/Some VM" -maxdepth 1 -type f -print0 | grep  | grep ".vmdk" | while read file; do cp "$file" "/vmfs/volumes/destination_datastore/Some VM"; done
- Once done cloning and copying all necessary files, add the VM from the new datastore back to inventory
- In the vSphere client go to: Configuration->Storage->Data Browser, right click the destination datastore which you moved your VM to and click "Browse datastore”.
- Browse to your VM and right click the .vmx file, then click “Add to inventory"
- Boot up the VM to see if it works, when asked whether you copied or moved it, just answer that you copied it. (I’m not sure what this means, but I think it has to do at least with the MAC address of the vNIC being changed.)
- If the VM boots up fine, you can remove the VM from the old datastore.
rm -rf "/vmfs/volumes/source_datastore/Some VM"