I recently had a need to make a bunch of clones of a vmware virtual image on my vmware server. After doing a few by hand, I got tired of it and wrote a little script to do it for me. The script assumes that there’s a working set of virtual image files in a directory named “vm-template” and that the virtual machine name defined in the template is also “vm-template.” You can change these values by changing the SOURCE_DIR and SOURCE_NAME variables at the top of the file (or you could modify the script to set these variables using passed arguments). Whatever image you wind up using to do the cloning, you should make sure it isn’t running in order to avoid unpredictable results when doing the copy.
To use the script, just run it, passing the desired new virtual image name as an argument. A directory will be created using that name (so avoid spaces or weird characters; escaping them might also be ok). Files from the image to be cloned will then be copied into the new directory. The SOURCE_NAME value in the source image’s .vmx file will be replaced with the name you pass as an argument, and all files will be renamed to use the argument’s name rather than the SOURCE_DIR name. To clarify: Typically, your source image will live in a directory named (for example) “vm-template” and will be full of files named (for example) “vm-template.vmx,” “vm-template.vmdk,” etc. The script renames any such matching files to use the argument passed, and it changes references to those names within the .vmx file to point to the renamed file.
If your source image is large, it could take a few minutes to copy the files. The rest of the process goes quickly. Once you’re done, if you’re using vmware server, you’ll want to pick the option to add a new machine to the inventory. Then browse to the new file. When you boot it up, you should see (I’m using the web console here) a warning asking you whether you copied or moved the image. This is because we didn’t do anything to change the guid that identifies the image. Tell vmware server that you copied it, and it should make any necessary adjustments and boot your image.
Once it’s booted, you’ll need to make adjustments such as changing the hostname and applying any patches or updates that may have landed since you created the source image.
The script I used follows.
#!/bin/bash SOURCE_DIR="vm-template" SOURCE_NAME="vm-template" DEST_NAME=$1 if [ -z $DEST_NAME ]; then echo echo "Please specify a VM name as the sole argument" echo exit 1 fi if [ -e $DEST_NAME ]; then echo echo "$DEST_NAME already exists. Please specify another." echo exit 2 fi echo mkdir $DEST_NAME echo "Copying source files to $DEST_NAME directory" echo cp -R $SOURCE_DIR/* $DEST_NAME/ cd $DEST_NAME for file in `ls |grep $SOURCE_NAME`; do new=`echo $file | sed 's/'$SOURCE_NAME'/'$DEST_NAME'/'` mv $file $new done perl -pi -e 's/'$SOURCE_NAME'/'$DEST_NAME'/g' *.vmx rm -rf *.lck