Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ENV vars from host to guest in Vagrant

Is there any way that I can set some ENV vars from host to guest Vagrant OS when booting it up? From my guest OS I need to connect to a database and I want to pass the database URL from host to guest as well as other parameters.

I tried with TEST="foo" vagrant up but TEST is nowhere in my env vars on guest os. Any ideas?

like image 396
Romeo Mihalcea Avatar asked Oct 01 '22 06:10

Romeo Mihalcea


People also ask

How do I set environment variables in vagrant?

The Vagrant File used in the VPP repo sets the configuration options based on your ENV (environment) variables, or to default the configuration at specified values if your ENV variables are not initialized (if you did not run the env.sh script found below). This is the env.sh script found in vpp/extras/vagrant.

How do I change my vagrant home directory?

Fortunately, vagrant provides an environment variable called VAGRANT_HOME by which you can set vagrant home. To make it permanent, add this to your ~/. bash_profile (for login shell). VAGRANT_HOME can be set to change the directory where Vagrant stores global state.

What is a Vagrantfile?

A Vagrantfile is a Ruby file that instructs Vagrant to create, depending on how it is executed, new Vagrant machines or boxes. You can see a box as a compiled Vagrantfile. It describes a type of Vagrant machines. From a box, we can create new Vagrant machines.


2 Answers

Your way of altering `vagrant up´ won't work. The correct way of doing this is during provisioning. Depending on the provisioner you are using, there are different ways.

Here is an example how to echo your host PATH env on your guest during provisioning:

config.vm.provision "shell", inline: "echo " + ENV['PATH']

As you can see, inside your Vagrantfile you can use the ENV variable to access the host environment variables. You can use this to pass variables to the provisioner of your choice and processing it as needed.

As I'm most used to chef, here is how I would do it:

  1. Pass all ENV variables needed through Vagrantfile into some chef attributes
  2. Create a template which iterates over the values provided and writes export statements
  3. Use chef to put this template into /etc/profile.d/ under some name that fits the needs
like image 179
Sgoettschkes Avatar answered Oct 05 '22 11:10

Sgoettschkes


@Romeo: See my related answer here: https://stackoverflow.com/a/42250314/6864226

config.vm.provision :shell, path: "scripts/bootstrap.sh", env: {"MYVAR" => ENV['ABC']}

@Sgoettschkes: Thanks for the pointer in the right direction

like image 27
bluebiscuit Avatar answered Oct 05 '22 12:10

bluebiscuit