vSphere,通过 API(govmomi) 将现有 HDD 添加到 VM

vSphere, add existing HDD to VM via API(govmomi)

我正在尝试将现有硬盘从一台虚拟机添加到另一台。 我使用 golang 和这个 api: https://github.com/vmware/govmomi

起初我像这样从源虚拟机获取磁盘:

for _, device := range devices {
        currentDeviceLabel := device.GetVirtualDevice().DeviceInfo.GetDescription().Label
        if strings.Contains(strings.ToLower(currentDeviceLabel), "hard disk"){
        disks = append(disks, device)
    }    
return disks

然后我尝试将收到的磁盘添加到其他 VM:

func addDisk(vm *object.VirtualMachine, disk types.BaseVirtualDevice) {

    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

    spec := types.VirtualMachineConfigSpec{

        DeviceChange : []types.BaseVirtualDeviceConfigSpec {

            &types.VirtualDeviceConfigSpec{

                Operation: types.VirtualDeviceConfigSpecOperationAdd,
                FileOperation: types.VirtualDeviceConfigSpecFileOperationCreate,
                Device: disk,
            },

        },
    }

    result, err := vm.Reconfigure(ctx, spec)
    if err != nil {
        log.Fatal(fmt.Sprintf("err: %s", err.Error()))

    }

我从 vSphere 收到错误:

Cannot complete the operation because the file or folder [xxxxx] xxxxx/xxxxx.vmdk already exists

我做错了什么?谢谢!

我在这里得到了答案:https://github.com/vmware/govmomi/issues/790

工作代码:

spec := types.VirtualMachineConfigSpec{}
config := &types.VirtualDeviceConfigSpec{
    Device:    disk,
    Operation: types.VirtualDeviceConfigSpecOperationAdd,
}
spec.DeviceChange = append(spec.DeviceChange, config)

result, err := vm.Reconfigure(ctx, spec)
if err != nil {
    log.Fatal(fmt.Sprintf("err: %s", err.Error()))

}