How use local environment variable with Vagrant?

ぃ、小莉子 提交于 2020-01-06 20:15:33

问题


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.



来源:https://stackoverflow.com/questions/35310584/how-use-local-environment-variable-with-vagrant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!