3

I'm running Vagrant 1.8.5, which supports environment variables in the Vagrantfile at provisioning time using a format like this

config.vm.provision :shell, path: "bootstrap.sh", env: {"MYSQL_DB_USERNAME"=>"django", "MYSQL_DB_PASSWORD"=>"supersecretpasswordwasreplaced"}

However, I would like these environment variables to also be available when I do up without provisioning, or when I SSH into the server to do jobs. The obvious ways I can find are

  • to have them built into the box (seems like overkill) or
  • repeat them in my config.ssh.forward_env so that they are available to both the provisioner and SSH.

Is there a better way?

Tadhg
  • 561
  • 5
  • 15

2 Answers2

8

I am not sure about the best ultimate way - I've seen this question popping from time to time and discussion.

repeat them in my config.ssh.forward_env so that they are available to both the provisioner and SSH.

well, it could sound like a good solution but there's some drawback, I've discussed in this question already

Personally when I need to set env variable, I would add them in the .profile file:

  config.vm.provision "shell", privileged: false, inline: <<-SHELL
    echo "export MYSQL_DB_USERNAME = django" > /home/vagrant/.profile
    echo "export MYSQL_DB_PASSWORD = supersecretpasswordwasreplaced" > /home/vagrant/.profile
  SHELL

They will be available when you login.

Community
  • 1
  • 1
Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
6

At first glance, this answer seems similar to the top voted answer. However, please look carefully at the redirection operator on the second echo

config.vm.provision "shell", env: {"DOCKERHUBID"=>ENV['DOCKERHUBID'], "DOCKERHUBPASS"=>ENV['DOCKERHUBPASS']}, inline: <<-SHELL
echo "export DOCKERHUBID=$DOCKERHUBID" > /home/vagrant/.profile
echo "export DOCKERHUBPASS=$DOCKERHUBPASS" >> /home/vagrant/.profile
SHELL
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
  • Thank you! There are so many incorrect and confusing answers out there for how to accomplish this. Yours is neither. :) – TJ Zimmerman Sep 11 '20 at 17:19