Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 36 ยท Multi-machine Environments

Data-driven Machine Definitions

Use plain Ruby in a Vagrantfile to loop over machines, read a YAML file, merge defaults with per-machine overrides, and keep large clusters readable.

A Vagrantfile is a Ruby program. That means you are not limited to copy-pasting config.vm.define blocks. You can describe your machines as data, loop over that data, and generate the configuration. This keeps a ten-node cluster as short as a two-node one, and it lets teammates change a setting in one place.

Looping over a hash

The simplest step is a Ruby hash at the top of the file.

Ruby
NODES = {
  "web1" => { ip: "192.168.56.21", memory: 1024 },
  "web2" => { ip: "192.168.56.22", memory: 1024 },
  "db"   => { ip: "192.168.56.30", memory: 2048, cpus: 2 }
}

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/jammy64"

  NODES.each do |name, spec|
    config.vm.define name do |node|
      node.vm.hostname = name
      node.vm.network "private_network", ip: spec[:ip]
      node.vm.provider "virtualbox" do |vb|
        vb.name   = "demo-#{name}"
        vb.memory = spec[:memory]
        vb.cpus   = spec.fetch(:cpus, 1)
      end
    end
  end
end

spec.fetch(:cpus, 1) is a small but valuable habit: it supplies a default when a key is missing. Adding a third web server now means adding one line to NODES.

Generating names with a range

When machines are identical, do not even list them. Count them.

Ruby
WEB_COUNT = (ENV["WEB_COUNT"] || 3).to_i

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/jammy64"

  (1..WEB_COUNT).each do |i|
    config.vm.define "web#{i}" do |web|
      web.vm.hostname = "web#{i}"
      web.vm.network "private_network", ip: "192.168.56.#{20 + i}"
    end
  end
end

Run WEB_COUNT=5 vagrant up for five servers. On Windows PowerShell set the variable first with $env:WEB_COUNT = 5.

If you change the count after machines exist, Vagrant sees the extra definitions as new machines and the missing ones as orphans that it no longer lists in vagrant status. Run vagrant destroy for removed machines before you shrink the definition, or you will leave stray VMs behind (visible with vagrant global-status).

Reading a YAML file

Hash literals are fine for developers, but a YAML file is friendlier for people who do not read Ruby. Put the data in machines.yml beside the Vagrantfile:

YAML
defaults:
  box: ubuntu/jammy64
  memory: 1024
  cpus: 1
machines:
  - name: web
    ip: 192.168.56.10
    forward: { 8080: 80 }
  - name: db
    ip: 192.168.56.11
    memory: 2048

Then load and merge it:

Ruby
require "yaml"

settings = YAML.load_file(File.join(__dir__, "machines.yml"))
defaults = settings.fetch("defaults")

Vagrant.configure("2") do |config|
  settings.fetch("machines").each do |machine|
    spec = defaults.merge(machine)          # per-machine keys win

    config.vm.define spec["name"] do |node|
      node.vm.box = spec["box"]
      node.vm.hostname = spec["name"]
      node.vm.network "private_network", ip: spec["ip"]

      (spec["forward"] || {}).each do |host_port, guest_port|
        node.vm.network "forwarded_port", guest: guest_port, host: host_port
      end

      node.vm.provider "virtualbox" do |vb|
        vb.memory = spec["memory"]
        vb.cpus   = spec["cpus"]
      end
    end
  end
end

File.join(__dir__, ...) makes the path independent of where you run the command. Hash#merge implements the "defaults plus overrides" idea in one call: any key the machine sets replaces the default.

Layered config files

Teams often want a committed file with sensible values and an uncommitted personal file for one developer's tweaks, such as more RAM on a powerful desktop.

Ruby
base  = YAML.load_file(File.join(__dir__, "machines.yml"))
local = File.join(__dir__, "machines.local.yml")
base  = base.merge(YAML.load_file(local)) { |_, a, b| a.merge(b) } if File.exist?(local)

Add machines.local.yml to .gitignore. Everyone else keeps the shared defaults.

A stand-in: merge and validate in plain Ruby

The same merge logic runs anywhere Ruby does. Here it is with a heredoc YAML string so you can see the resulting plan. (Vagrant itself is not involved; this is the data-handling half of the Vagrantfile.)

Ruby Merge defaults and overrides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The total at the end is useful in real life too. A quick sum like this warns you when a cluster would need more RAM than your laptop has.

Keeping data-driven files readable

  • Validate early. Raise a clear error when a required key is missing; a stack trace deep inside Vagrant is much harder to read.
  • Keep logic out of the data. If you need conditionals for many machines, the data is probably hiding two different designs.
  • Print the plan. A puts of the resolved plan (guard it with ENV["DEBUG"]) saves hours when a value does not behave as expected.
  • Do not compute things at load time that depend on running VMs. The Vagrantfile is evaluated on every command, including vagrant status.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does defaults.merge(machine) do when both hashes have a memory key?

    Hash#merge lets the argument's keys win, so per-machine values override defaults.
  2. 2. Why use File.join(dir, "machines.yml") instead of "machines.yml"?

    dir is the directory of the Vagrantfile, so the path does not depend on the current working directory.
  3. 3. You lower WEB_COUNT from 5 to 3 without destroying anything. What can happen?

    Vagrant only manages machines it finds in the Vagrantfile. Destroy removed machines first or find them with vagrant global-status.
  4. 4. Why should a personal override file such as machines.local.yml be in .gitignore?

    Local overrides are per-person tweaks and should not be shared.

Summary

  • A Vagrantfile is Ruby: use hashes, ranges and loops to generate machines.
  • Read machine specs from YAML, merge shared defaults with per-machine overrides, and layer an ignored local file on top.
  • Validate input and print the resolved plan so mistakes are easy to spot.
  • Remove machines with vagrant destroy before shrinking a generated set.

Next: Providers overview