pycontribs/python-vagrant

Support passing environment variables

aconrad opened this issue · 4 comments

I need python-vagrant to pass environment variables down to the vagrant subprocess call so the code in Vagrantfile can act accordingly but this is not possible given the way things are currently set up.

For example, Vagrantfile can check in the system's environment if the variable USE_NFS=1 is set in which case Vagrantfile will mount the shared directories using NFS (instead of the default vboxfs). The python tool that wraps python-vagrant would know whether this flag should be set to 1 or 0 but it can't currently pass it to vagrant.up().

Would this be something considered if I were to submit a pull request?

I was considering having vagrant.up() take an new env keyword argument such that my tool could do:

vagrant.up(env={"USE_NFS": "1"})

... and then the underlying code in Vagrant._call_vagrant_command would have:

def _call_vagrant_command(self, args, env=None):
    # ...
    subprocess.check_call(command, cwd=self.root, env=env)

Bump.

Thanks for the bump. :-) Unless you see a particular reason to vary the environment on a per-command basis, I lean toward including the environment in the Vagrant constructor and passing it to the underlying vagrant command similar to how you suggested:

def _call_vagrant_command(self, args):
    # ...
    subprocess.check_call(command, cwd=self.root, env=self.env)

Let me know if this approach would satisfy your use case.

I think this would work. By default Vagrant.environ would be None since subprocess automatically inherits from the current environment if env=None.

If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process’ environment, which is the default behavior.

source: https://docs.python.org/2/library/subprocess.html#subprocess.Popen

But if users want to tweak the environment they will want to do this:

vagrant.environ = os.environ.copy()
vagrant.environ['USE_NFS'] = '1'