#!/bin/sh # simple script to clone a virtual machine (vmware) # to another datastore/folder. # usage: ./clone_vm.sh # source path must be a directory and contain a virtual machine (at least a single .vmdk file) # destination path must a directory, preexist and be empty (to avoid overwriting another machine) # sources: # https://serverfault.com/questions/372526/move-vmware-esxi-vm-to-new-datastore-preserve-thin-provisioning # https://communities.vmware.com/thread/498408 echo; echo "**** Simple virtual machine cloning script ****"; echo sleep 0.5; echo "Before you continue all snapshots need to be deleted" echo "and all virtual disks (.vmdk files) need to be consolidated."; echo echo "And please, for your own sake, make sure the VM is powered down!"; echo echo "Do you want to continue? [Y]" read a if [ -z $a ] || [ $a == "Y" ] || [ $a == "y" ]; then if [ $1 ] && [ $2 ]; then if [ -d $1 ]; then if [ -r $1 ]; then if [ -n "$(ls -A $1)" ]; then source=${1%/} if [ -d $2 ]; then if [ -w $2 ]; then if [ -z "$(ls -A $2)" ]; then destination=${2%/} sleep 0.5; echo "INFO: Preflight checks good. Commencing cloning process." for disk in $(find "$source" -maxdepth 1 -type f | grep ".vmdk" | grep -v "flat.vmdk"); do if [ -n "${disk##*delta*}" ]; then echo "ERROR: You little rebel did not remove all snapshots. Failsave exit!"; exit 1 fi #try the following to move a specific snapshot #find . -maxdepth 1 -type f | grep "000030.vmdk" sleep 0.5; echo "INFO: Cloning $disk to $destination" vmkfstools -i $disk -d thin $destination/${disk##*/} if [ $? -ne 0 ]; then echo "ERROR: An error occured while cloning $disk to $destination." fi done for file in $(find "$source" -maxdepth 1 -type f | grep -v ".vmdk"); do sleep 0.5; echo "INFO: Copying $file to $destination" cp "$file" "$destination" if [ $? -ne 0 ]; then echo "ERROR: An error occured while copying $file to $destination." fi done else sleep 0.5; echo "ERROR: Destination path is not empty ($2)."; exit 1 fi else sleep 0.5; echo "ERROR: Destination path is not writeable ($2)."; exit 1 fi else sleep 0.5; echo "ERROR: Destination path is not a directory ($2)."; exit 1 fi else sleep 0.5; echo "ERROR: Source path empty ($1)."; exit 1 fi else sleep 0.5; echo "ERROR: Source path is not readable ($1)."; exit 1 fi else sleep 0.5; echo "ERROR: Source path is not a directory ($1)."; exit 1 fi else sleep 0.5; echo "ERROR: Source and destination path must be given."; exit 1 fi else sleep 0.5; echo "ERROR: Mission aborted by user." exit 2 fi