Environment variables are useful to store sensitive data like API keys or passwords when we don't want them to be hard coded in our source code. But we often only use them in some specific circumstances and don't need to have them set all the time. In this short post, I am going to show how to save environment variables in a virtual environment set using conda.

First, we need to create the virtual environment using the conda create command:

$ conda create --name my_environment

This command will create a my_environment subdirectory in the anaconda3/env directory.

Next, we activate the environment:

$ source activate my_environment
(my_environment)$ 

Now, we need to create scripts that will set our environment variables whenever we activate our virtual environment and unset them when we deactivate. The path to our environment directory is set as $CONDA_PREFIX. We cd to that directory and create a /etc/conda/activate.d and a /etc/conda/deactivate.d directory:

(my_environment)$ cd $CONDA_PREFIX
(my_environment)$ mkdir -p ./etc/conda/activate.d
(my_environment)$ mkdir -p ./etc/conda/deactivate.d

In each of those directories, we create a env_var.sh script where we'll write the commands to set and unset our variables:

(my_environment)$ touch ./etc/conda/activate.d/env_vars.sh
(my_environment)$ touch ./etc/conda/deactivate.d/env_vars.sh

In activate.d/env_vars.sh, we add the export commands to set our variables when the virtual environment is activated:

#!/bin/sh

export MY_VARIABLE=some_value

In deactivate.d/env_vars.sh, we add the unset commands to delete our variables when the virtual environment in deactivated.

#!/bin/sh

unset MY_VARIABLE

Let's test our setting. We need to reactivate our environment to get the variables set.

(my_environment)$ conda deactivate
$ conda activate my_environment
(my_environment)$ echo $MY_VARIABLE
some_value

The environment variable has been set. Now, let's check if the variable is unset when we deactivate our environment:

(my_environment)$ conda deactivate
$ echo $MY_VARIABLE

$

The echo command returns an empty line, meaning that our variable has been unset.

VoilĂ ! We now have a virtual environment with it's own environment variables.