Secrets and Environment Variables in Functions
What you'll learn: How to securely manage credentials and sensitive data in serverless functions without hardcoding or exposing them.
The Problem with Environment Variables
In serverless functions, environment variables seem like a convenient place to store API keys, database passwords, and other secrets. But here's the catch: they're visible in plaintext to anyone with console access, stored in deployment configurations, and often logged during debugging. It's like writing your house key code on a sticky note attached to your front door.
The Secure Pattern: Secret Managers
Instead of embedding secrets in environment variables, use dedicated secret managers like AWS Secrets Manager, Azure Key Vault, or GCP Secret Manager. Think of these as secure vaults that your function accesses at runtime rather than configuration time.
Here's the workflow:
- Store secrets in the secret manager (encrypted at rest)
- Grant your function's IAM role permission to retrieve specific secrets
- Retrieve secrets at runtime when your function executes
- Optionally cache secrets in memory for the function's lifetime to reduce API calls
Why Runtime Retrieval Matters
When you retrieve secrets at runtime:
- Secrets never appear in deployment artifacts or console displays
- You can rotate secrets without redeploying functions
- Access is audited through cloud logging
- Principle of least privilege applies—functions only get what they explicitly request
The Middle Ground: Encrypted Environment Variables
If you must use environment variables (for legacy reasons), encrypt them with your cloud provider's KMS. Your function decrypts them at startup—better than plaintext, but still inferior to dedicated secret managers.
Key Takeaway: Never store secrets in plaintext environment variables in serverless functions; instead, use cloud secret managers with runtime retrieval and proper IAM controls for secure, auditable, and rotatable secret management.