6

I want certain environment variables from my host system to be visible inside my Vagrant VM, using the config.ssh.forward_env setting. I'm using Vagrant 1.8.1. Here's my Vagrantfile:

Vagrant.configure(2) do |config|
  config.vm.box = 'ubuntu/trusty64'
  config.ssh.forward_env = ['FOO']
end

After creating it, I ran these commands:

vagrant up
export FOO=bar
vagrant ssh -c 'echo $FOO'

I expected the final line to output bar, but instead it outputs a blank line (followed by Connection to 127.0.0.1 closed.). What am I doing wrong?

Taymon
  • 24,950
  • 9
  • 62
  • 84

2 Answers2

10

TL;DR

fhenri@machine$ export LC_MYVAR=TEST
fhenri@machine$ vagrant ssh -c 'echo $LC_MYVAR'
TEST
Connection to 127.0.0.1 closed.
fhenri@machine$ 

As said in the doc, config.ssh.forward_env works as sendEnv so to pass variables using sendEnv you must configure your host to accept env variables, by default (and hoping my example above should work) the common setup allows LC_* through, you can review the authorized variables in /etc/ssh/sshd_config

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

you can add your own variables here as needed or use default prefix LC_

Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
0

I know this does not answer your question directly as you say you want to use config.ssh.forward_env but you can actually send environment variables without that like so:

a=1
vagrant ssh -- -t <<EOF
echo a=$a
EOF

# prints:
a=1

What happens here is the variable $a gets replaced by 1 and then only the heredoc (the part between <<EOF and EOF) gets sent to the vagrant VM.

It's maybe obvious to some, but it wasn't to me in the beginning. If you want to make the value of $a available in a script you're calling inside the heredoc, then you need to assign it first to a variable and export that variable:

a=1
vagrant ssh -- -t <<EOF

export b="$a"
c="$a"

bash -c 'echo b=\$b c=\$c'
EOF

# prints:
b=1 c=

This trick is valid with "plain" ssh too.

ibizaman
  • 3,053
  • 1
  • 23
  • 34