问题描述
有人可以指导我如何在VagrantFile中包含变量吗?我试图从外部文件将配置注入Vagrantfile,以便我可以将配置分发给我的同事,而无需他们直接在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曾以为,由于它是基于Ruby的,所以我只能包含一个Ruby文件,但出现错误
消息:未初始化的常量MyVars
I had thought that since it was Ruby based I could just include a Ruby file but I get an errorMessage: unintialized constant MyVars
我的VagrantFile简化了
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
.rb包含
module MyVars
WEBVMNAME = "rex"
end
请注意,我也是Ruby的新手,所以我不确定它是否只是我弄错了语法吗?
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?
编辑:我正在使用的更新代码
Updated code I am using
推荐答案
我使用的方法,我在Vagrantfile的同一目录中创建了一个文件config.yaml。 ..
I use the approach of https://puphpet.com, I create a file config.yaml in the same directory of the Vagrantfile and...
在我的Vagrantfile中:
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']
...
在我的config.yaml中:
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>...
这篇关于如何在VagrantFile中包含变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!