如何在 VagrantFile 中包含变量? [英] How do I include variables in my VagrantFile?

查看:18
本文介绍了如何在 VagrantFile 中包含变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能指导我如何在 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.

我原以为因为它是基于 Ruby 的,所以我可以只包含一个 Ruby 文件,但我收到一个错误消息:未初始化的常量 MyVars

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

我的 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

和 vagrant.rb 包含

And vagrant.rb contains

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?

更新我正在使用的代码

推荐答案

我使用了https://puphpet.com的方法,我创建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 中包含变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆