Dans cette série consacrée à Vagrant, nous avons déjà utilisé des boxes préconfigurées téléchargées depuis Vagrant Cloud. Vous pouvez aussi créer votre propre box, la personnaliser et la partager.
Deux méthodes existent : construire une box depuis zéro avec un hyperviseur, ou télécharger une box existante, la personnaliser puis la repackager. Cette seconde approche est plus rapide.
Créer une nouvelle box Vagrant
1. Choisissez une box de base, par exemple ubuntu/focal64.
$ mkdir ubuntu $ cd ubuntu $ vagrant init -m "ubuntu/focal64"
2. Démarrez la machine virtuelle.
$ vagrant up
3. Connectez-vous à la VM.
$ vagrant ssh
Si nécessaire, activez l’authentification par mot de passe :
$ sudo sed -i "/^[^#]*PasswordAuthentication[[:space:]]no/c\PasswordAuthentication yes" /etc/ssh/sshd_config $ sudo service sshd restart
4. Installez PostgreSQL dans la VM.
$ sudo sh -c 'echo "deb https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list' $ wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add - $ sudo apt-get update $ sudo apt-get -y install postgresql
Vérifiez l’installation :
$ sudo su - postgres $ psql
5. Avant de repackager, compressez l’espace disque :
$ sudo dd if=/dev/zero of=/EMPTY bs=1M $ sudo rm -f /EMPTY
Repackager la box
6. Créez la nouvelle box :
$ vagrant package --output ubuntu_repacked.box
7. Ajoutez la box à Vagrant :
$ vagrant box add repacked ubuntu_repacked.box
8. Utilisez-la dans un nouveau projet :
$ mkdir repacked $ cd repacked $ vagrant init -m "repacked" $ vagrant up
Connectez-vous et vérifiez PostgreSQL :
$ vagrant ssh $ sudo su - postgres $ psql
Vous savez maintenant créer une box Vagrant personnalisée à partir d’une box existante.