Skip to main content

Environment variables to Enhance Data Security in Python

By febrero 16, 2024marzo 19th, 2024No Comments

In the dynamic world of software development, managing sensitive information such as API keys and other configuration details is a critical aspect to build secure applications. One powerful tool that Python developers utilize for this purpose is environment variables. In my other blog, I wrote about masking data as a security measure. I this blog, I will explore what environment variables are, how they work in Python, and how they contribute to data security.

Understanding Environment Variables

Environment variables are external configuration values that are accessed by processes running on a system. These values are set outside the code and are used to configure the behavior of applications. In Python, the os library provides a straightforward way to interact with environment variables. Environment variables are a good tool to prohibit sensitive information such as usernames, passwords, or API keys in files that you want to share in a shared repository. Before delving into the security aspects, let’s understand how to set environment variables. You can store them by using a special file format such as .env. In this file you can define any sensitive information as variables in the .env file (Fig. 1)

As mentioned previously, the os library in python provides a straightforward way to interact with these environment variables. Additionally, the dotenv library allows you to find the .env. file, saves the path, and loads the .env file to the current directory (Fig. 2).


Use case example: Python connector for Snowflake

For a current project we have to set up a connection between python and snowflake via a snowflake connector. If you want to set up a Snowflake connector in Python you need to fill in your account information, such that python can actually connect to the specific snowflake account. By simply providing your username and password, this sensitive information can accidentally end up in a shared public environment. Hence, using environment variables is a safe way to add a level of security to this type of information (Fig. 3)

Final step: Security measure

A final crucial step is to actually make sure that the .env file is not shared in the repository. Otherwise, all this effort of securing your sensitive information has gone to waste. If you work with GitHub for shared repositories you can add the .env file to your .gitignore file. By adding the environment file to your .gitignore file, other members of the shared repository cannot see the .env file, such that your sensitive information is only stored on your local computer!



Leave a Reply