Handling Passwords and Secret Keys using Environment variables

Handling Passwords and Secret Keys using Environment variables

·

4 min read

This article shows a quick tip on how you can hide the secret information on environment variables and access that information from Python code in a Windows Machine.

Sharing your secret stuff like credentials related to the code is not recommended while working on a project and the reason is ,we will be working with databases, or accessing an API that have a secret key, then they have their passwords or secret keys, directly in Python scripts.

Now the problem with that is, if you working with team of people or pushing your code to the repository, then anyone who can see that code, will also have the access to that secret information.

Keep them in environment variables

So, if you have the information saved in the environment variable, then you still be able to share your code but your secret information saved on your local machine.

Let’s see how you can do this in a Windows Operating system . For explanation,I have a script with fake credentials i.e. I have fake database user and fake database password. This code can also be secret API key or any information that you don’t want to share with everyone who has access to the code.

import os

db_user = 'my_project_user'
db_password = 'my_project_pass'

To save passwords and secret keys in environment variables on Windows, you will need to open Advance System Setting.

You can navigate to control panel > System and Security > System > Advanced system Settings

Now in Advance System Setting click on Environment Variables. Here we can add new user variables and new system variables. We will add user variable by clicking New under user variables.

In the new window you can add Variable name and Variable value and click ok. Now, click Ok on Environment Variables window to save changes.

Access the environmental variables

To access these environment variables in our python script, we need to import the os module. We can do that by using os.environ.get() .This is a dictionary . So we can access the keys of that dictionary by using get() method and passing the key you want to access.

import os

db_user = os.environ.get('db_user')
db_password = os.environ.get('db_password')

Now if we run the code, we can see that we got the values that we set in our environment variables without them actually being hardcoded into our script.