AWS Lambda: Environment Variables and Secrets
What you'll learn: How to securely configure Lambda functions using environment variables and integrate with AWS secrets management services.
The Core Idea
Environment variables let you store configuration data separately from your function code—think of them as labeled boxes where you keep settings your function needs to run. Instead of hardcoding values like database endpoints or API keys directly in your code, you store them as key-value pairs that Lambda makes available during execution.
However, sensitive data like passwords or API keys shouldn't live as plain environment variables. That's where AWS Secrets Manager and Systems Manager Parameter Store come in—they're secure vaults that encrypt and manage secrets, which your Lambda function can fetch at runtime.
How It Works
Environment Variables are set in your Lambda configuration and appear as system environment variables in your function's runtime. They're perfect for non-sensitive configuration like region names, feature flags, or endpoint URLs.
Secrets Manager stores sensitive credentials with automatic rotation support, encryption at rest, and fine-grained access control. Your function uses the AWS SDK to retrieve secrets when needed.
Parameter Store (part of Systems Manager) offers a simpler, cost-effective option for both plain configuration and encrypted secrets, though without automatic rotation.
Best Practices
- Use environment variables for non-sensitive configuration
- Store credentials, API keys, and passwords in Secrets Manager or Parameter Store
- Encrypt sensitive environment variables using AWS KMS
- Cache retrieved secrets in the execution context to avoid repeated API calls
- Use IAM roles to grant your Lambda function permission to access secrets
- Never log or expose secret values in your function output
Key Takeaway: Separate configuration from code using environment variables for settings, and always store sensitive credentials in Secrets Manager or Parameter Store with proper encryption and access controls.