In this lesson, you’ll learn how to secure your application by decoupling sensitive credentials from your codebase using operating system environment variables.
The Problem with Hardcoding
When you write an API key or a database password directly into your Python file, you create a major security risk. If you push that code to a version control system like Git, those secrets are exposed to anyone with repository access. Even if your repo is private, it is considered bad practice to leave sensitive data in plaintext.
Using Environment Variables
An environment variable is a value that exists outside your code, managed by the operating system. By storing your secrets in the environment, you ensure they remain separate from your project's logic.
In Python, the os module provides a standard way to access these variables using os.environ.
import os
# Access a secret key from the environment
# It is good practice to provide a default or handle the case where it's missing
api_key = os.environ.get("MY_SERVICE_API_KEY")
if not api_key:
raise EnvironmentError("Missing required environment variable: MY_SERVICE_API_KEY")
def connect_to_service():
print(f"Connecting with key: {api_key[:4]}****")
Setting and Accessing
How you set these variables depends on your OS:
- Linux/macOS: You can export them in your terminal session via
export MY_SERVICE_API_KEY="your_secret_here". - Windows: You can set them via PowerShell using
$env:MY_SERVICE_API_KEY="your_secret_here".
When your Python script runs, it looks into the process environment to retrieve these values. Because these variables are set in the shell session rather than inside the .py file, they never get committed to your repository. This makes your deployment process safer, as you can define different variables for development, testing, and production environments without changing a single line of your application code.
Key Takeaway: Never hardcode sensitive credentials; always inject them as environment variables to keep your secrets out of your version control history.