Highly Opinionated Thoughts on Programming

by Elnur Abdurrakhimov


Vagrantfile With Customizable Configuration

Apr 1, 2014


Forcing every developer working on a particular project to use the same IP address for the VM is not practical. Some developers may be using that IP address for another project. Others can run into problems with 192.168.0.x addresses.

Also you can run into problems with memory and number of CPUs. Using the defaults with 512MB of RAM and a single CPU makes the VM too slow — especially if you have a very powerful system and are used to things working fast. But setting the Vagrant configuration to, say, 8 CPUs and 8 GB of RAM may not be practical because some developers on the team may be using systems with less real CPUs and RAM.

Instead of trying to find a perfect configuration that will work for everyone on the team, it makes more sense to make the configuration customizable by each developer.

First create Vagrantparams.yml.dist with contents like:

1
2
3
ip: 192.168.0.7
memory: 1024
cpus: 2

Each developer would copy that file to Vagrantparams.yml and customize for themselves.

You should commit Vagrantparams.yml.dist to the repo and setup your VCS of choice to ignore Vagrantparams.yml. This way, changes to the latter will not be tracked by the VCS and a developer will not commit it accidentally.

Now you need to parse the params file and use its values in Vagrantfile:

1
2
3
4
5
6
7
8
9
10
11
12
require "yaml"

params = YAML::load_file("./Vagrantparams.yml")

Vagrant.configure("2") do |config|
  config.vm.network "private_network", :ip => params['ip']

  config.vm.provider :virtualbox do |vb|
    vb.customize ["modifyvm", :id, "--memory", params['memory']]
    vb.customize ["modifyvm", :id, "--cpus", params['cpus']]
  end
end

This should be self-explanatory, but if it’s not, the main trick is in the first 3 lines. You require the YAML module and parse the configuration file. Then you can use the params hash instead of hardcoded values.

That’s it. Now, each developer can configure their VM to use an IP address that works for them and set as many CPUs and as much RAM as they can to be sure they get the maximum performance their system allows.



© Elnur Abdurrakhimov