Basic Developing with Vagrant

If you've been following my posts you'll have noticed that for some posts I have a vagrant environment preprepared. This post discusses how to set up your own vagrant environment and customize it a bit.

Prerequisites:

  • VirtualBox, or other virtualization provider (even cloud providers will work).
  • Vagrant

Windows users please read this.

First, create a directory to store your work:

mkdir ~/project-vagrant

Let's also create a directory to share files with the virtual machine:

mkdir ~/project-vagrant/shared

Next lets create a very minimal vagrant file:

~/project-vagrant/Vagrantfile

VAGRANTFILE_API_VERSION = "2"

config.vm.box = “nrel/CentOS-6.5-x86_64” config.vm.provider “virtualbox” do |v| v.memory = 512 v.cpus = 1 end

config.vm.define “box1” do |box| box.vm.host_name = “box1” box.vm.synced_folder “shared/”, “/shared/” box.vm.network “private_network”, ip: “192.168.250.100” box.vm.network “forwarded_port”, guest: 80, host: 8080 box.vm.provision “shell”, inline: “service iptables stop” box.vm.provision “shell”, inline: “service httpd start” end end

The first line is setting the vagrant api version we want to use. Then the next block is setting the image we want to use to nrel/CentOS-6.5-x86_64. You can get box ids from the here. If you wanted multiple types of boxes you’d add multiple of these blocks.

The first inner block configures the provider and general settings for the boxes created from that image you selected. In this example I am granting cpus and memory allotments.

The second inner block is slightly more complex - I’m defining a virtual machine named box1. In the definition of the box I am setting it’s hostname, creating a shared folder between my system and the virtual machine, setting up an ip address, configuring a port forward (dnat), and executing arbitrary in line commands.

For multiple boxes, you can do this:

VAGRANTFILE_API_VERSION = “2”

config.vm.box = “nrel/CentOS-6.5-x86_64” config.vm.provider “virtualbox” do |v| v.memory = 512 v.cpus = 1 end

config.vm.define “server1” do |box| box.vm.host_name = “server1” box.vm.synced_folder “shared/”, “/shared/” box.vm.network “private_network”, ip: “192.168.250.100” box.vm.network “forwarded_port”, guest: 80, host: 8080 box.vm.provision “shell”, inline: “service iptables stop” box.vm.provision “shell”, inline: “service httpd start” end

(1..3).each do |i| config.vm.define “client-#{i}” do |node| node.vm.network “private_network”, ip: “192.168.250.10{i}” node.vm.provision “shell”, inline: “echo hello from node #{i}” end end end

You can find examples here.