英文:
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
然后,我尝试将接收到的硬盘添加到另一个虚拟机中,代码如下:
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得到了错误信息:
无法完成操作,因为文件或文件夹 [xxxxx] xxxxx/xxxxx.vmdk 已经存在
我做错了什么?谢谢!
英文:
I am try to add existing HDD from one virtual machine to other.
I use golang and this api: https://github.com/vmware/govmomi
At first i get disks from source vm like this:
for _, device := range devices {
currentDeviceLabel := device.GetVirtualDevice().DeviceInfo.GetDescription().Label
if strings.Contains(strings.ToLower(currentDeviceLabel), "hard disk"){
disks = append(disks, device)
}
return disks
And then i trying to add received disk to other 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()))
}
I get error from vSphere:
Cannot complete the operation because the file or folder [xxxxx] xxxxx/xxxxx.vmdk already exists
What i am doing wrong? Thanks!
答案1
得分: 1
我在这里找到了答案: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()))
}
英文:
I got answer here: https://github.com/vmware/govmomi/issues/790
Working code:
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()))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论