Search code examples
rubyvagrantvagrantfile

Include a directory of config files for a Vagrantfile


I have a Vagrantfile that has the following semi-standard setup:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/focal64"
  config.vm.network :forwarded_port, guest: 80, host: 8080, auto_correct: true
  config.vm.network "private_network", ip: "192.168.56.40"
  config.vm.hostname = "development.local"
  config.vm.boot_timeout = 600

  config.vm.provider "virtualbox" do |v|
    v.name = "development.local"
    v.memory = "1024"
    v.check_guest_additions = true
  end

  config.vm.provision :shell, path: "bootstrap.sh"
end

My aim is to auto include files within a folder that configure the site on vagrant up.

For apache settings, I have managed to create a nice bash script that parses a folder and sets up sites-enabled for all the configs within a folder.

I would like to also share these folders inside the Vagrantfile without having to modify the core, much like apache parses the sites-enabled folder. This would mean I can easily share this box with others, without having to change the Vagrantfile every time I spin up a test environment and want to share a new folder.

The usual syntax is:

config.vm.synced_folder "../some-folder/", "/var/www/some-folder", owner: "www-data"

Using pseudocode, this is what I'm aiming for:

foreach([$files_in_$folder] as $synced_folder) {

    require $synced_folder_config_file;
    // ^ this would be a small config file

}

Note that the advantage of the small config file is that other things could be specified on a per-file bases (such as different owners/permissions etc).

Key things to do:

  • parse over folder contents
  • ensure that this config is executed as part of the vagrant up

I've barely touched ruby, so apologies if this is obvious.

Thanks


Solution

  • After some research and a lot of reprovisions and up/down/destroy:

    Create appropriate files in the /synced-folders/, each consisting of something like:

    config.vm.synced_folder "../development.local/", "/var/www/development.local", owner: "www-data"
    

    Then, in your Vagrantfile:

    Dir[File.dirname(__FILE__) + '/synced-folders/*.rb'].each {|file| eval File.read(file) }
    

    This parses over the directory, and evals them.