Перенос виртуальной машины hyper v на proxmox
Перенос виртуальной машины из Hyper-V в Proxmox (KVM)
В данной статье мы рассмотрим как можно перенести виртуальную машину из Hyper-V в Proxmox (KVM).
Чтобы импортировать Vm из Hyper-V в Proxmox нужно конвертировать ее виртуальный диск.
Делается это в два этапа.
Первый этап это конвертирование диска Hyper-V в формат vhd.
Откройте консоль Hyper-V и выберите пункт «изменить диск»
Далее выберите диск вашей виртуальной машины
Выберите пункт преобразовать
Далее укажите тип — «виртуальный жесткий диск»
В конце мастера укажите расположение конвертированного диска.
Следующий этап — это загрузка сконвертированного vhd диска на Proxmox.
Подключитесь по Ssh к proxmox.
Создайте папку на датасторе (это можно сделать на примонтированном датасторе, например если вы используете датастор с ext4 или btrfs)
Далее загрузите в нее диск (например через winscp).
Мой датастор находится по пути /mnt/content/
Я создал следующую папку для диска /mnt/content/images/700/ и скопировал в нее по scp сконвертированный ранее vhd диск.
Теперь нужно запустить конвертацию vhd образа с qcow2.
Это довольно долгая операция.
Теперь нужно создать VM и подключить к ней сконвертированный диск qcow2.
Создайте в proxmox виртуальную машину, по характеристикам идентичную вашей изначальной машине в Hyper-V.
При создании VM выберите тип контроллера sata, иначе если будет указан тип Virtio, ваша VM не загрузится.
После создания машины удалите пустой виртуальный диск, который создал Proxmox, он нам не понадобится.
Если в Hyper-V ваша машина была второго поколения, то в Proxmox для созданной ранее машины нужно изменить тип биос на OVMF и добавить EFI диск
Добавленный EFI диск.
Теперь нужно добавить сконвертированный ранее qcow2 диск.
Сделать это можно отредактировав конфиг VM.
В интерфейсе proxmox посмотрите номер VM, в моем случае номер 700
Теперь посмотрите название Вашего датастора, на котором храниться сконвертированный диск qcow2
У меня он называется Backup_Storage
Запомните id машины и название датастора, они нам понадобятся при редактировании конфига.
Подключаемся к Proxmox по ssh и запускаем команду редактирования конфига
Converting a Hyper-V vhdx for use with KVM or Proxmox VE
Recently we removed a 1/2 rack of servers from one of our data centers. That included our last two Microsoft Hyper-V 2012 R2 servers that hosted two VMs with historical STH Bench data for development. To make things slightly more interesting, the domain controller had been removed so we had Hyper-V hosts that were not responding to GUI tools and we had one day to move data off them. Not a great situation, but we wanted to show how you can quickly convert a Hyper-V VM to KVM. In this case, we are putting the VMs on a Promxox VE cluster so we can get the VMs on an all-flash Ceph storage array. Proxmox VE is a Debian Linux based platform that combines features such as KVM virtualization, containers, ZFS, GlusterFS and Ceph storage as well as cluster management all with a nice Web GUI. If you are simply using a Ubuntu, RHEL or CentOS KVM virtualization setup, these same steps will work minus the Proxmox GUI views.
Converting Hyper-V vhdx Virtual Machine for KVM Usage
The total process took a long time as we only had 100mbps of bandwidth between the three data centers free for this project. The actual hands-on-keyboard time took a matter of minutes for both VMs. The trick is that our KVM system did not work with vhdx Hyper-V virtual machine drives so we needed to convert them into a qcow2 image (more on why later.)
Step 1: Export the VM to get a clean VHDx snapshot
Hyper-V has a great snapshot and replication feature. The Hyper-V hypervisors we had setup had a very fast 40GbE interconnect and SSD storage so we could take many snapshots. The first step is to export the VM so you can have one vhdxx virtual drive to transfer and convert. If you can use the GUI, this is a few clicks away.
Export Hyper V Vhdx (demonstrated on a desktop copy and Hyper-V Manager)
If you cannot get to a Hyper-V Manager GUI, then you will likely want to use the Export-VM command via PowerShell. If you get really stuck and cannot open a remote PowerShell session to the Hyper-V host, you can use RDP (if enabled) or iKVM on the server to get to a PowerShell prompt.
Using the Export-VM command via PowerShell or via the Hyper-V Manager GUI ensures that you get a single vhdx file ready to transfer and convert.
Step 2: Send the vhdx to the target KVM virtualization host
This step is really easy, especially if you exported the VM to a network share location. If so, you can simply copy the resultant vhdx to the new server. If you cannot, we have seen various other combinations of USB drives, SFTP clients and other methods to get the vhdx drive to the target server.
Step 3: Check the image before proceeding
Since the transfer was likely many GB in size and we are going Windows to Linux, it is always good to check that the vhdx image does not have errors before proceeding. Here is the command where “Bench-Dev.vhdx” is the file we transferred.
Hyper-V Vhdx To Proxmox Qcow2 Qemu-Img Check
As you can see, the vhdx file passed with no errors reported.
Migration of servers to Proxmox VE
Contents
Introduction
There are various ways to migrate existing servers to Proxmox VE. They can be divided into two categories:
Physical-to-Virtual (P2V) Migration of physical servers to Proxmox VE Virtual-to-Virtual (V2V) Migration of virtual machines and containers from other hypervisors to Proxmox VE
Physical-to-Virtual (P2V)
Follow these steps to do a P2V migration and turn a physical machine into a Proxmox VE virtual machine that uses Qemu and KVM.
Clonezilla Live CDs
This method is fast, reliable and OS independent as it uses live CDs.
VMware Converter
Physical (running) Windows server to Proxmox VE (KVM) using VMware vCenter Converter Standalone Client (V5)
Tested on an HP ProLiant ML350 G5 and G6
Prepare Windows
VMware vCenter Converter Standalone Client
Prepare location to save local image
This guide is using an external USB Hard Drive. You may also save to a mapped network share.
NOTE Although the final image will be around the same size as the actual amount of data on the server, the Proxmox VE server should have enough free space to fit the total physical disk of the server unless you plan to shrink the windows disks. once migrated to Proxmox VE.
VMware vCenter Settings
Launch VMware vCenter and use the following settings:
The next screen shows the settings for the virtual machine.
Click on Advanced options, select the Post-conversion tab and make sure ‘Install VMware Tools on the destination virtual machine’ is NOT check. We do not want to install VMware tools.
Click next and Finish.
Prepare the VM on Proxmox VE
Create a new KVM virtual machine. You’ll want to use similar CPU and memory as the physical system. In the Hard Disk menu, leave everything as default. We won’t be using the disk created by Proxmox VE. Finish creating the VM. Make note of the VMID. For this guide, we’ll be using 100 as an example.
Once the VMware converter has completed, disable all of the networks adapters on the physical server and shut down. Disabling the network adapters will avoid potential IP conflicts if you will start the physical server back into Windows after you have your new virtual server running.
Move the image to the Proxmox VE Server
Plug a USB Hard Drive into the server
From the Proxmox VE command line:
You should see the contents of the USB drive. In my case, the vmdk file was located in /mnt/usb/windows-server/
Converting to qcow2
This can take a while depending on the size of file and speed of your system.
Final Steps
Once the conversion is complete, we need to edit the configuration file for the VM.
In the line with ide0: we want to change vm-100-disk-1.raw,size=32G to windows-server.qcow2
You may delete the empty disk created by Proxmox VE when you created the VM.
Start the VM and open the console. Windows should boot up normally. It’ll take a few minutes to detect the hardware changes. If the Windows system had a static IP address, you’ll have to reconfigure the settings.
Alternative Methods
Virtual-to-Virtual (V2V)
Follow these steps to do a V2V migration and move a virtual machine from another hypervisor to a Proxmox VE virtual machine that uses Qemu and KVM.
VMware
This explains the migration from a VMware ESXi 6.7 hypervisor to Proxmox VE 6.1. It is tested with guests with the following operating systems:
Exporting
Install VMware’s ovftool on your Proxmox VE host. ovftool version 4.4 has been reported to work with the following versions of ESXi: 6.5 and 6.7. Others (for example, 6.0) might crash with an unhelpful error message
Remove any attached disk or ISO from your ESXi VM and run
to export a virtual machine from ESXi directly into your current directory.
You can replace the dot with any other path, for example «/mnt/pve/ «. This way you can export directly to a storage that you created in Proxmox VE.
Importing
Go to the command line interface of Proxmox VE. Use the command qm importovf
to import the virtual machine. For example:
This will create a new virtual machine, using cores, memory and VM name as read from the OVF manifest, and import the disks. You have to configure the network manually. You can find syntax and an example on how to use this command on its man page.
Note: Windows guests require a few additional steps |
If your guest is Windows, you additionally have to execute the following commands. This example assumes that your imported virtual machine has the ID 130.
This gives you a first working version. You can then improve your experience by installing additional drivers as explained in Windows 10 guest best practices.
Server self-migration
It is also possible to migrate without the need to export each VM separately including virtual disks.
This way, you can convert a server from vSphere to Proxmox VE without the need of a second server.
For this process your vSphere should use VMFS6 and you need at least one empty HDD.
1. Export the VM information without the disks using ovftool (you still need to configure the network configuration for each VM).
2. Install Proxmox VE on some disk that does not contain any important data. You don’t need vSphere anymore at this point. If you have an OS disk with only vSphere on it, then you can now overwrite it with Proxmox VE.
Warning: Do not use/touch any other existing drives which are VMFS formatted |
3. Create a directory on the above mention spare HDD.
4. Install vmfs6-tools which you need to mount (ready-only) the VMFS-formatted drives with the vSphere virtual disks.
5. List all available drives to identify the VMFS formatted ones
6. Mount the VMFS disk partition (note it is read only)
7. Convert the vSphere disk to a suitable format for Proxmox VE
8. While the conversion is in progress you may create the 1st VM from ovf
9. As soon as the conversion is finished you may mount the new Proxmox VE disk image to the VM.
If all VM images have been moved away from a VMFS6 disk, you can format it and use it at Proxmox VE
HyperV
This explains the migration from a Hyper-V on Windows 10 hypervisor to Proxmox VE 6.1. It is tested with a Proxmox VE 6.1 guest.
Go to the GUI of Proxmox VE and create a new virtual machine. We don’t need the hard disk that the virtual machine creation wizard created. Delete it in the hardware options of the virtual machine.
XEN also uses qemu disk format, so it should work in the same manner as described under «VMware to Proxmox VE (KVM)».
You can use xenmigrate to do it
FreeNAS
Those are the necessary steps to migrate a Ubuntu Bionic VM from FreeNAS 11.2 to Proxmox VE 6.2-1. The VM in FreeNAS was created with the following parameters
Check the name of your zvol by going to Virtual Machines → Options of the VM ⋮→ Devices → Options of your disk ⋮ → Edit → Zvol
Preparation in FreeNAS
Importing to Proxmox VE
Qemu/KVM
Create an new VM on Proxmox VE and add the existing disk image to this new VM, set the boot order and start.
First a VM has to be created. 120 is an unused VM ID.
someImage.img is an image that was created before. someStorage is the name of a storage as listed in pvesm status.
qm importdisk adds the image as unused disk to the virtual machine. Thus, making it the bootdisk is still necessary.
Further information
If your use case is not covered by this article you should check out the additional ways to migrate to Proxmox VE in the wiki. It gathers years of knowledge for cases which are not as common as the ones explained here.
Занимался на днях переносом виртуальных машин с обычного kvm гипервизора на proxmox. На исходном гипервизоре диски виртуальных машин были в формате qcow2. Я решил заодно сконвертировать диски из qcow2 в lvm и написать заметку об этом, чтобы не забыть.
Для тех, кто не знает, в чем разница между разными форматами дисков в гипервизоре KVM, предлагаю почитать об этом в моей статье на тему бэкапа виртуальных машин kvm. В общем случае, сконвертировать диски qcow2 в lvm можно следующим образом. Сначала преобразуем их в raw формат с помощью qemu-img.
Далее raw образ переносим на новый сервер. На нем же к виртуальной машине подключаем новый диск из lvm хранилища такого же размера, как raw образ. Далее в консоли proxmox выполняем конвертацию в lvm с помощью обычного dd.
Все то же самое можно сделать одной командой на новом сервере, перенеся туда диск в формате qcow2.
Я описал общий случай для любого гипервизора KVM. Но конкретно в proxmox это можно сделать проще. Если вам нужно конвертировать qcow2 в lvm на этом же хосте, то достаточно просто через web интерфейс выбрать Move disk и указать в качестве storage хранилище с LVM. Proxmox сам конвертирует диск с помощью того же qemu-img.
Если вы выполняете, как и я, перенос виртуальной машины с одного сервера на другой, то действуйте так:
Я по такой схеме переносил как linux машины, так и windows. Проблем не было. Единственное, надо не забыть зайти через консоль в windows машину и проверить сетевые настройки. Нужно будет заново настроить сеть, иначе по rdp не подключиться. После переноса сетевой адаптер поменяется.
Импорт kvm виртуалок в Proxmox
Система виртуализации на базе Proxmox все больше набирает популярность при создании IT инфраструктуры в последнее время. Данное решение объединяет в себе черты профессиональной системы виртуализации с возможностью создания кластеров и централизованного управления с одной стороны. А также все свойства Open Source продукта с другой стороны. При миграции на данную систему управления виртуализации Вам скорее всего придется столкнуться с задачами импортирования виртуальных машин как из среды VMware, так и работающих под управлением гипервизора kvm. Как это сделать легко и просто со вторым типом виртуальных машин, используемых в open source среде хочется рассказать поподробнее.
Последовательность действий
Для начала миграции kvm виртуальной машины ее необходимо выключить на хосте источнике. После этого найти образ жесткого диска, который используется в виртуальной машине. Данный образ копируется на хост назначения с Proxmox, на котором мы будем проводить импорт. Допустим, образ нашего диска называется kvm_virtual_disk.qcow2.
Теперь создадим виртуальную машину в гипервизоре Proxmox с помощью утилиты qm. Данная программа одна из нескольких, часто используемых для управления и настройки Proxmox VE. В данном примере идентификатор машины будет 222, в реальной жизни используем любой свободный в нашей среде виртуализации. Также рекомендую использовать на всех виртуальных машинах qemu agent, для обеспечения более полного взаимодействия между гипервизором и виртуальной машиной. Для этого при создании ВМ добавляем опцию —agent enabled=1. Пример команды qm, создающий виртуальную машину, представлен ниже.
Когда операция успешно завершится, проводим заключительную операцию по привязке диска к виртуальной машине с помощью все той же утилиты qm. Это делается следующим образом.
После этого донастраиваем параметры CPU, Memory, если надо сетевых интерфейсов в веб панели Proxmox. Теперь наша виртуалка полностью импортирована и готова к работе в среде Proxmox. Осталось запустить ее и дождаться отклика в консоли.
Заключение
Небольшая статья показывает основные моменты для импорта виртуальных машин kvm в гипервизор Proxmox. Хотя, в гипервизоре есть удобный веб интерфейс для управления, однако, все основные действия в данном случае приходится делать с помощью утилит командной строки. С учетом того, как хорошо развивается проект Proxmox VE в целом, можно предположить, что в скором будущем данный функционал будет доступен и в веб интерфейсе.