This post is on how to use vagrant to spin up a virtual machine and provision it.

Why Use Vagrant?

Vagrant gives you the tools to build unique development environments for each project once and then easily tear them down and rebuild them only when they’re needed so you can save time and frustration. Why?

How?

Vagrant allows you to configure a virtual machine using a text file called the Vagrantfile. This configuration file lets you specify things like the operating system to use, any ports that you want to forward and the cookbook or manifest to use to provision your server.

Vagrant runs on VirtualBox to run virtual machines.

Here’s an example of the Vagrant file for the rails-dev-box.

Vagrant::Config.run do |config|
    config.vm.box       = 'precise32'
    config.vm.box_url   = 'http://files.vagrantup.com/precise32.box'
    config.vm.host_name = 'rails-dev-box'

    config.vm.forward_port 3000, 3000

    config.vm.provision :puppet,
      :manifests_path => 'puppet/manifests',
      :module_path    => 'puppet/modules'
  end

You’ll see that the operating system is Ubuntu 12.04 Precise Pangolin. The base image for the box can be downloaded from http://files.vagrantup.com/precise32.box’, the host name for the new vm is ‘rails-dev-box’ and port 3000 on the host machine is port-forwarded to port 3000 and the vm. This allows you to go to http://localhost:3000/ on your host machine and connect to port 3000 on your VM.

This is incredibly powerful for bring new team members up to speed in a short amount of time. Rather then having to manually configure a new development box and remember to install a specific version of a database and web server you can version control a recipe for bootstrapping a development machine quickly and easily without having to polute your host machine.

Commandline Interface

Vagrant has a command line interface. To interact with Vagrant you can issue a set of commands to interact with your virtual machine.

$ gem install vagrant   # install the vagrant gem
  $ vagrant box add lucid32 http://files.vagrantup.com/lucid32.box # add the lucid32 box to your local cache of vagrant base images
  $ vagrant init lucid32  # create a new Vagrantfile initialized for the lucid32 base image
  $ vagrant up            # start the vagrant virtual machine
  $ vagrant ssh           # ssh into the vagrant vm
  $ vagrant suspend       # save the current running state of the vm and stop it
  $ vagrant resume        # resume a suspended vm
  $ vagrant halt          # shutdown the vm
  $ vagrant destroy       # delete the virtual machine (not the base image)

vagrant ssh

When you ssh into your vagrant vm you will find a folder called /vagrant. This is virtual box shared folder that shares the files from your host machine. You can then work on your host machine, editing source files and saving them and running an app from within your vm.

comments powered by Disqus