Course contentsShow
← Cloud and Infrastructure
Lesson 477 of 2,9899. Serverless ComputeFree lesson

Environment Variables in Functions

Using environment variables to configure function behavior without changing code across different environments.

Environment Variables in Functions

What you'll learn: How to use environment variables to control your serverless functions' behavior across different environments without editing code.

The Core Idea

Environment variables are key-value pairs that you set outside your function's code but that your function can read at runtime. Think of them like labeled dials on a machine: you can adjust the settings without opening up and rewiring the machine itself.

When you deploy a function to development, staging, or production, you often need different configurations—database connection strings, API keys, feature flags, or service endpoints. Instead of maintaining separate code files or hardcoding these values, you inject them as environment variables.

How It Works in Practice

When you configure your function through your cloud provider's console or CLI, you define environment variables like:

DATABASE_URL=prod-db.example.com
API_TIMEOUT=5000
DEBUG_MODE=false

Inside your function code, you read these values from the runtime environment:

import os

def handler(event, context):
    db_url = os.environ['DATABASE_URL']
    timeout = int(os.environ.get('API_TIMEOUT', '3000'))
    # Use these variables to configure behavior

Why This Matters

Environment variables separate configuration from code. Your function code stays identical across all environments. Only the environment variables change. This makes deployments safer, secrets more secure (no hardcoded passwords!), and testing easier—you can quickly switch configurations without redeploying code.

Environment variables are set when your function starts (during cold start), so they're available immediately and don't require external calls to fetch configuration.

Key Takeaway: Environment variables let you configure serverless functions dynamically per environment, keeping your code portable and your secrets out of source control.