haiku code

Rails dev environment with Vagrant and Berkshelf

December 28, 2013

Finally, after months of telling myself “I really should’ve been doing that by now” I switched to a VM-based local development environments. Now, every time I need to work on a project I just spin up a VM containing the whole setup and run the development server there, instead of polluting my everyday system and fighting dependency hell every time I switch projects using different database versions.

My configuration is based on Vagrant, chef-solo and Berkshelf. Here’s a simple Vagrantfile along with explanations what, how, and why.

# Berksfile
site :opscode

cookbook 'apt'
cookbook 'locale'
cookbook 'mysql'

# Vagrantfile
require 'berkshelf/vagrant'


Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

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

  # Use Berksfile
  config.berkshelf.enabled = true

  # 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.add_recipe 'apt'
    chef.add_recipe 'locale'
    chef.add_recipe 'mysql::client'

    chef.json = {
      'mysql' => {
        'client' => {'packages' => ['mysql-client', 'libmysqlclient-dev','ruby-mysql']}
      'locale' => {'lang' => 'en_US.utf8'}

What does it do? It creates a simple VM based off Ubuntu 12.04.3 LTS (Precise Pangolin). Then it refreshes apt, configures locale and installs just enough MySQL stuff so that mysql2 gem installs correctly.

How does it do it? First, it creates the bare box based on precise32. Then, it downloads all the cookbooks that you’re going to use. Finally, it uses chef to run specific recipes out of those cookbooks. The configuration attributes for those recipes are hel in the JSON hash.

Why Vagrant? Because I want to be able to control the VM boxes from command line interface.

Why Chef? Because we don’t want to start with a bare Ubuntu box. Keeping all the server environment in chef allows us to easily destroy and recreate boxes, share the configuration with the rest of the team increasing the productivity in the long run.

Why Berkshelf? Because it takes care of downloading and updating the cookbooks. Otherwise I’d have to keep them in my application repo and update them myself, instead of relying on Berkshelf to handle that busywork.

Of course, such a simple Vagrantfile’s not that useful. That’s why more posts are coming on installing typical parts of a Rails dev stack using Vagrant. Stay tuned.

Written by Wojciech Ogrodowczyk who takes photos, climbs mountains, and runs Brains & Beards to help companies deliver better mobile applications faster.

© 2012 - 2024, built in a 🚐 with Gatsby and ☀️