Getting Started with Vagrant

Last post, I show you how to install VirtualBox on Ubuntu 12.04. Today, I’ll show you how to improve your capabilities to manage VMs by using an awesome tool. Yes, I’m speaking about Vagrant.

What’s Vagrant ?

Vagrant is an open source tool for managing virtual machines (VMs) developed by Mitchell Hashimoto and John Bender. A virtual machine is a full implementation of a computer with a virtual disk, memory and CPU. A Box, or base image, is the pre-packaged virtual machine that Vagrant will manage.

Vagrant is a CLI tool. Calling vagrant without additional arguments will provide the list of available commands:

  • init — create the base configuration file.
  • up — start a new instance of the virtual machine.
  • suspend — suspend the running guest.
  • halt — stop the running guest, similar to hitting the power button on a real machine.
  • resume — restart the suspended guest.
  • reload — reboot the guest.
  • status — determine the status of vagrant for the current Vagrantfile.
  • provision — run the provisioning commands.
  • destroy — remove the current instance of the guest, delete the virtual disk and associated files.
  • box — the set of commands used to add, list, remove or repackage box files.
  • package — used for the creation of new box files.
  • sshssh to a running guest.

Install it

This is so easy. Go to the Vagrant downloads page and download the latest release version which is v1.7.4 when writing this post. You can download it with the below command:

wget https://dl.bintray.com/mitchellh/vagrant/vagrant_1.7.4_x86_64.deb

Next install it with the following command:

dpkg -i vagrant_1.7.4_x86_64.deb

Great ! Now you have vagrant installed on your machine. You can test it by adding boxes, creating a new box, etc.

Your first Vagrant project

Download the precise Ubuntu 12.04 vagrant box

vagrant box add precise64 http://files.vagrantup.com/precise64.box # 323MB, faster download

Once it’s downloaded, let’s initialize the new Vagrant project basing on the downloaded box:

mkdir -p ~/vagrant-tutorial/ && cd ~/vagrant-tutorial/
vagrant init precise64 # creates a default Vagrantfile in the current directory

For more details about Vagrantfile, see the official documentation.

Creating VM

Now let’s start up a VM defined by the created Vagrantfile:

vagrant up

The VM is now running. You can ssh into it with the following command:

vagrant ssh

Note that on the new VM, /vagrant is a shared directory mounted to ~/vagrant-tutorial

ls /vagrant

Soon, you’ll start making modifications to the Vagrantfile. There are three ways to rebuild the VM.

# Fastest method: re-runs the provisioner without stopping the VM.
vagrant provision 

# Restarts VM, provisions. Use this if you changed virtualbox settings (e.g shared folders)
vagrant reload 

# Destroys the active VM, and rebuilds.
# Slow, but guarantees stability.
vagrant destroy --force && vagrant up

Thanks for reading !