modularize Vagrantfile with include, require, require_relative

291 views
Skip to first unread message

Kevin Kruzich

unread,
Feb 17, 2018, 4:52:29 PM2/17/18
to Vagrant

I'd like to modularize my Vagrantfile. I want a main section, Vagrantfile, to be shared amongst several environments, with 'Vagrantfile.include' used for local definitions.

I've tried an endless number of solutions towards this. All have failed. Please let me know if the expectations are unrealistic here. 

I have the following Vagrantfile. The 'require' and 'require_relative' reflect two of the many attempts to do this. 

The Vagrantfile.include is further below. In the case of require, I get the error 'uninitialized constant MyVars'. In the case of require_relative I get 'undefined local variable or method `systems'

What would be a better approach here? 


# -*- mode: ruby -*-
# vi: set ft=ruby :

BOX_IMAGE
= "centos7-2018020400"

# require 'Vagrantfile.include'
require_relative
'Vagrantfile.include'
include
MyVars

Vagrant.configure("2") do |config|
 systems
.each do |i,x|
  config
.vm.define vm_name = "#{i}" do |subconfig|
   subconfig
.vm.box = BOX_IMAGE
   subconfig
.ssh.username = "vagrant"
   subconfig
.ssh.password = "vagrant"
   subconfig
.vm.hostname = "#{i}"
   subconfig
.vm.network :public_network, auto_config: false, bridge: "#{ENV['BRIDGE']}"
   subconfig
.vm.provision "shell", inline: <<-SHELL
   
/bin/yum -y update
   SHELL
   subconfig
.vm.provider "virtualbox" do |v|
    v
.name = vm_name
    v
.customize ["modifyvm", :id, "--paravirtprovider", "kvm"]
    v
.customize ["modifyvm", :id, "--autostart-enabled", "on"]
   
end
 
end
 
end
end


Vagrantfile.include

# -*- mode: ruby -*-
# vi: set ft=ruby :

module MyVars

ENV
["BRIDGE"] = "eno1"

systems
= {
       
'host1' => '',
       
'host2' => '',
       
'host3' => '',
       
}
end

Matthew Andersen

unread,
Feb 18, 2018, 10:18:00 AM2/18/18
to Vagrant
If the code works when you move the ENV and systems definitions inside the Vagrantfile, you’re probably having issues with variable scope. When you define a module it hides all the variables inside it from the outside world.

Unless you need to run Ruby code in your config, maybe it would be better to define your configuration in some kind of text format, like YAML, then you can import that in the Vagrantfile and use it like an object.

I’m not a Ruby programmer by any stretch, but a quick Google search made it look like the YAML module would be easy to use.

Kevin Kruzich

unread,
Feb 18, 2018, 2:51:21 PM2/18/18
to Vagrant

Thanks Matthew --I did see an example that involved creating the ancillary file in YAML. I may pursue that however I was hoping to find as simple a means as `include foobar` 
Reply all
Reply to author
Forward
0 new messages