Vagrant synced folders using environment variables

Lately, I’ve been working towards automated, reproducible, standardized environments at work and this includes our dev environment. My brother-in-law turned me on to Vagrant so I’ve started evaluating it.

We use a standard set of environment variables to refer to the locations of the source repositories on our machines. We build with Maven. So I decided it might be a smart idea for the /target folder that Maven produces from a build to be shared to the guest VM where it can then be deployed via a script whenever we want.

A normal Vagrantfile synced folder definition looks like this example from the Vagrant documentation:

Vagrant.configure("2") do |config|
  # other config here

  config.vm.synced_folder "src/", "/srv/website"

Instead of “src/”, what I wanted to see there is a reference (for example) to `$MY_PROJECT/target’ (or whatever Bash environment variable I decided).

Unfortunately, nothing on Stack Overflow or a couple of searches across the internet yielded any useful information about how to use our existing environment variables in the Vagrantfile. Most people seemed to want to pass environment variables from the host to the guest.

The answer is: a Vagrantfile is just Ruby so you use the Ruby ENV construct. This looks like:

config.vm.synced_folder ENV['MY_PROJECT'] + "/target", "/workspace/my-project/target"

Hope this helps someone out there, but if it doesn’t, at least I’ll remember it since it’s posted here!

Leave a Reply

Your email address will not be published. Required fields are marked *