shellubuntufabric

How to set environment variables using Fabric


I have a local development environment that relies heavily on system environment variables (it follows the Heroku 12-factor app model), and I currently set these using a shell script. The shell script also sets up git remotes, and activates the virtualenv environment, and I'd like, if possible, to move all this to a Fabric command (or series of commands), as we are using Fabric for a bunch of other stuff, and I'd like to retire the shell scripts.

Running local('export FOO=bar') doesn't work:

$ fab set_default_env_vars
Using fabfile '/home/hugo/Projects/test/fabfile.py'
[localhost] local: export FOO=bar

Done.

$ echo $FOO

$

Is this possible - and if so, how?


Solution

  • You can use fabric.context_managers.shell_env to export a variable to bash for your shell and all subshells spawned from it - but those variables won't persist beyond the shell that they were defined for (so you can't set environmental variables for the parent shell from a fabric script the way your example has it).

    You can set up a bash script that you source for your local environment that is identical to what you would add to ~/.profile in your production slug (in its keys, not necessarily its values) and use fabric.context_managers.prefix to source that file before you run your local commands.