Vagrant tricks – overwrite variables

In this post I will go over a useful vagrant trick I have been using, overwriting variables in the Vagrantfile.
Since the vagrant files are essentially just ruby files, we can take advantage of that and overwrite variables quite easily allowing us to tune the infrastructure we are building up. We can define variables in the Vagrantfile with some defaults and have a separate ruby file that we require in if it is present where we overwrite these defaults.

Example

Vagrantfile

$worker_box_name = "centos/7"
$worker_count = 3
$worker_memory = 1024
CLUSTER_CONFIG = File.expand_path("cluster-config.rb")
if File.exist?(CLUSTER_CONFIG)
  require CLUSTER_CONFIG
end
Vagrant.configure(2) do |config|
  (1..$worker_count).each do |i|
    config.vm.define "w#{i}" do |w|
      w.vm.box = $worker_box_name
      w.vm.hostname = "w#{i}"
      w.vm.provider "virtualbox" do |vb|
        vb.memory = $worker_memory
      end
      # provision steps...
    end
  end
end

cluster-config.rb

$worker_count = 2
$worker_memory = 2048

This will create a cluster with 2 workers with 2048mb memory instead of the default 3 worker with 1024mb memory

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s