Skip to content

Lambda Environment Variables — Configuration Management

DodaTech Updated 2026-06-28 5 min read

In this tutorial, you will learn about Lambda Environment Variables. We cover key concepts, practical examples, and best practices to help you master this topic.

AWS Lambda environment variables let you pass configuration to your function code without modifying the deployment package, supporting separate settings per function alias.

What You'll Learn

By the end of this lesson you will understand how to set and use Lambda environment variables, manage secrets securely, handle different environments, and use AWS Systems Manager for advanced configuration.

Why It Matters

Hardcoding configuration values in code requires redeployment for every change. Environment variables decouple configuration from code, making functions portable across environments and enabling configuration changes without code updates.

Real-World Use

DodaZIP's Lambda function for subscription management uses environment variables for the Stripe secret key, DynamoDB table name, and SNS topic ARN -- the same code runs in dev, staging, and production with different configuration values.

flowchart LR
    subgraph "Lambda Function"
        C[Code] -->|reads| EV[Environment Variables]
        EV --> S[DynamoDB Table Name]
        EV --> K[Stripe Secret Key]
        EV --> T[SNS Topic ARN]
    end
    subgraph "Sources"
        SSM[AWS Secrets Manager] --> K
        PARAM[SSM Parameter Store] --> S
        ENV[Inline Config] --> T
    end
    style EV fill:#f90,color:#fff

Setting and Using Environment Variables

Environment variables are key-value pairs set in the Lambda configuration. They are accessible via os.environ in Python or Process.env in Node.js.

# env_vars.py
# Using environment variables in Lambda

import os
import json

def lambda_handler(event, context):
    table_name = os.environ.get("TABLE_NAME", "default-table")
    stage = os.environ.get("STAGE", "dev")
    log_level = os.environ.get("LOG_LEVEL", "INFO")
    region = os.environ.get("AWS_REGION", "us-east-1")
    
    print(f"Environment: {stage}")
    print(f"Table: {table_name}")
    print(f"Log level: {log_level}")
    print(f"Region: {region}")
    
    return {
        "statusCode": 200,
        "body": json.dumps({
            "table": table_name,
            "stage": stage,
            "region": region
        })
    }

result = lambda_handler({}, None)
print(f"Response: {result}")

Expected output:

Environment: dev
Table: default-table
Log level: INFO
Region: us-east-1
Response: {'statusCode': 200, 'body': '{"table": "default-table", "stage": "dev", "region": "us-east-1"}'}

Managing Secrets Securely

Never store secrets like API keys or database passwords directly in environment variables visible in the console. Use AWS Secrets Manager or SSM Parameter Store with secure strings.

# secrets_manager.py
# Retrieving secrets securely

import json
import os

def get_secret(secret_name):
    """Simulate retrieving a secret from AWS Secrets Manager."""
    secrets = {
        "prod/stripe/key": "sk_live_abc123...",
        "prod/db/password": "encrypted-password-456"
    }
    secret = secrets.get(secret_name, "secret-not-found")
    print(f"[Secrets Manager] Retrieved {secret_name}")
    return secret

def lambda_handler(event, context):
    secret_name = os.environ.get("SECRET_NAME", "prod/stripe/key")
    api_key = get_secret(secret_name)
    
    # Never log the actual secret
    print(f"Using secret: {secret_name}")
    masked = api_key[:6] + "..." if api_key else "none"
    print(f"Secret value (masked): {masked}")
    
    return {
        "statusCode": 200,
        "body": json.dumps({"secret_configured": bool(api_key)})
    }

result = lambda_handler({}, None)

Expected output:

[Secrets Manager] Retrieved prod/stripe/key
Using secret: prod/stripe/key
Secret value (masked): sk_liv...

Environment-Specific Configuration

Use function aliases (dev, staging, prod) to attach different environment variables to the same function version.

# env_configs.py
# Multi-environment configuration

def get_config_for_alias(alias):
    configs = {
        "dev": {
            "TABLE_NAME": "users-dev",
            "LOG_LEVEL": "DEBUG",
            "API_URL": "http://localhost:3000"
        },
        "staging": {
            "TABLE_NAME": "users-staging",
            "LOG_LEVEL": "INFO",
            "API_URL": "https://staging.example.com"
        },
        "prod": {
            "TABLE_NAME": "users-prod",
            "LOG_LEVEL": "WARNING",
            "API_URL": "https://api.example.com"
        }
    }
    return configs.get(alias, configs["dev"])

def print_config(alias):
    config = get_config_for_alias(alias)
    print(f"--- {alias.upper()} Configuration ---")
    for key, value in config.items():
        print(f"  {key}: {value}")

print_config("dev")
print_config("staging")
print_config("prod")

Expected output:

--- DEV Configuration ---
  TABLE_NAME: users-dev
  LOG_LEVEL: DEBUG
  API_URL: http://localhost:3000
--- STAGING Configuration ---
  TABLE_NAME: users-staging
  LOG_LEVEL: INFO
  API_URL: https://staging.example.com
--- PROD Configuration ---
  TABLE_NAME: users-prod
  LOG_LEVEL: WARNING
  API_URL: https://api.example.com

Reserved Environment Variables

Lambda provides reserved environment variables that are automatically set: AWS_REGION, AWS_LAMBDA_FUNCTION_NAME, AWS_LAMBDA_FUNCTION_VERSION, AWS_LAMBDA_LOG_GROUP_NAME, AWS_LAMBDA_LOG_STREAM_NAME.

# reserved_vars.py
# Reserved Lambda environment variables

def lambda_handler(event, context):
    reserved = {
        "AWS_REGION": os.environ.get("AWS_REGION", "us-east-1"),
        "AWS_LAMBDA_FUNCTION_NAME": context.function_name,
        "AWS_LAMBDA_FUNCTION_VERSION": context.function_version,
        "AWS_LAMBDA_LOG_GROUP_NAME": context.log_group_name,
        "AWS_LAMBDA_LOG_STREAM_NAME": context.log_stream_name,
        "AWS_EXECUTION_ENV": os.environ.get("AWS_EXECUTION_ENV", "AWS_Lambda_python3.9"),
    }
    
    for key, value in reserved.items():
        print(f"{key}: {value}")

import os
class MockContext:
    function_name = "my-function"
    function_version = "$LATEST"
    log_group_name = "/aws/lambda/my-function"
    log_stream_name = "2026/06/28/[$LATEST]abc123"

lambda_handler({}, MockContext())

Common Mistakes

  1. Storing secrets as plain-text environment variables: Anyone with Lambda console access can see plain-text env vars. Use Secrets Manager with IAM policies.

  2. Not encrypting sensitive values: Lambda supports KMS encryption for environment variables. Enable it for production secrets.

  3. Hardcoding environment names in code: Use environment variables to determine the current environment rather than checking for variable existence.

  4. Oversharing environment variables across functions: Each function should have only the environment variables it needs. Use separate IAM roles for isolation.

  5. Forgetting that env vars count toward the 4KB limit: Total environment variable size cannot exceed 4KB. Use configuration files in layers for larger configs.

Practice Questions

  1. How do you access environment variables in a Python Lambda function? Using os.environ.get("KEY", "default") to read the variable with an optional fallback value.

  2. What is the maximum size for Lambda environment variables? 4KB total for all environment variables combined.

  3. How should you store database passwords for Lambda? Use AWS Secrets Manager with IAM permissions to retrieve the secret at runtime.

  4. Can you have different environment variables for different function versions? Yes, using function aliases. Each alias can have its own environment variable overrides.

  5. Challenge: Design a configuration system for a Lambda application that reads defaults from environment variables, overrides from a config file in a layer, and secrets from Secrets Manager.

FAQ

Are Lambda environment variables encrypted?

They are encrypted at rest by default using AWS KMS. You can provide a custom KMS key for additional control.

Can I update environment variables without redeploying?

Yes. Update the function configuration in the console, CLI, or SDK. The changes take effect on the next invocation.

Do environment variables persist across warm starts?

Yes. Once set, the same values are available for all invocations using that execution environment.

Can I use environment variables for feature flags?

Yes. Feature flags are a common use case for environment variables, allowing behavior changes without code deployment.

How do I handle sensitive configuration in environment variables?

Enable KMS encryption on the environment variables and restrict IAM access to decrypt only for authorized roles.

Mini Project

Create a Lambda function that reads configuration from environment variables, retrieves a database password from Secrets Manager, and connects to the appropriate database based on the STAGE variable.

import json
import os

def get_db_connection():
    stage = os.environ.get("STAGE", "dev")
    host = os.environ.get(f"DB_HOST_{stage.upper()}", "localhost")
    port = os.environ.get(f"DB_PORT_{stage.upper()}", "5432")
    db_name = os.environ.get(f"DB_NAME_{stage.upper()}", "app_dev")
    
    print(f"Connecting to {host}:{port}/{db_name} for {stage} environment")
    return {"connected": True, "host": host, "port": port, "database": db_name}

def lambda_handler(event, context):
    connection = get_db_connection()
    return {"statusCode": 200, "body": json.dumps(connection)}

os.environ["STAGE"] = "staging"
os.environ["DB_HOST_STAGING"] = "staging-db.example.com"
os.environ["DB_PORT_STAGING"] = "5432"
os.environ["DB_NAME_STAGING"] = "app_staging"

print(json.dumps(lambda_handler({}, None)))

What's Next

Next: Lambda Event Sources for triggering functions from AWS services.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro