Managing Django Secrets in Production
Using a .env
file with python-dotenv for your Django application in production has both advantages and limitations from a security perspective.
Security Considerations for .env
Files
When using a .env
file on a DigitalOcean Droplet:
- It's better than hardcoding secrets in your settings files or committing them to Git
- However, the secrets are still stored in plaintext on the server filesystem
- If your server is compromised, an attacker could potentially access these secrets
Best Practices for .env
Files
If you choose to use a .env
file in production:
-
Restrict file permissions:
This ensures only the file owner can read or write to it
-
Place it outside the web root:
Store the file in a location not accessible via the web server
-
Limit user access:
Only the application user should have access to the directory containing the .env
file
Alternative Approaches
According to Django's deployment checklist, here are some recommended approaches for managing secrets:
1. Using System Environment Variables
Instead of a .env
file, set environment variables directly in your system:
import os
SECRET_KEY = os.environ["SECRET_KEY"]
You can set these in your server's startup scripts or systemd service files.
2. Using a Separate File for Secrets
with open("/etc/secret_key.txt") as f:
SECRET_KEY = f.read().strip()
This approach allows you to:
- Place sensitive files outside your application directory
- Apply strict file permissions
- Potentially use different backup/security policies for these files
3. Key Rotation Support
If you need to rotate keys, Django supports fallbacks:
import os
SECRET_KEY = os.environ["CURRENT_SECRET_KEY"]
SECRET_KEY_FALLBACKS = [
os.environ["OLD_SECRET_KEY"],
]
Conclusion
While a .env
file is acceptable for many production scenarios, it's not the most secure option if your server is compromised. For a DigitalOcean Droplet, using system environment variables or separate files with strict permissions provides a reasonable balance between security and simplicity.
If your application handles particularly sensitive data, you might want to reconsider more robust solutions like HashiCorp Vault in the future.