Environment Variables for Agents
os.environ, os.getenv(), and why never hard-code secrets in source code.
Why Not Hard-Code API Keys?
Hard-coding API keys directly in source code is one of the most common and costly security mistakes. Keys committed to version control are visible to everyone who has access to the repository — including future contributors, CI systems, and anyone who finds the repo online.
The Git History Problem
Even if you delete a hard-coded key from your code later, it remains in your git history. Anyone who clones the repository and runs git log or git show can find it. Keys must never enter version control.
# NEVER DO THIS:
OPENAI_API_KEY = 'sk-proj-abc123def456...' # in source code
# This key is now:
# 1. In your current code
# 2. In git commit history FOREVER
# 3. Visible to all collaborators
# 4. Visible if repo is made public
# 5. Visible in CI logs that print env vars
# ALWAYS DO THIS:
import os
OPENAI_API_KEY = os.environ['OPENAI_API_KEY'] # read from environment
print('Key loaded from environment — never hard-coded')All lessons in this course
- Environment Variables for Agents
- .env Files and python-dotenv
- Secrets Rotation and Security
- Configuration Profiles for Dev and Prod