Adding Environment Variables
This lesson covers the environment variables feature available on our platform.
Environment variables are global variables that allow you to take data from the learner and use it in the code. For example, you may want the learner to connect to Firebase using their credentials. These credentials can be extracted as environment variables and used in your application.
Creating Environment Variables
To use environment variables, you need to build a Docker image and then create a Docker job as learned earlier.
In the Docker Container section of the course editor, click the globe icon to add a new environment variable:
The Environment Variables fields will open up where you can specify the key and the value.
Key
The key is the name used to access the environment variable inside your code. Accessing environment variables has a different syntax for every language. For example, if we wanted to use the key created above in Python, we’d write os.environ["username"]
.
Value
This is the actual value of the environment variable exposed in the container. You can leave it empty if you strictly want the user to specify it. For the username
key we created above, its default value is Educative
.
Click on the Save icon to store your environment variable. It will now be available in all widgets that support Docker.
Setting Up the Docker Job
For our example, we have created a Docker image that has mlxtend
support for Python. Here’s what the job looks like:
Enabling Environment Variables
To enable environment variables in a widget, select a Docker job in that widget. Below, we have selected the mlxtend
Docker job in a code widget.
Note: You do not have to select a Docker job for the Terminal widget.
Now, your environment variables will be visible to the learner! Check out the widget below:
import osprint(os.environ["username"])
Users can edit the value of any environment variable by clicking the Edit button. Changing the value in one lesson changes it everywhere in the course.
Disabling Environment Variables
You may not want a particular widget to show environment variables. In that case, you can disable any environment variable using the Select Env Vars option in the widget’s panel:
Things to Know
-
Environment variables cannot be defined in the Dockerfile. Those variables will not be transferred over to the platform when the image is built. Hence, it’s always safer to use the environment variable functionality discussed above.
-
Environment variables can be updated in the Start Script of a job. However, the Run Script cannot be used to update environment variables.
-
The terminal widget will relaunch if a user changes the environment value in it.
-
To ensure safety, values added by a user are not accessible by Educative. We do not store any credentials or data.