Créer une VM Linux dans Windows 10 Pro avec Hyper-V, le tout automatisé avec Vagrant

Objectif

On souhaite créer une VM Linux sous Windows 10 Pro. On va donc passer directement par l’outil Hyper-V (fourni avec Windows 10 Pro), et installer une VM Ubuntu par exemple. Mais cela impose pas mal de taches manuelles interactives, donc on va essayer de l’automatiser.

Pour cela on va utiliser un outil d’Infrastructure as Code, en l’occurrence Vagrant. D’autres existent comme Terraform, Ansible, Chef, Puppet…

Pourquoi Hyper-V ? En effet parfois on n’a pas la possibilité d’utiliser WSL 2 par exemple, ou ce dernier ne répond pas au besoin. Si on ne dispose pas de Windows 10 Pro et Hyper-V, on pourrait aussi simplement utiliser VirtualBox, compatible avec Vagrant.

Pour information, Vagrant est plutôt destiné à des environnement hors production, comme pour du développement ou des tests.

Installer Vagrant

Tout d’abord il faudra installer Vagrant pour votre OS, et en l’occurrence, pour Windows dans notre cas.

Activer Hyper-V

Bien sûr il faut s’assurer que Hyper-V est activé dans Windows. On pourra utiliser la commande suivante avec PowerShell :

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V -All

Sinon on peut aussi l’activer via le menu Programmes et fonctionnalités, comme suit :

Fichier Vagrantfile

Le fichier Vagrantfile va permettre de décrire en lignes de code la machine que l’on veut créer, en essayant de garder une certaine portabilité entre les différentes plateformes.

On trouvera notamment le paramètre config.vm.box, indiquant à partir de quelle box ou image on veut créer notre VM. Un catalogue de box est disponible ici : https://app.vagrantup.com/boxes/search.

Dans notre cas, on va choisir generic/ubuntu2004, qui est compatible Hyper-V.

Exemple de script Vagrantfile :

# -*- mode: ruby -*-
# vi: set ft=ruby :
# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
# The most common configuration options are documented and commented below.
# For a complete reference, please see the online documentation at
# https://docs.vagrantup.com.
# Every Vagrant development environment requires a box. You can search for
# boxes at https://vagrantcloud.com/search.
#config.vm.box = "base"
#config.vm.box = "generic/debian10"
#config.vm.box = "hashicorp/bionic64"
config.vm.box = "generic/ubuntu2004"
# Disable automatic box update checking. If you disable this, then
# boxes will only be checked for updates when the user runs
# `vagrant box outdated`. This is not recommended.
# config.vm.box_check_update = false
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine. In the example below,
# accessing "localhost:8080" will access port 80 on the guest machine.
# NOTE: This will enable public access to the opened port
# config.vm.network "forwarded_port", guest: 80, host: 8080
# Create a forwarded port mapping which allows access to a specific port
# within the machine from a port on the host machine and only allow access
# via 127.0.0.1 to disable public access
# config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"
# Create a private network, which allows host-only access to the machine
# using a specific IP.
# config.vm.network "private_network", ip: "192.168.33.10"
# Create a public network, which generally matched to bridged network.
# Bridged networks make the machine appear as another physical device on
# your network.
# config.vm.network "public_network"
# Share an additional folder to the guest VM. The first argument is
# the path on the host to the actual folder. The second argument is
# the path on the guest to mount the folder. And the optional third
# argument is a set of non-required options.
# config.vm.synced_folder "../data", "/vagrant_data"
config.vm.synced_folder "../data-test", "/vagrant_data"
# Provider-specific configuration so you can fine-tune various
# backing providers for Vagrant. These expose provider-specific options.
# Example for VirtualBox:
#
# View the documentation for the provider you are using for more
# information on available options.
# https://www.vagrantup.com/docs/providers/hyperv
config.vm.provider "hyperv" do |hv|
hv.cpus = "2"
hv.memory = "2048"
hv.enable_enhanced_session_mode = true
end
# https://www.vagrantup.com/docs/providers/virtualbox
config.vm.provider "virtualbox" do |vb|
vb.cpus = "2"
vb.memory = "2048"
end
# Enable provisioning with a shell script. Additional provisioners such as
# Ansible, Chef, Docker, Puppet and Salt are also available. Please see the
# documentation for more information about their specific syntax and use.
config.vm.provision "shell", inline: <<-SHELL
add-apt-repository ppa:git-core/ppa -y
apt-get update
apt-get install -y git git-svn svn2git
SHELL
end
view raw Vagrantfile hosted with ❤ by GitHub

Partage de fichiers

Cela pourra être pratique de mettre en place un partage de fichier entre l’hôte et la VM invitée, bien que ce ne soit pas obligatoire. C’est l’objet de la propriété :

config.vm.synced_folder "../data-test", "/vagrant_data"

Dans ce cas il faudra s’authentifier pour mettre en place le partage SMB.

Une fois dans la VM, on pourra voir ce dossier partagé dans la liste des mounts, et accéder au chemin /vagrant_data.

Exécution du script

On va maintenant demander à Vagrant de créer une VM correspondant au Vagrantfile. Pour ce faire, se placer dans le répertoire contenant le fichier Vagrantfile et lancer :

vagrant up --provider hyperv

Attention, si on ne spécifie pas le provider, par défaut Vagrant va essayer de créer une VM avec VirtualBox. Voir : https://www.vagrantup.com/docs/providers/default.

Lister les box Vagrant

Si la VM a bien été créée, une box a normalement été téléchargée. On peut vérifier çà avec cette commande :

vagrant box list

Vérification

On peut vérifier le statut de la VM (running si tout va bien) avec la commande suivante :

vagrant status

Il existe une commande globale pour lister toutes les VMs, que l’on peut exécuter de n’importe quel endroit :

vagrant global-status

Accéder à la VM

Il est maintenant possible d’accéder à la VM via SSH. Vous pouvez par exemple utiliser PuTTY. Vagrant propose aussi une commande pour cela :

vagrant ssh

A la création de la VM, Vagrant a créé une configuration SSH. On peut consulter ces infos (adresse IP, username, clé privée) avec la commande :

vagrant ssh-config

Arrêter la VM

On peut suspendre la VM avec la commande :

vagrant suspend

Détruire la VM

Si vous n’en avez plus besoin, vous pouvez aussi supprimer une VM :

vagrant destroy

Besoin de configurer un proxy ?

Allez voir cette réponse à la question How to use vagrant in a proxy environment?

C’est le plugin vagrant-proxyconf qui sera utilisé dans ce cas, et qui devra auparavant avoir été installé comme suit :

vagrant plugin install vagrant-proxyconf

Il faudra simplement penser à définir les variables d’environnement VAGRANT_HTTP_PROXY, VAGRANT_HTTPS_PROXY, voire VAGRANT_NO_PROXY. Comme précisé dans la réponse plus haut, les variables http_proxy et https_proxy sont nécessaires pour pouvoir télécharger la box sur internet.

La bonne nouvelle c’est que ce plugin permet non seulement de télécharger la box Vagrant nécessaire pour initialiser la VM, mais aussi de configurer le proxy de différents programmes.

Par exemple pour Apt c’est ce plugin qui va configurer le fichier /etc/apt/apt.conf.d/01proxy. Donc plus besoin de suivre cette manip : Configure proxy for APT.

Références externes