How use local environment variable with Vagrant?

2019-09-04 02:36发布

问题:

I'm passing my local environment variables like this:

# -*- 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

Obviously, for that I need to set this variable on my ~/.profile file. But I wonder if there is another way of doing this. Where I don't need to inform this via Vagrantfile, it doesn't look nice.

回答1:

one way I manage to have settings dependency is to use an external file (I use yaml, but any file would work like json .... Vagrantfile is a ruby script so as long as you can easily read it using ruby you're fine)

An example of my Vagrantfile using a Yaml dependency

:# -*- 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

the file settings/common.yaml would be defined as

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

db_hostname:      "local.db"

ssh_user:         "pws"

As said in comment, the main advantage I found using this technique is when you distribute box. My team would git clone the project, has to fill up the settings (for password dependency and so on) and ready to go.