Environment Variables in AWS Lambda

Environment variables are a powerful way to manage configurations dynamically in AWS Lambda. In this blog, we'll cover:

  • How to set up environment variables in AWS Lambda.
  • Accessing and using them in your function.
  • Practical use cases and best practices.

What are Environment Variables?

Environment variables are key-value pairs accessible within the execution environment of your Lambda function. They allow dynamic configuration without modifying the code, making it easier to adapt to different environments.

Step-by-Step Guide

1. Create a Lambda Function

Start with a simple Python function:

import json
import os

def lambda_handler(event, context):
    
    name = os.environ['myname']
    age = os.environ['age']
    response = f"my name is {name} and my age is {age}"
    
    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

2. Add Environment Variables

  1. Navigate to the Configuration tab of your Lambda function.
  2. Go to Environment variables and add the following key-value pairs:
    • Key: myname
    • Value: Saurav
    • Key: age
    • Value: 30
  3. Save the configuration.

3. Test Your Function

Deploy the function and trigger it via the AWS Management Console. The output should be:

"my name is Saurav and my age is 30"

Use Cases for Environment Variables

  1. Dynamic Configuration:

    • Use environment variables for database connection strings, API endpoints, or feature toggles.
  2. Multi-Environment Support:

    • Maintain separate configurations for development, staging, and production environments.
  3. Feature Toggles:

    • Dynamically enable or disable features without modifying code.

    Example:

    feature_toggle = os.getenv('ENABLE_FEATURE', 'false')
    if feature_toggle == 'true':
        # Execute feature-specific logic
    

Code Explanation

  1. Import Modules:

    • The os module allows access to environment variables.
    • The json module is used for formatting the response.
  2. Access Environment Variables:

    • Use os.environ['key'] to retrieve the value of a specific environment variable.
  3. Dynamic Response:

    • The function uses the retrieved variables to dynamically generate a response.

Best Practices for Environment Variables

  1. Do Not Store Secrets:

    • Avoid storing sensitive data such as API keys or passwords in environment variables. Use AWS Secrets Manager or AWS Parameter Store instead.
  2. Use Default Values:

    • Provide default values for optional variables to avoid runtime errors.

    Example:

    timeout = os.getenv('TIMEOUT', '30')  # Default to 30 if TIMEOUT is not set
    
  3. Environment-Specific Configuration:

    • Use different values for development, staging, and production environments to maintain isolation.

Pitfalls to Avoid

  • Hardcoding Environment Variable Keys:

    • Always define keys in a configuration file or documentation to avoid confusion.
  • Overusing Environment Variables:

    • Keep the number of environment variables manageable for easier maintenance.
  • Storing Secrets in Environment Variables:

    • Secrets should always be stored in a secure service like AWS Secrets Manager.

Real-Life Scenarios

  1. Database Configuration:

    • Use an environment variable to store the database connection string for dynamic updates.
  2. Feature Management:

    • Enable or disable features based on environment variables during runtime.
  3. Debugging Levels:

    • Set a DEBUG_LEVEL variable to control logging verbosity.

Code Example

Here’s the final code snippet:

import json
import os

def lambda_handler(event, context):
    
    name = os.environ['myname']  # Retrieve 'myname' from environment variables
    age = os.environ['age']      # Retrieve 'age' from environment variables
    response = f"my name is {name} and my age is {age}"
    
    return {
        'statusCode': 200,
        'body': json.dumps(response)
    }

Environment variables are an essential feature for managing configurations in AWS Lambda. By following the best practices mentioned, you can build scalable and maintainable serverless applications while avoiding common pitfalls.

For more tutorials and insights, visit learning-ocean.com. Stay updated with the latest in AWS Lambda and serverless technologies!