Course contentsShow
← Security
Lesson 1953 of 3,05239. Cloud Security - Compute and ServerlessFree lesson

Environment Variable Security

Secure configuration through encrypted environment variables and avoid storing secrets directly in function configuration.

Environment Variable Security

What You'll Learn

You'll learn how to protect sensitive data in serverless functions by encrypting environment variables and avoiding direct secret storage in function configuration.

Why Environment Variables Are Risky

Environment variables in serverless functions are convenient for configuration—but they're also dangerously visible. When you set environment variables through cloud consoles or infrastructure-as-code, they're often stored in plaintext in the function's configuration metadata. Anyone with read permissions on the function can see them, including logs, error messages, and stack traces.

Think of it like writing your house alarm code on a sticky note attached to your front door. Sure, it's convenient for you—but it's equally convenient for attackers.

The Secure Approach

Encrypt at rest: Cloud providers offer native encryption for environment variables. AWS Lambda uses KMS keys to encrypt variables, Azure Functions uses Key Vault references, and GCP Cloud Functions supports Secret Manager integration. The function runtime automatically decrypts values when your code runs—but the stored configuration remains encrypted.

Never store secrets directly: Avoid putting API keys, database passwords, or tokens in environment variables at all. Instead, store a reference to a secret (like an ARN or secret ID) and fetch the actual credential at runtime using a secrets management service.

Limit visibility: Apply least-privilege IAM policies so only authorized roles can view or update function configuration. Even encrypted variables can be decrypted by anyone with sufficient permissions.

The Pattern

  1. Store secrets in a dedicated secret manager
  2. Grant your function's execution role permission to read specific secrets
  3. Reference the secret location (not the value) in environment variables if needed
  4. Fetch and decrypt secrets programmatically at startup

Key Takeaway: Encrypt environment variables using cloud-native KMS integration and prefer runtime secret retrieval over storing credentials directly in function configuration—treat your function metadata as semi-public.