"key => -1" works fine for me:
Since I am adding a bunch of pre-existing disks, what I do is this:
- locate the disks based on the datastore and folder location using datastore browser (SearchDatastoreSubFolders call).
- do an inventory of the controllers so that I can reference the controller keys when needed
- do an inventory of the virtual disks currently attached to the vm (so that I know if adding more disk to a particular virtual node makes sense).
then loop through the diks that you have found from the datastore and are supposedly attaching disks to.
my $backing = @$disks[$i]->diskType->new (
diskMode => 'independent_persistent',
fileName => $result->folderPath . @$disks[$i]->path,
);
my $connectInfo = VirtualDeviceConnectInfo->new (
allowGuestControl => 0,
connected => 1,
startConnected => 1,
);
my $devInfo = VirtualDisk->new (
backing => $backing,
controllerKey => $ctrlKey,
unitNumber => $unit,
connectable => $connectInfo,
key => -1,
capacityInKB => @$disks[$i]->capacityKb,
);
$devspec[$i] = VirtualDeviceConfigSpec->new(
operation => VirtualDeviceConfigSpecOperation->new('add'),
device => $devInfo,
);
Once finish the loop, construct the $spec and run reconfigVM (or reconfigVM_task):
my $spec = VirtualMachineConfigSpec->new(deviceChange => [@devspec] );
if (@devspec) {
print "Reconfig VM with disk changes...\n";
# Asynchronous vs Synchronous execution
#eval { $vm->ReconfigVM(spec => $spec); };
eval { $vm->ReconfigVM_Task(spec => $spec); };
if ($@) { print "Reconfiguration failed.\n $@";}
else {print "Disks added successfully.\n"; }
} else { print "Nothing to add!\n"};