Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

ruby - How do I include variables in my VagrantFile?

Can anyone guide me to how do I include variables in my VagrantFile? I am trying to inject configs into the Vagrantfile from an external file so that I can distribute the config to my colleagues without having them to hardcode configs directly on the Vagrantfile.

I had thought that since it was Ruby based I could just include a Ruby file but I get an error Message: unintialized constant MyVars

My VagrantFile simplified

# -*- mode: ruby -*-
# vi: set ft=ruby :
require 'vagrant.rb'
include MyVars

Vagrant.configure("2") do |config|

  # Web
  config.vm.define :joe do |joe|
    joe.vm.box = "precise64_4.2.12"
    joe.vm.hostname = WEBVMNAME
    joe.vm.network :private_network, ip: "192.168.140.141"

    # Port Forwarding
    joe.vm.network :forwarded_port, guest: 22, host: 2201
    joe.vm.network :forwarded_port, guest: 80, host: 8080

    # Bootstrap Bash Script
    joe.vm.provision :shell, :path => "bootstrap.sh"
  end

end

And vagrant.rb contains

module MyVars

    WEBVMNAME = "rex"

end

Do note that I am also a newbie at Ruby so I am not sure as well if its just the syntax I got wrong?

Edit: Updated code I am using

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I use the approach of https://puphpet.com, I create a file config.yaml in the same directory of the Vagrantfile and...

In my Vagrantfile:

# encoding: utf-8
# -*- mode: ruby -*-
# vi: set ft=ruby :

require 'yaml'

current_dir    = File.dirname(File.expand_path(__FILE__))
configs        = YAML.load_file("#{current_dir}/config.yaml")
vagrant_config = configs['configs'][configs['configs']['use']]

Vagrant.configure('2') do |config|

    config.vm.network 'public_network', ip: vagrant_config['public_ip']
    ...

In my config.yaml:

---
configs:
    use: 'home'
    office:
        public_ip: '192.168.2.117'
        <more variables>...
    home:
        public_ip: '192.168.1.117'
        <more variables>...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...