Handling Passwords and Secret Keys using Environment Variables

The simplest way and the wrong way to handle these important credentials is to hardcode it in our code. When you push the code to the repository you are sharing your secret stuff with everybody else in your project. Even if you are working alone it can cause problems as anyone who sees your code will also have access to your secret information.

Keep them in environment variables

The safest way to handle your secret keys/password is saving them in envirnoment variables. In this post we will learn how to save important credentials in environment variables and access them in python script.


To set password or secret keys in environment variable on Linux(and Mac) you need to modify .bash_profile file that is in your home directory. You need to open the terminal and cd to the home directory.

$ cd 

Now, open the .bash_profile file in any text editor of your choice.

$ nano .bash_profile 

We need to add our environment variable in this file. For that add following content at the top of the file.

export USER="username" 
export PASSWORD="password" 

Note: There should not be any whitespace on either side of = sign.

Save the nano file by pressing ctrl + x and Y. Now, use the following command to effect the changes.

$ source .bash_profile 

Using a separate .env file

The above mentioned method saves the secret credentials system-wide which may not be good idea if you have multiple applications.

The solution is to store the secrets in a seperate .env file.

A dotenv file contains only text, where it has one environment variable assignment per line.

Create a .env file in your project and add your secret keys or passwords: