Quantcast
Channel: vidasConcurrentes » Programación
Viewing all articles
Browse latest Browse all 11

Automatizando la creación de entornos de desarrollo con Vagrant

$
0
0

¿Toc toc, hay alguien ahí?

VagrantSe que esto lleva demasiado tiempo abandonado, pero hoy me veía con ganas de hablar sobre una herramienta que he descubierto hace poco.

Vagrant es una herramienta open-source desarrollada por Mitchell Hashimoto y John Bender destinada a la creación y configuración de entornos de desarrollo virtuales. Podemos considerar que Vagrant aporta una capa por encima del software de virtualización que utilicemos (VMWare, VirtualBox, HyperV…).

Además, Vagrant es realmente sencillo de utilizar, y es capaz de replicar exactamente el mismo entorno de trabajo en cualquier máquina (que posea un software de virtualización y el propio Vagrant instalado). Esto, que podría parecer banal, adquiere mucha importancia en el desarrollo de software. ¿Quién no ha oido eso de…no, si en mi ordenador funcionaba bien?.

Antes de empezar a utilizar Vagrant, hemos de estar seguros que poseemos un software de virtualización instalado. En este tutorial se va a utilizar Virtual Box por ser gratuito. Los binarios de Vagrant se pueden encontrar aquí. No es el objetivo de este blog guiar a través de la instalación de Vagrant, ya que es sumamente facil (Siguiente, Siguiente, Finalizar).

(Añadir que tras la instalación, es necesario agregar la ruta de los binarios de Vagrant a la variable de entorno PATH para poder ejecutarlo desde linea de comandos)

Empezamos!

El objetivo de este tutorial es documentar la creación de un LAMP server bajo Ubuntu 12.04 Precise Pangolin.

Antes de nada, vamos a crear una carpeta, donde se alojarán las configuraciones de Vagrant. En mi caso tiene el nombre de ‘vagrant_vc’, pero vosotros podeis ponerle el nombre que gusteis.

Una vez creada la carpeta, podemos inicializar nuestra VM con el comando ´vagrant init´.

Creando el directorio

Esto nos creará un archivo con nombre ‘Vagrantfile’ en el directorio, que será la configuración para la VM. Si miramos dicho archivo nos encontraremos algo así:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # All Vagrant configuration is done here. The most common configuration
  # options are documented and commented below. For a complete reference,
  # please see the online documentation at vagrantup.com.

  # Every Vagrant virtual environment requires a box to build off of.
  config.vm.box = "base"

  # 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.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # 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"

  # If true, then any SSH connections made will enable agent forwarding.
  # Default value: false
  # config.ssh.forward_agent = true

  # 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"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Don't boot with headless mode
  #   vb.gui = true
  #
  #   # Use VBoxManage to customize the VM. For example to change memory:
  #   vb.customize ["modifyvm", :id, "--memory", "1024"]
  # end
  #
  # View the documentation for the provider you're using for more
  # information on available options.

  # Enable provisioning with CFEngine. CFEngine Community packages are
  # automatically installed. For example, configure the host as a
  # policy server and optionally a policy file to run:
  #
  # config.vm.provision "cfengine" do |cf|
  #   cf.am_policy_hub = true
  #   # cf.run_file = "motd.cf"
  # end
  #
  # You can also configure and bootstrap a client to an existing
  # policy server:
  #
  # config.vm.provision "cfengine" do |cf|
  #   cf.policy_server_address = "10.0.2.15"
  # end

  # Enable provisioning with Puppet stand alone.  Puppet manifests
  # are contained in a directory path relative to this Vagrantfile.
  # You will need to create the manifests directory and a manifest in
  # the file default.pp in the manifests_path directory.
  #
  # config.vm.provision "puppet" do |puppet|
  #   puppet.manifests_path = "manifests"
  #   puppet.manifest_file  = "site.pp"
  # end

  # Enable provisioning with chef solo, specifying a cookbooks path, roles
  # path, and data_bags path (all relative to this Vagrantfile), and adding
  # some recipes and/or roles.
  #
  # config.vm.provision "chef_solo" do |chef|
  #   chef.cookbooks_path = "../my-recipes/cookbooks"
  #   chef.roles_path = "../my-recipes/roles"
  #   chef.data_bags_path = "../my-recipes/data_bags"
  #   chef.add_recipe "mysql"
  #   chef.add_role "web"
  #
  #   # You may also specify custom JSON attributes:
  #   chef.json = { mysql_password: "foo" }
  # end

  # Enable provisioning with chef server, specifying the chef server URL,
  # and the path to the validation key (relative to this Vagrantfile).
  #
  # The Opscode Platform uses HTTPS. Substitute your organization for
  # ORGNAME in the URL and validation key.
  #
  # If you have your own Chef Server, use the appropriate URL, which may be
  # HTTP instead of HTTPS depending on your configuration. Also change the
  # validation key to validation.pem.
  #
  # config.vm.provision "chef_client" do |chef|
  #   chef.chef_server_url = "https://api.opscode.com/organizations/ORGNAME"
  #   chef.validation_key_path = "ORGNAME-validator.pem"
  # end
  #
  # If you're using the Opscode platform, your validator client is
  # ORGNAME-validator, replacing ORGNAME with your organization name.
  #
  # If you have your own Chef Server, the default validation client name is
  # chef-validator, unless you changed the configuration.
  #
  #   chef.validation_client_name  = "ORGNAME-validator"
end

Ahora mismo no vamos a hacerle demasiado caso a este archivo, pero volveremos sobre el más adelante.

Agregando boxes

Vagrant está basado en ´boxes´, esto es una especie de máquinas virtuales prefabricadas que podemos elegir para nuestro proyecto. Puedes descubrir la variedad de boxes que hay en vagrantbox.es y vagrantcloud.com.

Para agregar una box hay dos maneras de hacerlo, que dependen de dónde esté alojada la box:

    1. Si está alojada en vagrantcloud.com, es tan simple como apuntar el nombre que le dan a la box (en este caso ´hashicorp/precise64´) y ejecutar el comando:
vagrant box add hashicorp/precise64

Instalando box

    1. En caso de que esté alojada en vagrantbox.es, es necesario apuntar la url y ejecutar el siguiente comando:
vagrant box add {Nombre que queramos} {url}

Mientras se instala la box, en caso de que esta esté disponible para varios entornos de virtualización, nos dejará elegir cual es el nuestro (como se puede apreciar en la imagen anterior).

Una vez instalada, nos devolverá al prompt y podemos seguir configurando la VM.

Box instalada

Vagrantfile

En este archivo se especificará la configuración de la VM. Tanto el nombre, la box…hasta redirección de puertos, provisionamiento después de la instalación, e incluso configuraciones asociadas al software de virtualización sobre el que vayamos a correr nuestra VM.

Vamos a echar un vistazo al Vagrantfile de este tutorial:

# -*- mode: ruby -*-
# vi: set ft=ruby :

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  # base box
  config.vm.box = "hashicorp/precise64"

  # port forwarding
  config.vm.network :forwarded_port, guest: 80, host: 3000

  # provision after box setup
  config.vm.provision :shell, :path => "setup_env/init.sh"

  # shared folder between host and guest
  config.vm.synced_folder "shared_folder/", "/home/vagrant/shared_folder/"

  # provider related settings
  config.vm.provider :virtualbox do |vb|
    # machine name on VirtualBox
    vb.name = "LAMPServer Precise"
    # RAM for VM
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end

end

Vamos a repasar las opciones que se especifican en este archivo de configuración:

config.vm.box = "hashicorp/precise64"

La box que acabamos de descargar y sobre la que se basará el proyecto. Si no la hemos descargado en el paso anterior no ocurre nada, al iniciar la creación de la VM se descargará automáticamente.

config.vm.network :forwarded_port, guest: 80, host: 3000

Esta linea indica que en nuestra VM habrá un redireccionamiento de puertos, desde el 80 en la VM (queremos instalar un server LAMP) hasta el 3000 en el host.

config.vm.provision :shell, :path => "setup_env/init.sh"

Aquí se indica tanto el tipo de provisionamiento tras la instalación de la VM (shell script) como la ruta donde está alojado. En este tutorial hemos usado un shell script para esta tarea, sin embargo Vagrant también soporta herramientas más especializadas como Puppet o Chef.

config.vm.synced_folder "shared_folder/", "/home/vagrant/shared_folder/"

Al igual que en VirtualBox, podemos configurar las carpetas compartidas que queramos entre el host y el guest. En este caso compartirán unicamente una carpeta llamada shared_folder, que estará en el home del usuario vagrant. Es necesario que creemos dicha carpeta en el host antes de ejecutar la inicialización de la VM.

config.vm.provider :virtualbox do |vb|
    # machine name on VirtualBox
    vb.name = "LAMPServer Precise"
    # RAM for VM
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end

Por último en este bloque se especifican opciones propias de VirtualBox, como pueden ser el nombre de la VM y la cantidad de memoria RAM máxima que puede utilizar.

Al turrón

Una vez configurado nuestro Vagrantfile, y creada(s) la(s) carpeta(s) compartida(s) toca la creación de la VM. Es tan simple como teclear el comando ´vagrant up´ dentro del directorio donde tengamos el Vagrantfile.

vagrant up

Después de unos minutos, una vez se haya instalado la VM y ejecutado el script que instalará el stack LAMP, si abrimos VirtualBox comprobaremos que hay una VM nueva:

vagrant up finalizado

Nueva VM en VirtualBox

Para conectarnos a la VM podemos simplemente escribir ´vagrant ssh´ y ya estaremos conectados por SSH.

vagrant ssh

Ahora, a modo de prueba vamos a crear un archivo de texto (desde la VM) y efectivamente comprobar que la carpeta compartida funciona correctamente:

Comprobación de carpetas compartidas I

Comprobación de carpetas compartidas II

Por último, si accedemos en nuestro navegador a localhost:3000 (este puerto es el que se ha especificado previamente en el Vagrantfile para el host) comprobaremos que nuestro servidor apache ya está en funcionamiento.

Servidor Apache en marcha

Por último, y no mas importante, una vez que hayamos acabado de trabajar con nuestra VM, con el comando ´vagrant halt´ apagaremos la VM.

vagrant halt

Ahora, la próxima vez que queramos ejecutar nuestra VM simplemente tenemos que abrir una consola y teclear:

vagrant up

Otros comandos útiles pueden ser:

vagrant suspend
vagrant destroy -> borrar vm
vagrant reload

Viewing all articles
Browse latest Browse all 11

Latest Images





Latest Images