Convertir une machine Linux Hyper-V en Gen 2

Existe-t-il un moyen de convertir facilement (et sans réinstallation) une VM Linux Hyper-V (gen 1) en gen 2 ?

Je connais la cmdlet Convert-VMGeneration pour PowerShell (celle-ci : https://code.msdn.microsoft.com/windowsdesktop/Convert-VMGeneration-81ddafa2) mais elle ne fonctionne pas avec les VM Linux.

Je rencontre des problèmes d’exécution sur HyperV (la machine ne répond plus pendant un moment, etc.), qui pour la plupart, d’après ce que j’ai vu, sont grandement améliorés en Gen2 (nous suivons toutes les pratiques recommandées par Microsoft pour exécuter Linux sur Hyper-V mais ce n’est toujours pas suffisant, au moins en Gen1).

La VM originale fonctionnait sur un hôte Windows Server 2008. Nous avons mis à niveau vers un hôte 2012 R2 et pouvons maintenant exécuter Gen2, mais chaque source que j’ai trouvée dit qu’il faut réinstaller Linux (je n’ai pas réussi à comprendre pourquoi, mais il doit y avoir une raison).

L’installation et la migration pour ce serveur particulier (c’est un serveur Gitlab fonctionnant sous Ubuntu 14.04) sont assez laborieuses et nous préférerions ne pas réinstaller et migrer si possible.

Puisque c’était le premier résultat lorsque j’ai essayé de trouver une réponse, je publie ma propre solution, même si cela fait plus de 6 ans depuis la question. (au passage fercasas.com dans les anciens commentaires n’est plus disponible donc je ne pouvais pas dire si c’était utile ou non)

Introduction et notes

Quoi qu’il en soit, le vrai problème est BIOS vs UEFI, tandis que IDE vs SCSI ne m’a pas posé de problème supplémentaire.

Donc en bref - la réponse est la même que pour convertir un PC BIOS en PC UEFI.

Un peu plus de détails ci-dessous.

Note n°1 : J’ai fait cela avec Ubuntu 20.04, Ubuntu 16.04 et CentOS 7, je dois répéter cela avec Ubuntu 18.04, si cela diffère de manière importante, je modifierai la réponse.

Note n°2 : Comme toujours, votre schéma de partitionnement et vos noms de disques seront probablement différents de mes exemples, VEUILLEZ les modifier en conséquence, je ne suis en aucun cas responsable de la perte de données si vous formatez la mauvaise partition ! Vous pouvez vérifier les partitions dans votre OS d’origine en utilisant fdisk -l et/ou cat /etc/fstab

Note n°3 : Je recommande de sauvegarder l’ensemble de la VM avant cette procédure, par exemple en utilisant la fonction “Exporter” dans le gestionnaire Hyper-V

Ubuntu 20.04

Voici les instructions basées sur mes VM Ubuntu 20.04 (installées fraîchement pour ce but, paramètres d’installation par défaut) :

# boot your Gen 1 VM
# note: all steps done as root, so sudo su first
    sudo su

# install grub efi version for later use, just in case; note: it will remove other version on install
    apt-get install -y grub-efi
# backup current boot files
# make /boot2 folder and copy everything from /boot to /boot2 (for backup, safe keeping, later use)
    mkdir -p /boot2
    cp -r /boot/* /boot2

# delete old VM in Hyper-V Manager, but keep the VHDX file(s) (also, remember to export/backup before trying this all)
# create new Gen2 VM with same settings, and attach existing VHDX file(s)
# Add DVD drive and make it first device, attach same ISO image you used to install this OS
# boot LiveCD, or server install + shell, or similar, it's important to boot in Gen2/EFI mode
# if you boot in Server installer, pick Help, Enter shell

# Prepare partitions and mounts
# format old boot partition to FAT
    mkfs -t vfat /dev/sda2
# create mountpoints
    mkdir -p /mnt/boot
    mkdir -p /mnt/root
# mount them
    mount /dev/sda2 /mnt/boot/
    mount /dev/ubuntu-vg/ubuntu-lv /mnt/root/
#       OR
    mount /dev/mapper/ubuntu--vg-ubuntu--lv /mnt/root/

# copy files from old (BIOS) /boot2 backup, one you made before formatting
# copy backup files back to /boot
    cp -r /mnt/root/boot2/* /mnt/boot/
# install EFI grub
    apt-get install -y grub-efi
    grub-install --force --target=x86_64-efi --boot-directory=/mnt/boot --efi-directory=/mnt/boot /dev/sda
# should reply:     - No error reported
# edit fstab
    nano /mnt/root/etc/fstab
# change UUIDs to what says in comments above them like "was on .... during curtin installation".. so use that "....", for example
# also /boot needs to be changed from ext2/ext4/whatever to "vfat", so like this
    /dev/ubuntu-vg/ubuntu-lv / ext4 defaults 0 0
    /dev/sda2 /boot vfat umask=0077 0 0
# keep other entries (eg swap) as is, or if you know what you're doing change them in similar way, or find new UUIDs, etc.

# now we can shut down VM, unmount DVD/ISO, and get it ready for normal boot
    poweroff
# eject media + enter
# turn off VM

# start again by doing: Connect, Start

# after successful reboot, install and update grub, to have correct and fresh system with current mounts etc
# if you had to manually fix boot, first fix whatever was wrong (like fstab, or whatever), then do this
    grub-install /dev/sda --efi-directory=/boot
    update-grub
    reboot

C’est essentiellement tout avec Ubuntu 20.04. J’ai essayé d’installer un nouveau noyau après cette procédure, et après update-grub et redémarrage, j’ai pu voir les nouvelles entrées. Les futures mises à jour devraient donc fonctionner également.

En cas de problème, ne désespérez pas ! Si vos premières tentatives échouent et que vous vous retrouvez à l’invite grub >, vous pouvez corriger en faisant quelque chose comme ceci :

# if you reboot to grub rescue prompt, you can still fix everything, no need to return to original export/backup files !
# enter these commands
# try this first
    configfile (hd0,gpt2)/grub/grub.cfg
# if above didn't start boot, try manually like this, instead "-x.x.x-xx-generic" enter your current kernel version, use tab to autocomplete
    set root=(hd0,gpt2)
    insmod linux
    linux /vmlinuz-x.x.x-xx-generic root=/dev/mapper/ubuntu--vg-ubuntu--lv
    initrd /initrd.img-x.x.x-xx-generic
    boot

Après cela, vous devriez vous retrouver dans votre instance OS normale, faites simplement sudo en root à nouveau, et répétez le grub-install et update-grub comme expliqué ci-dessus.

Vous pouvez également forcer la création du fichier grub.cfg sur Ubuntu avec la commande suivante :

grub-mkconfig -o /boot/grub/grub.cfg

Ubuntu 16.04

Ceci est pour Ubuntu 16.04. C’est similaire, pratiquement identique, mais je l’ai modifié pour correspondre au flux de travail du mode « Rescue » disponible depuis l’image ISO de démarrage standard 16.04. Le mode « Rescue » vous place en chroot, j’ai donc dû modifier les chemins et supprimer quelques étapes qui ne sont pas nécessaires.

# boot your Gen 1 VM
# note: all steps done as root, so sudo su first
    sudo su

# install grub efi version for later use, just in case; note: it will remove other version on install
    apt-get install -y grub-efi
# backup current boot files
# make /boot2 folder and copy everything from /boot to /boot2 (for backup, safe keeping, later use)
    mkdir -p /boot2
    cp -r /boot/* /boot2

# delete old VM in Hyper-V Manager, but keep the VHDX file(s) (also, remember to export/backup before trying this all)
# create new Gen2 VM with same settings, and attach existing VHDX file(s)
# Add DVD drive and make it first device, attach same ISO image you used to install this OS
# boot ISO while in Gen2/EFI VM, and in grub pick "Rescue" option, then follow the questions
# when it asks, pick a correct root filesystem (something like /dev/ubuntu-vg/root if you have LVM
# it will ask to mount /boot ; skip that
# once you are in shell you have "#" at bottom of screen, start bash to make your workflow easier
    bash

# Prepare partitions and mounts
# if you mounted /boot just unmount it again
    umount /boot
# check which partition was your boot
    fdisk -l
    cat /etc/fstab
# format old boot partition to FAT
    mkfs -t vfat /dev/sda1
# mount boot back
    mount /dev/sda1 /boot/

# copy files from old (BIOS) /boot2 backup, one you made before formatting
# copy backup files back to /boot
    cp -r /boot2/* /boot/
# install EFI grub if you did not earlier, otherwise it should be available since you are effectively in chroot of your original OS installation; you may need to setup /etc/resolv.conf temporarily
#    apt-get install -y grub-efi
    grub-install --force --target=x86_64-efi --boot-directory=/boot --efi-directory=/boot /dev/sda
# should reply:     - No error reported
# edit fstab
    nano /mnt/root/etc/fstab
# change UUIDs to what says in comments above them like "was on .... during installation".. so use that "....", for example
# also /boot needs to be changed from ext2/ext4/whatever to "vfat", and added umask, so like this
    /dev/mapper/ubuntu--vg-root / ext4 errors=remount-ro 0 1
    /dev/sda1 /boot vfat umask=0077 0 2
# keep other entries (eg swap) as is, or if you know what you're doing change them in similar way, or find new UUIDs, etc.

# now we can shut down VM, unmount DVD/ISO, and get it ready for normal boot
    exit / exit / poweroff
# eject media + enter
# turn off / shut down VM

# start again by doing: Connect, Start

# you may get "press any key to continue" .. just press any key

# after successful reboot, install and update grub, to have correct and fresh system with current mounts etc
# if you had to manually fix boot, first fix whatever was wrong (like fstab, or whatever), then do this
    sudo su
    grub-install /dev/sda --efi-directory=/boot
    update-grub
    reboot

Lors d’une future mise à jour du noyau, vous pourriez être invité par l’installateur grub à choisir si vous souhaitez conserver votre configuration ou quelques autres options. Choisissez la première - installer la version du « mainteneur du paquet » (en supposant que vous n’avez pas fait de modifications manuelles à grub.cfg, ce qui serait inhabituel pour une VM serveur). Puisque Ubuntu est le mainteneur du paquet, il devrait définir tous les « paramètres par défaut sûrs » correctement pour vous.

Si vous êtes bloqué, consultez la procédure Ubuntu 20.04 et les conseils à la fin.

CentOS 7

Ensuite, nous faisons les étapes CentOS 7, c’est assez similaire, veuillez donc lire d’abord les instructions Ubuntu 20.04 pour comprendre l’idée générale et les avertissements.

# as with Ubuntu, create Gen1 VM, with default settings, or use one you already have, just make sure to backup/export VM to prevent any data loss

# boot your Gen 1 VM
# again we either do this as root or sudo into root
    sudo su

# while still in Gen1, install the following in your OS
    yum install -y grub2-efi
    yum install -y grub2-efi-modules
    yum install -y efibootmgr
# following are optional, but won't hurt, and can be handy later
    yum install -y shim
    yum install -y dosfstools
    yum install -y nano

# backup content of /boot to temporary /boot2 folder
    mkdir -p /boot2
    cp -r /boot/* /boot2/
    ll /boot2/
# then shut down and export/backup your VM if you haven't already
    poweroff

# after export/backup, again remove your Gen1 VM, but keep VHDX file(s)
# then recreate it as new VM with Gen2 setup, and with DVD with installer ISO attached, boot to ISO

# once booted, pick "Troubleshooting" then "Rescue a CentOS system"
# wizard/guide will ask you something, pick "1" to "Continue"
# this will mount your current OS
# once you are in shell, start bash to make your workflow easier
bash

# Prepare partitions and mounts
# check for your old boot partition
    fdisk -l /dev/sda*
# format old boot partition, make sure you change to sdXn for your real situation!
    umount /dev/sda1
    mkfs -t vfat /dev/sda1
# chroot to your real OS instance; didn't have to do this in Ubuntu, couldn't find a way around it
# as in CentOS rescue mode yum was non operational (in my testing)
    chroot /mnt/sysimage
# mount the boot partition
    mount /dev/sda1 /boot
# no need to mount root as it was already mounted at /mnt/sysimage/ by Rescue guide/wizard

# copy files from old (BIOS) /boot2 backup, one you made before formatting, to /boot
    cp -r /boot2/* /boot/
# install EFI grub; if you get errors then you didn't install packages with yum as instructed earlier
    grub2-install --force --target=x86_64-efi --boot-directory=/boot --efi-directory=/boot /dev/sda
        # should output : No error reported
# you HAVE TO regenerate grub config after reinstall, or it won't pick up everything
    grub2-mkconfig -o /etc/grub2.cfg
# edit fstab
    vi /etc/fstab
        # OR if you installed  optional packages
    nano /etc/fstab
# updated fstab content is something like this
    /dev/mapper/centos-root / xfs defaults 0 0
    /dev/sda1 /boot vfat umask=0077 0 0
#   /swap... keep as is ; same with other partitions if you have them
# instructions for vim:
#    i to edit ; esc to end editing mode ; :x to save ; :q to quit ; :q! to quit without changes
# exit chroot environment
    exit
# then shut down VM
    poweroff
# eject media
# turn off, then you can start it again
#    Connect, Start

# while booting it should provide grub menu, let it boot, then it will (re)boot again, let it do it again to get to normal login prompt, this is expected because SELinux is doing some conversion on first boot and seems to need a reboot after that!

# after reboot, install and update grub, to have correct and fresh system with current mounts etc
# if you had to manually fix boot, first fix whatever was wrong (like fstab, or whatever), then do this
grub2-install /dev/sda --efi-directory=/boot
grub2-mkconfig -o /etc/grub2.cfg
reboot

Cela devrait vous donner une VM CentOS 7 Gen2 / EFI fonctionnelle. Comme avec Ubuntu, j’ai fait une mise à jour du noyau après cette procédure, et bien que j’aie dû exécuter manuellement la commande grub2-mkconfig, tout le reste a bien fonctionné, et au redémarrage j’ai pu choisir une nouvelle entrée dans grub et démarrer correctement sur le nouveau noyau.

Encore une fois, si quelque chose a mal tourné lors de votre première tentative, ne vous inquiétez pas, vous pouvez corriger en faisant quelque chose comme ceci :

    # if you reboot to grub rescue prompt, you can still fix everything, no need to return to original export/backup files !
    # enter these commands
    # try this first
        configfile (hd0,msdos1)/grub2/grub.cfg

    # if above didn't start proper boot, try manually like this, just enter your current kernel version, use tab to autocomplete
        set root=(hd0,msdos1)
        linux /vmlinux-(hit the Tab)
        linux /vmlinuz-(your.version) ro root=/dev/mapper/centos-root
        initrd /initramfs-(your.version).img
        boot
    # if needed repeat this 2 times until you get to normal login prompt because of SELinux is doing some conversion on first boot!

Après cela, vous devriez vous retrouver dans votre instance OS normale, faites simplement sudo en root à nouveau, et répétez le grub2-install et grub2-mkconfig comme expliqué ci-dessus.

Conclusion

Je suppose que certaines parties pourraient être mieux faites/différemment, car j’ai trouvé beaucoup de variations sur le sujet, comme on peut le voir entre Ubuntu et CentOS déjà..

Si quelqu’un trouve une manière encore meilleure, faites-le moi savoir dans les commentaires ci-dessous. J’ai tout un environnement de serveurs de production de VM Ubuntu/CentOS/Debian assorties à convertir de Gen1 à Gen2 en 2021, donc tout ajout est le bienvenu !

Quelques liens que j’ai utilisés dans mes recherches :

https://unix.stackexchange.com/questions/418401/grub-error-you-need-to-load-kernel-first

https://help.ubuntu.com/community/Installation/UEFI-and-BIOS/stable-alternative#Create_boot-loading_systems_for_external_drives

How do I convert my linux disk from MBR to GPT with UEFI?

https://askubuntu.com/questions/831216/how-can-i-reinstall-grub-to-the-efi-partition/1203713#1203713

https://unix.stackexchange.com/questions/152222/equivalent-of-update-grub-for-rhel-fedora-centos-systems