Using Environment Variables in Python

Cherie
5 min readOct 26, 2022

--

Below is a basic tutorial about how to set up environment variables and call them in Python. I’ve decided to create this how-to after I didn’t find any straight forward explanation on the internet. Let me start by telling you why it is a good idea to use environment variables in your code.

  1. Improved Security: You shouldn’t be storing passwords, tokens, or sensitive information in your source code. It’s how credential leaks like Shibu Inu’s happen… I’ve also been part of awkward company wide demos where sensitive information is on display for the entire organization to see.
  2. CI/CD workflows are more efficient when credentials aren’t hardcoded. I am not going to explain CI/CD is in this post, that’s another rabbit hole for a different day. Bottom line, everyone hates doing redundant things and hard coded credentials are redundant. Using environment variables stops you from having to manually change those values over and over.

Now let’s begin…

First I am going to start with a list of prerequisites.

Python Libraries & Functions

Step 1: Launch VS Code, create a project folder, and download dotenv library

Create a new folder on your desktop that you will be able to open once you launch VS Code. For the purpose of this demo, I am going to create a folder names Environment Variables. This folder is used to store a set of files specific to this project and is good practice for managing code.

Launch VS Code and open the folder.

After you need to install the dotenv library to your terminal. Don’t worry about the os library as it is native to python (meaning one of the preinstalled libraries). To install the library using VS Code go to Terminal>New Terminal and in the terminal window type the code below.

pip3 install python-dotenv
Installing the python-dotenv library using the terminal in VS Code

Step 2: Create a .env file, a python file, and a .gitignore file

Select the new file icon and then type .env this will create a file with a gear icon beside it to store your environment variables. Next, create your python file. I am going to name my file envVar.py. After, create a .gitignore file, this is necessary because you will need to reference your .env file in the .gitignore file so all your passwords aren’t pushed to a shared repository (if you are pushing your code to a repo).

Create new files by clicking the New Icon or navigating to File>New File

Step 3: Adding environment variables to the .env file

I am going to add some Azure variables in here as an example because I work with Azure a lot. The same thing can be done if you need to store login credentials, like a username and password. So in the environment file I am going to use the following code snippet.

# Setting the subscription variablesAZURE_SUBSCRIPTION_ID = '[YOUR SUBSCRIPTION ID]'
AZURE_TENANT_ID = '[YOUR TENANT ID]'
AZURE_CLIENT_ID = '[YOUR SERVICE PRINCIPAL APPLICATION (CLIENT) ID]'
AZURE_CLIENT_SECRET = '[YOUR SERVICE PRINCIPAL SECRET VALUE]'

After you add the details hit ctrl+K S or File> Save All

Step 4: Reference the environment variables in your python script

Drum roll please… Now it’s time to call these environment variables and store them in your script. While in the envVar.py file, you will need to import the libraries mentioned above, then use the load_dotenv() method which allows the current envVar.py file to “acknowledge” the .env file.

Then, you will assign the needed environment variables to their own variable within the envVar.py script by using the os library, getenv() method, and reference the name of the respective environment variables in the .env file.

Illustration of referencing the environment variables in the main python script

I’ve used a print statement so we can confirm that the script is indeed calling the environment variables from the .env file. You’ll need to save the envVar.py file by hitting hit ctrl+K S or File> Save All.

Call the python script, using a new terminal (you should be pointed to the path where your project folder and files are located). Run the following snippet ‘python envVar.py’ in the terminal to test your script.

C:\Desktop\Environment Variables> python envVar.py
Taaa-daaa! The output of the script are those environment variables you stored in the .env file

Now you shouldn’t typically print your environment variables out like this but I am confirming that you can pull them in to a script from the .env file.

Step 5: Using .gitignore to leave out the.env file when pushing to a repository

Okay so if you are going to be pushing your code to a repository and the whole point of using environment variables is to NOT share secret values, then make sure you add your .env file to the .gitignore file. gitignore is used to intentionally ignore files when tracking changes using version control or code management tools.

All you have to do is type /.env in the .gitignore file to reference the .env file where your values are stored. Save everything by using ctrl+K S or File> Save All.

gitignore is robust and can be used to declutter repositories and make project more lightweight for sharing

You just created, stored, and used environment variables.

Thank You!

Q & A

Well how do other team members get these environment variables then?

If you are sharing sensitive information like passwords, keys, token, certificates, etc. you should be using a key vault, encrypted email, or service like secret server to share that information.

Okay for some reason my environment variables are pointing to ones I just used in a different script, what’s going on?

To fix this, import the .env file within the load_dotenv() method. (i.e. load_dotenv (“C:/Desktop/Environment Variables/.env”). This points to the environment variables in the required path.

--

--