Skip to content

Instantly share code, notes, and snippets.

@grier
Created February 8, 2012 23:41
Show Gist options
  • Save grier/1775527 to your computer and use it in GitHub Desktop.
Save grier/1775527 to your computer and use it in GitHub Desktop.
vSphere API - Create Linked Clone
public static void doClone(String url, String username, String password, String vmname, String clonename) throws Exception
{
ServiceInstance si = new ServiceInstance(new URL(url), username, password, true);
Folder rootFolder = si.getRootFolder();
VirtualMachine vm = (VirtualMachine) new InventoryNavigator(rootFolder).searchManagedEntity("VirtualMachine", vmname);
if(vm==null)
{
System.out.println("VM " + vmname + " not found");
si.getServerConnection().logout();
throw new Exception("Source Virtual Machine Not Found");
}
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
VirtualMachineRelocateSpec relSpec = new VirtualMachineRelocateSpec();
relSpec.diskMoveType = "createNewChildDiskBacking";
cloneSpec.setLocation(relSpec);
cloneSpec.setPowerOn(false);
cloneSpec.setTemplate(false);
cloneSpec.snapshot = vm.getCurrentSnapShot().getMOR();
System.out.println("Cloning " + vmname + " into " + clonename);
Task task = vm.cloneVM_Task((Folder) vm.getParent(), clonename, cloneSpec);
String status = task.waitForMe();
if(status==Task.SUCCESS)
{
System.out.println("VM cloned successfully.");
}
else
{
throw new Exception("Error while cloning VM");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment