» Tips & Tricks

The Vagrantfile is a very flexible configuration format. Since it is justRuby, there is a lot you can do with it. However, in that same vein, sinceit is Ruby, there are a lot of ways you can shoot yourself in the foot. Whenusing some of the tips and tricks on this page, please take care to use themcorrectly.

» Loop Over VM Definitions

If you want to apply a slightly different configuration to manymulti-machine machines, you can use a loop to do this. For example, ifyou wanted to create three machines:

  1. (1..3).each do |i|
  2. config.vm.define "node-#{i}" do |node|
  3. node.vm.provision "shell",
  4. inline: "echo hello from node #{i}"
  5. end
  6. end

Warning: The inner portion of multi-machine definitionsand provider overrides are lazy-loaded. This can cause issues if you changethe value of a variable used within the configs. For example, the loop belowdoes not work:

  1. # THIS DOES NOT WORK!
  2. for i in 1..3 do
  3. config.vm.define "node-#{i}" do |node|
  4. node.vm.provision "shell",
  5. inline: "echo hello from node #{i}"
  6. end
  7. end

The for i in … construct in Ruby actually modifies the value of ifor each iteration, rather than making a copy. Therefore, when you run this,every node will actually provision with the same text.

This is an easy mistake to make, and Vagrant cannot really protect against it,so the best we can do is mention it here.

» Overwrite host locale in ssh session

Usually, host locale environment variables are passed to guest. It may causefailures if the guest software do not support host locale. One possible solutionis override locale in the Vagrantfile:

  1. ENV["LC_ALL"] = "en_US.UTF-8"
  2. Vagrant.configure("2") do |config|
  3. # ...
  4. end

The change is only visible within the Vagrantfile.