如何在Vagrant中使用本地环境变量?

时间:2016-02-10 08:55:50

标签: ruby ubuntu vagrant vagrantfile

我传递了我的本地环境变量:

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

Vagrant.configure(2) do |de|

  de.vm.box = 'ubuntu/trusty64'
  de.vm.hostname = 'virtual_machine'
  de.vm.network 'public_network', bridge:ENV['NETWORK_INTERFACE'], ip:'192.168.2.170'

  de.vm.provider "virtualbox" do |v|
    v.memory = 4096
    v.cpus = 2
  end

  de.vm.synced_folder '.', '/vagrant', disabled:true
  de.vm.synced_folder '../../synced/shared/', '/shared/'
  de.vm.synced_folder '../../synced/devops/', '/devops/'

  install = ENV['DEVOPS_HOME'] + '/vagrant/lib/install'
  de.vm.provision 'shell', path: install + '/basic'
  de.vm.provision 'shell', path: install + '/java8', args: ['automatic']
  de.vm.provision 'shell', path: install + '/aws_cli', args: [ENV['S3_AWS_ACCESS_KEY_ID'],ENV['S3_AWS_SECRET_ACCESS_KEY']]

  setup = ENV['DEVOPS_HOME'] + '/vagrant/lib/setup'
  de.vm.provision 'shell', path: setup + '/hosts'

  sys = ENV['DEVOPS_HOME'] + '/vagrant/lib/system'
  de.vm.provision 'shell', path: sys + '/add_user', args: ['virtual-machine',ENV['VIRTUAL_MACHINE_PASSWORD']]

  steps = ENV['DEVOPS_HOME'] + '/vagrant/server/virtual_machine/steps'
  de.vm.provision 'shell', path: steps + '/install_rserve'

end

显然,为此,我需要在~/.profile文件上设置此变量。但我想知道是否还有另一种方法可以做到这一点。如果我不需要通过Vagrantfile告知这一点,那么它看起来并不好看。

1 个答案:

答案 0 :(得分:2)

我设法拥有设置依赖的一种方法是使用外部文件(我使用yaml,但任何文件都可以像json一样工作.... Vagrantfile是一个ruby脚本,所以只要你可以使用ruby轻松读取它'很好)

使用Yaml依赖项的我的Vagrantfile示例

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

require 'yaml'
settings = YAML.load_file 'settings/common.yaml'

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

  config.vm.box = settings['host_box'] || "pws/centos65"
  config.ssh.username = settings['ssh_user']

  config.vm.define "db" do |db|
    db.vm.hostname = settings['db_hostname']
    db.vm.network "private_network", ip: settings['host_db_address']
  end

...

end

文件settings/common.yaml将被定义为

--- 
host_db_address:  "192.168.90.51" 
host_app_address: "192.168.90.52"

db_hostname:      "local.db"

ssh_user:         "pws"

正如评论中所述,我发现使用这种技术的主要优点是当你分发盒子时。我的团队将git克隆项目,必须填写设置(用于密码依赖等)并准备好了。