Define Lambda Function Configuration Variables

Create Terraform variables for AWS Lambda function settings including runtime, memory, timeout, and environment variables.

Resource Configuration

Detailed Explanation

Lambda Function Configuration Variables

Lambda functions have several configurable parameters that benefit from variable definitions — especially when the same function module is used across environments with different resource allocations.

Variable Definitions

variable "lambda_runtime" {
  type        = string
  description = "Lambda function runtime"
  default     = "nodejs20.x"

  validation {
    condition     = contains(["nodejs18.x", "nodejs20.x", "python3.11", "python3.12", "go1.x", "java17", "java21"], var.lambda_runtime)
    error_message = "Must be a supported Lambda runtime."
  }
}

variable "lambda_memory" {
  type        = number
  description = "Memory allocated to the Lambda function in MB"
  default     = 256

  validation {
    condition     = var.lambda_memory >= 128 && var.lambda_memory <= 10240
    error_message = "Lambda memory must be between 128 MB and 10,240 MB."
  }
}

variable "lambda_timeout" {
  type        = number
  description = "Lambda function timeout in seconds"
  default     = 30

  validation {
    condition     = var.lambda_timeout >= 1 && var.lambda_timeout <= 900
    error_message = "Lambda timeout must be between 1 and 900 seconds."
  }
}

variable "lambda_env_vars" {
  type        = map(string)
  description = "Environment variables for the Lambda function"
  default     = {}
  sensitive   = true
}

Key Design Patterns

  1. Runtime validation: The contains() check limits to supported runtimes, preventing deployment errors
  2. Memory bounds: AWS Lambda supports 128 MB to 10,240 MB — the validation enforces these limits
  3. Timeout bounds: Lambda max timeout is 900 seconds (15 minutes)
  4. Sensitive env vars: Environment variables often contain API keys, so the entire map is marked sensitive

Environment-Specific Settings

# dev.tfvars
lambda_memory  = 128
lambda_timeout = 10
lambda_env_vars = {
  LOG_LEVEL = "debug"
  API_URL   = "https://api.dev.example.com"
}

# prod.tfvars
lambda_memory  = 1024
lambda_timeout = 60
lambda_env_vars = {
  LOG_LEVEL = "warn"
  API_URL   = "https://api.example.com"
}

Usage in Resource

resource "aws_lambda_function" "api" {
  function_name = "${var.project_name}-${var.environment}-api"
  runtime       = var.lambda_runtime
  memory_size   = var.lambda_memory
  timeout       = var.lambda_timeout

  environment {
    variables = var.lambda_env_vars
  }
}

Use Case

Serverless application modules where Lambda function configuration needs to differ between environments — more memory and longer timeouts in production, minimal in development.

Try It — Terraform Variable Generator

Open full tool