.env File Management

Local development relies on .env files for ergonomic secret injection without requiring external infrastructure. However, careless loading patterns introduce silent override vulnerabilities that propagate to production. This section establishes strict precedence rules and validation workflows.

Security-First .env Practices

The .env file must serve exclusively local development. Production deployments inject all secrets via orchestrator variables or secret managers. Implement conditional loading that respects platform-injected configuration.

Key Principles

  • Never commit .env to version control - Use .env.example instead
  • Enforce strict precedence - System variables always override local files
  • Validate all content - Reject malformed or suspicious values
  • Clear after use - Minimize secret lifetime in memory

Implementation

import os
from pathlib import Path
from dotenv import dotenv_values

# Load only in local environments
if os.getenv("ENVIRONMENT", "production") == "local":
    env_file = Path(".env")
    if env_file.exists():
        local_config = dotenv_values(env_file)
        for key, value in local_config.items():
            # Never override existing environment variables
            if key not in os.environ and value:
                os.environ[key] = value

Learn more about safe loading patterns in How to safely load .env files in Python 3.12.