How to Use Environment Variables in AWS Lambda Functions
You can set environment variables for AWS Lambda functions in the AWS Management Console or via infrastructure as code. Inside your Lambda code, access these variables using
process.env.VARIABLE_NAME in Node.js or os.environ['VARIABLE_NAME'] in Python to configure behavior without changing code.Syntax
Environment variables in AWS Lambda are key-value pairs you define to store configuration data. You set them in the Lambda function settings or via deployment tools. In your code, you access them using language-specific methods.
- Node.js:
process.env.VARIABLE_NAME - Python:
os.environ['VARIABLE_NAME'] - Java:
System.getenv("VARIABLE_NAME")
javascript
exports.handler = async (event) => { const myVar = process.env.MY_VARIABLE; return `Value is: ${myVar}`; };
Example
This example shows how to set an environment variable named GREETING and access it in a Node.js Lambda function to return a greeting message.
javascript
exports.handler = async (event) => { const greeting = process.env.GREETING || 'Hello'; return `${greeting}, AWS Lambda!`; };
Output
"Hello, AWS Lambda!"
Common Pitfalls
- Forgetting to redeploy or update the Lambda function after changing environment variables.
- Trying to access environment variables that are not set, causing errors.
- Storing sensitive data in environment variables without encryption.
- Using incorrect syntax to access variables in your code.
javascript
/* Wrong: Accessing undefined variable without check */ exports.handler = async () => { return process.env.UNDEFINED_VAR.toUpperCase(); // Error if UNDEFINED_VAR is not set }; /* Right: Check if variable exists */ exports.handler = async () => { const val = process.env.UNDEFINED_VAR || 'default'; return val.toUpperCase(); };
Quick Reference
Remember these tips when using environment variables in Lambda:
- Set variables in the AWS Console under Configuration > Environment variables or via deployment tools.
- Access variables using your language's environment variable methods.
- Use default values in code to avoid errors if variables are missing.
- Encrypt sensitive variables using AWS KMS and enable encryption in Lambda settings.
Key Takeaways
Set environment variables in Lambda configuration to separate code from settings.
Access variables in code using language-specific environment variable methods.
Always provide default values or checks to avoid runtime errors.
Encrypt sensitive environment variables using AWS KMS for security.
Update and redeploy your Lambda function after changing environment variables.