How to use config.ssh.forward_env in Vagrant?

Viewed 1134

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?

2 Answers

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.

Related