lunes, octubre 09, 2023

Creando una instalación de Vagrant con VirtualBox

Vagrant es una herramienta para construir y desplegar máquinas virtuales de manera sencilla y predecible a golpe de línea de comando. Se pueden desplegar de manera realmente rápida series de máquinas con las que crear entornos de desarrollo, laboratorios o servidores de producción sin tener que crear y personalizar a mano cada máquina virtual que creemos. Vamos a mostrar cómo instalar Vagrant y cómo desplegar una serie de máquinas básicas de manera sencilla.

Instalación de Vagrant

Vagrant puede instalarse en MacOS, Windows y Linux. Los binarios para tu sistema operativo pueden encontrarse en https://developer.hashicorp.com/vagrant/downloads.  En nuestro caso lo instalaremos sobre un Windows 11. La instalación es directa y tras ella tendremos que reiniciar el equipo:


Supondremos que VirtualBox está previamente instalado, y si no, es el momento de instalarlo ahora con alguno de los binarios de https://www.virtualbox.org/wiki/Downloads .

Interactuando con Vagrant

Podemos ejecutar comandos de Vagrant desde una ventana de línea de comando (cmd.exe desde Inicio > Ejecutar) o desde PowerShell. Debemos asegurarnos de que tenemos instalado el cliente SSH en Características opcionales de Windows, ya que Vagrant lo usa para acceder a las máquinas virtuales:
 
 
 
Vagrant no funcionará correctamente desde un PowerShell x86, la versión de 32 bits de PowerShell, ya que necesita acceso a SSH y por alguna razón desde esta versión de PowerShell no la hay.

Creando un box

Un box en Vagrant es un entorno con ciertas características que se aplica a la máquina virtual que se corra bajo ese box. Cada box debería crearse en un directorio distinto de nuestro equipo.Hay una gran cantidad de boxes públicos predefinidos que pueden encontrarse en https://app.vagrantup.com/boxes/search . Solo tenemos que invocar uno que se adecúe a nuestras necesidades para tener corriendo en unos minutos. Veamos un ejemplo rápido en el que vamos a desplegar un CentOS 7 pelado bajo VirtualBox:

  • En el buscador elegimos los términos que queremos filtrar para nuestro box. Vemos que existe un box denominado generic/centos7.

 

  • En nuestra línea de comando de Windows vamos a nuestro home (cd $home si no lo tienes claro) y creamos un directorio para nuestro box con el nombre que queramos:

PS C:\Users\foo> cd $home
PS C:\Users\foo> mkdir vagrant_centos7


    Directorio: C:\Users\foo


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        08/10/2023     22:53                vagrant_centos7


  • Entramos al directorio e inicializamos el box con el comando vagrant init <nombre del box>, lo que genera un fichero con todos los parámetros necesarios para la máquina virtual. En nuestro caso:

PS C:\Users\foo> cd .\vagrant_centos7\

PS C:\Users\
foo\vagrant_centos7> vagrant init generic/centos7
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
 
PS C:\Users\foo\vagrant_centos7>ls


    Directorio: C:\Users\
foo\vagrant_centos7


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----        08/10/2023     23:20           3466 Vagrantfile



  • Como indica la salida del comando, podemos levantar la máquina con vagrant up asegurándonos ante de que VirtualBox está corriendo:

PS C:\Users\foo\vagrant_centos7> vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'generic/centos7'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'generic/centos7' version '4.3.2' is up to date...
==> default: Setting the name of the VM: vagrant_centos7_default_1696800250897_88565
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant

    default: SSH auth method: private key
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default:
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default:
    default: Guest Additions Version: 5.2.44
    default: VirtualBox Version: 7.0

Se puede ver cómo se han generado automaticamente los parámetros para la máquina y se ha descargado si era necesario. Si vamos a VirtualBox podemos ver que la máquina está levantada:


Podemos acceder a la máquina desde la propia línea de comando con vagrant ssh, lo que nos pone dentro de la máquina sin tener que abrir ninguna otra interfaz:

PS C:\Users\foo\vagrant_centos7> vagrant ssh
[vagrant@centos7 ~]$

Podemos comprobarlo con uname o cualquier otro comando:

[vagrant@centos7 ~]$ uname
Linux
 
[vagrant@centos7 ~]$ whoami
vagrant

Con exit o logout salimos de la sesión contra la máquina virtual.

Con vagrant halt pararíamos la máquina virtual y con vagrant destroy eliminaríamos completamente la máquina.

Creando boxes multimáquina

Podemos crear un box que arranque varias máquinas a la vez, lo cual es útil si queremos crear un entorno para probar funcionalidades de cliente-servidor, computación distribuida, etc. Para ello tenemos que editar el fichero Vagrantfile que se genera con vagrant init en el directorio que hemos creado y añadir subconfiguraciones para las máquinas que deseemos. Por ejemplo:

 config.vm.define "server1" do |server1|
    server1.vm.box = "generic/centos7"
  end

  config.vm.define "server2" do |server2|
    server2.vm.box = "generic/centos7"
  end

 Ahora al hacer vagrant up se levantarán las dos máquinas (o las que hayamos configurado):

PS C:\Users\foo\vagrant_centos7> vagrant up
Bringing machine 'server1' up with 'virtualbox' provider...
Bringing machine 'server2' up with 'virtualbox' provider...
==> server1: Importing base box 'generic/centos7'...
==> server1: Matching MAC address for NAT networking...
==> server1: Checking if box 'generic/centos7' version '4.3.2' is up to date...
==> server1: Setting the name of the VM: vagrant_centos7_server1_1696803510837_94859
==> server1: Clearing any previously set network interfaces...
==> server1: Preparing network interfaces based on configuration...
    server1: Adapter 1: nat
==> server1: Forwarding ports...
    server1: 22 (guest) => 2222 (host) (adapter 1)
==> server1: Running 'pre-boot' VM customizations...
==> server1: Booting VM...
==> server1: Waiting for machine to boot. This may take a few minutes...
    server1: SSH address: 127.0.0.1:2222
    server1: SSH username: vagrant
    server1: SSH auth method: private key
    server1:
    server1: Vagrant insecure key detected. Vagrant will automatically replace
    server1: this with a newly generated keypair for better security.
    server1:
    server1: Inserting generated public key within guest...
    server1: Removing insecure key from the guest if it's present...
    server1: Key inserted! Disconnecting and reconnecting using new SSH key...
==> server1: Machine booted and ready!
==> server1: Checking for guest additions in VM...
    server1: The guest additions on this VM do not match the installed version of
    server1: VirtualBox! In most cases this is fine, but in rare cases it can
    server1: prevent things such as shared folders from working properly. If you see
    server1: shared folder errors, please make sure the guest additions within the
    server1: virtual machine match the version of VirtualBox you have installed on
    server1: your host and reload your VM.
    server1:
    server1: Guest Additions Version: 5.2.44
    server1: VirtualBox Version: 7.0
==> server2: Importing base box 'generic/centos7'...
==> server2: Matching MAC address for NAT networking...
==> server2: Checking if box 'generic/centos7' version '4.3.2' is up to date...
==> server2: Setting the name of the VM: vagrant_centos7_server2_1696803548664_46540
==> server2: Fixed port collision for 22 => 2222. Now on port 2200.
==> server2: Clearing any previously set network interfaces...
==> server2: Preparing network interfaces based on configuration...
    server2: Adapter 1: nat
==> server2: Forwarding ports...
    server2: 22 (guest) => 2200 (host) (adapter 1)
==> server2: Running 'pre-boot' VM customizations...
==> server2: Booting VM...
==> server2: Waiting for machine to boot. This may take a few minutes...
    server2: SSH address: 127.0.0.1:2200
    server2: SSH username: vagrant
    server2: SSH auth method: private key
    server2:
    server2: Vagrant insecure key detected. Vagrant will automatically replace
    server2: this with a newly generated keypair for better security.
    server2:
    server2: Inserting generated public key within guest...
    server2: Removing insecure key from the guest if it's present...
    server2: Key inserted! Disconnecting and reconnecting using new SSH key...
==> server2: Machine booted and ready!
==> server2: Checking for guest additions in VM...
    server2: The guest additions on this VM do not match the installed version of
    server2: VirtualBox! In most cases this is fine, but in rare cases it can
    server2: prevent things such as shared folders from working properly. If you see
    server2: shared folder errors, please make sure the guest additions within the
    server2: virtual machine match the version of VirtualBox you have installed on
    server2: your host and reload your VM.
    server2:
    server2: Guest Additions Version: 5.2.44
    server2: VirtualBox Version: 7.0

Ahora podemos acceder a ambas máquinas usando vagrant ssh pero especificando al final a qué máquina queremos conectarnos:

PS C:\Users\foo\vagrant_centos7> vagrant ssh server1
Last login: Sun Oct  8 22:38:17 2023 from 10.0.2.2
server1 $exit
logout
Connection to 127.0.0.1 closed.

PS C:\Users\foo\vagrant_centos7> vagrant ssh server2
Last login: Sun Oct  8 22:38:57 2023 from 10.0.2.2
server2 $