Dynamic Vagrant Shares

May 14, 2014 by Jon Whitcraft

At SugarCRM, we are deploying Vagrant stacks as part of the DevOps Initiative. How ever we ran into a few problems with defining shares. Since no two engineers work the same or have the same setup we couldn’t define shares that were hard coded in the Vagrantfile. We had to come up with a way to do shares that end user could customize easily. While looking for solutions someone pointed out that the Vagrantfile is just Ruby and we could use YAML to define the shares. The seed had been planted and this is the bit of code we came up with.

Place this bit of code inside the Vagrantfile:

VAGRANTFILE_API_VERSION = '2'
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  #....
  # Start Dynamic Shares
  if File.exists?('share.yaml')
    require 'yaml'
    yaml = YAML.load_file(Dir.pwd + '/share.yaml')
    yaml.each do |share|
      share_group = 'vagrant'
      share_group = 'apache' if share['target'] =~ /www\/html/
      config.vm.synced_folder share['source'], share['target'], create: true, owner: 'vagrant', group: share_group
    end
  end
  # End Dynamic Shares
  #...
end

share.yaml example:

-
  source: '/Users/jwhitcraft/Sites'
  target: '/var/www/html/Sites'
-
  source: '/Users/jwhitcraft/Documents'
  target: '/var/www/html/Docs'

This method allows the user to create a share.yaml next to the Vagrantfile, which it will then be picked up and converted into the config.vm.synced_folder attribute when then vagrant up or vagrant reload command is issued.

Hope this helps others!

© 2017 h2ik | Build With Hugo