Search code examples
javatemplatesvirtual-machineclonevmware

Change disk size while cloning vm from template in vmware in java


I am very new to the vmware. I have requirement to change the Hard disk size while creating vm from template. Basically its cloning. But when i try to excecute it gives me the error "a specified parameter was not correct device.key".

Can you please help me here.

Here is my code:

VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec();
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec();
diskSpec.setOperation(VirtualDeviceConfigSpecOperation.edit);
VirtualDisk vd = new VirtualDisk();
long diskSizeKB = 1000000;
int cKey = 1000;
vd.setCapacityInKB(diskSizeKB);
diskSpec.setDevice(vd);
vd.setControllerKey(cKey);
vd.setKey(1);
vd.setUnitNumber(2);
VirtualDiskFlatVer2BackingInfo diskfileBacking =  new VirtualDiskFlatVer2BackingInfo();
String fileName = "[TestDataStore]";
diskfileBacking.setFileName(fileName);
diskfileBacking.setDiskMode("persistent");
diskfileBacking.setThinProvisioned(true);
vd.setBacking(diskfileBacking);
relocateSpec.setDatastore(vmInstace.getDatastores()[0].getMOR());
relocateSpec.setHost(hostSystem.getMOR());
relocateSpec.setPool(resourcePool.getMOR());
cloneSpec.setPowerOn(false);
cloneSpec.setLocation(relocateSpec);
VirtualMachineConfigSpec vmSpec = new VirtualMachineConfigSpec();
vmSpec.setMemoryMB(4000L);
vmSpec.setNumCPUs(3);
vmSpec.setDeviceChange(new VirtualDeviceConfigSpec[] {diskSpec});
cloneSpec.setConfig(vmSpec);
Task task = vmInstace.cloneVM_Task((Folder) vmInstace.getParent(),"TestVM", cloneSpec);

Solution

  • Each device (disk, controller, etc.) of a VM has its own unique key. The way VM configuration changes work is that you provide the key of the device you want to change, along with the new configuration.

    In your code, you call vd.setKey(1), and VMware is telling you that you gave an invalid key.

    Where did you get the value 1? If I had to guess, it was chosen arbitrarily. You will need to look at the configuration of the template and extract the disk device key from there. Then use this key in the call to vd.setKey.