2 min read

Configuring Vagrant Virtual Machines With .env

If you share your Vagrantfile and Vagrant provisioning files amongst team members for your local development environment it’s nice to be able to keep some of the options in your Vagrantfile flexible. Settings like memory usage, shared folder locations, and IP addresses. There’s a Vagrant plugin that allows you to do this and it’s really simple to setup.

Install the plugin:

vagrant plugin install vagrant-env

Now that you have the plugin installed it just needs to be enabled so you can use it in your Vagrantfile:

Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.env.enable # Enable vagrant-env(.env)
end

With config.env.enable added whenever we run a Vagrant command it’ll load .env into ENV which will allow the customizations that we’re looking for.

Within our Vagrantfile we’ll go ahead and configure a search virtual machine so that we have a local search server running. Typically we’d have another provisioning section here with Ansible(or some other provisioner) to configure everything properly as well for your local development environment.

The default memory allocation is a bit low with Vagrant/Virtualbox and on a newer machine it’s nice to be able to bump it up a bit. Add a configuration value to a new .env file in this directory:

SEARCH_MEMORY=1024

Now we can create the virtual machine with our .env configured memory value:

Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.env.enable # Enable vagrant-env(.env)

  config.vm.define "search" do |search|
    search.vm.provider "virtualbox" do |vb|
      vb.memory = ENV['SEARCH_MEMORY']
    end
  end
end

A big customization that usually varies from machine to machine is the location of the shared folder that you need to import into Virtualbox. Add an additional setting to .env so that it now contains:

SEARCH_MEMORY=1024
SRC_HOME=~/src

Some users may have this in ~/workspace or ~/web, doesn’t matter since we’ll be loading it from their own configuration anyways. Vagrant automatically symlinks the current directory that it’s running from as /home/vagrant on the virtual machine so with this synced folder it’ll place it in the src directory.

Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  config.env.enable # Enable vagrant-env(.env)

  config.vm.define "search" do |search|
    search.vm.provider "virtualbox" do |vb|
      vb.memory = ENV['SEARCH_MEMORY']
    end

    search.vm.synced_folder ENV['SRC_HOME'], "/home/vagrant/src"
  end
end

As more virtual machines and other settings get added there’s various other customizations that make sense to extract out so that team members can modify as needed. Copy the current .env over as .env.example so that new team members can utilize the example .env file to get going and customize from there.