Secrets in Environment Variables
You'll learn how environment variables are commonly used to store secrets, and why this approach has important limitations you must understand.
The Basic Idea
Environment variables offer a straightforward way to keep secrets out of your source code. Instead of hardcoding a database password in your application, you store it in an environment variable like DATABASE_PASSWORD, then read it at runtime. This separates sensitive data from your codebase, which is a significant improvement over hardcoding.
Many platforms (cloud providers, container orchestrators, CI/CD systems) make it easy to inject environment variables into your application's runtime environment. This convenience has made them a popular choice for externalizing secrets.
The Limitations
While better than hardcoding, environment variables have real security weaknesses:
Exposure through process listings: On many systems, environment variables are visible to other processes. Commands like ps -e on Linux can reveal them to anyone with system access.
Logging and error reports: Applications often dump environment variables into logs, crash reports, or debugging output—accidentally exposing secrets.
Child process inheritance: When your application spawns subprocesses, they typically inherit all environment variables, widening the exposure surface.
Limited access control: You can't easily restrict which parts of your application can read which environment variables.
When It's Acceptable
Environment variables work reasonably well for:
- Local development secrets (low stakes)
- Non-critical services in controlled environments
- As a stepping stone toward dedicated secret management
Key Takeaway: Environment variables externalize secrets from code, but they're visible to the entire process and can leak through logs, making them a basic solution that's often insufficient for production systems handling sensitive data.