Search code examples
vagrantvagrantfileshared-directoryhashicorp

Is it possible to set up a Vagrant sync folder with variable host/source directory, possibly from config file?


I'm trying to set up a Vagrantfile that will mount a code base on the developer's machine. The place the developer puts the codebase on their machine could be anywhere they like based on how they like to organize their machine. If I offer up this Vagrantfile to set up a small development and test environment that closely resembles production, I'd like them to be able to set the location of their code without having to edit the Vagrantfile (leaving it unchanged in source control).

Is there a way to make the Vagrantfile look somewhere else for a value to use as the host directory path for a sync folder?

I tried asking on the HashiCorp forum (might require login) yesterday, but haven't gotten a response yet and it seems like a low traffic site. I'll keep checking there in case a solid answer comes back, but I'm hoping someone here has dealt with this before. Thank you for any help.


Solution

  • You can customize additional synced folders with an additional line of code in the Vagrantfile described here:

    config.vm.synced_folder '<host_path>', '<guest_path>'
    

    This solves the problem of additional customized synced folders. However, you also stated you desired to customize this per user based on a config file. You can accomplish this with basic Ruby. We will assume the config file is YAML like:

    # config.yaml
    ---
    host_path: '/path/on/host'
    guest_path: '/path/on/guest'
    

    Then we can read in the file with normal Ruby and utilize its key-value pairs as per normal. This assumes the file is in the same directory as where vagrant commands are being executed; otherwise the code will need to be customized further:

    require 'yaml'
    
    paths = YAML.load_file('config.yaml')
    config.vm.synced_folder paths['host_path'], paths['guest_path']
    

    The code can also be easily modified for different config file formats.