Lambda Environment Variables
In Lambda, you can pass configuration values such as database endpoints, API keys, and flags to a function as environment variables. Environment variables let you switch configurations without modifying code, making it easy to manage separate development and production settings. For sensitive information (passwords, tokens, etc.), values are commonly stored in SSM Parameter Store or Secrets Manager and retrieved at runtime rather than stored in plain text as environment variables. Environment variables are configured with the aws lambda update-function-configuration --environment command.
Syntax
# -----------------------------------------------
# aws lambda update-function-configuration --environment
# -----------------------------------------------
# aws lambda update-function-configuration \
# --function-name {function-name} \
# --environment "Variables={KEY=value,KEY=value,...}"
# → Sets or overwrites the environment variables of a Lambda function
# All existing environment variables are overwritten (not a partial update)
# Example: aws lambda update-function-configuration \
# --function-name goku-power-func \
# --environment "Variables={ENV=production,APP_NAME=goku-service}"
# aws lambda get-function-configuration \
# --function-name {function-name} \
# --query 'Environment'
# → Lists the currently configured environment variables
# Example: aws lambda get-function-configuration \
# --function-name goku-power-func \
# --query 'Environment'
# -----------------------------------------------
# SSM Parameter Store operations
# -----------------------------------------------
# aws ssm put-parameter \
# --name {parameter-name} \
# --value {value} \
# --type {String|SecureString|StringList}
# → Saves a parameter to Parameter Store
# SecureString is encrypted with KMS
# Example: aws ssm put-parameter \
# --name "/goku/db_password" \
# --value "kamehameha123" \
# --type SecureString
# aws ssm get-parameter \
# --name {parameter-name} \
# --with-decryption
# → Retrieves a parameter from Parameter Store
# Adding --with-decryption decrypts SecureString values
# Example: aws ssm get-parameter \
# --name "/goku/db_password" \
# --with-decryption
# -----------------------------------------------
# Secrets Manager operations
# -----------------------------------------------
# aws secretsmanager create-secret \
# --name {secret-name} \
# --secret-string {value}
# → Creates a secret in Secrets Manager
# Secrets are often stored as JSON strings
# Example: aws secretsmanager create-secret \
# --name "vegeta/db-credentials" \
# --secret-string '{"username":"vegeta","password":"elitewarrior456"}'
# aws secretsmanager get-secret-value \
# --secret-id {secret-name-or-ARN}
# → Retrieves the value of a secret from Secrets Manager
# Example: aws secretsmanager get-secret-value \
# --secret-id "vegeta/db-credentials"
Reference
| Command / Operation | Description |
|---|---|
aws lambda update-function-configuration --environment | Sets environment variables for a Lambda function. Specify in Variables={KEY=value,...} format. All existing environment variables are overwritten. |
aws lambda get-function-configuration --query 'Environment' | Retrieves the list of environment variables configured for a function. |
aws ssm put-parameter --type String | Saves a plain-text parameter to SSM Parameter Store. Used for non-sensitive values such as configuration values and endpoint URLs. |
aws ssm put-parameter --type SecureString | Saves a KMS-encrypted parameter to SSM Parameter Store. Used for sensitive values such as passwords and API keys. |
aws ssm get-parameter --with-decryption | Retrieves a parameter from Parameter Store. Adding --with-decryption automatically decrypts SecureString values. |
aws ssm get-parameters-by-path | Retrieves all parameters under a specified path prefix in bulk. Useful when managing parameters in a path hierarchy such as /goku/. |
aws secretsmanager create-secret | Creates a secret in Secrets Manager. Usernames and passwords are often stored together in JSON format. |
aws secretsmanager get-secret-value | Retrieves the value of a secret from Secrets Manager. Specify the secret name or ARN in --secret-id. |
aws secretsmanager rotate-secret | Rotates (automatically updates) a secret in Secrets Manager. Used in combination with a Lambda rotation function. |
| Environment variable encryption | Lambda environment variables are encrypted at rest using the AWS managed key (aws/lambda) or a custom KMS key. They are also protected in transit with TLS. |
| Parameter Store vs. Secrets Manager | Parameter Store has a free tier (Standard Tier) and is suited for managing configuration values. Secrets Manager supports automatic rotation and is suited for managing credentials. |
Sample Code
# -----------------------------------------------
# Set environment variables for Goku's combat
# power calculation service (goku-power-func)
# Configure ENV, DB_HOST, APP_NAME, and more
# -----------------------------------------------
# Set environment variables (all existing variables are overwritten)
aws lambda update-function-configuration \
--function-name goku-power-func \
--environment "Variables={
ENV=production,
APP_NAME=goku-power-service,
DB_HOST=goku-db.ap-northeast-1.rds.amazonaws.com,
DB_PORT=5432,
LOG_LEVEL=info
}" \
--region ap-northeast-1
# Verify the configured environment variables
aws lambda get-function-configuration \
--function-name goku-power-func \
--region ap-northeast-1 \
--query 'Environment.Variables'
$ aws lambda update-function-configuration \
> --function-name goku-power-func \
> --environment "Variables={ENV=production,APP_NAME=goku-power-service,DB_HOST=goku-db.ap-northeast-1.rds.amazonaws.com,DB_PORT=5432,LOG_LEVEL=info}" \
> --region ap-northeast-1
{
"FunctionName": "goku-power-func",
"FunctionArn": "arn:aws:lambda:ap-northeast-1:111122223333:function:goku-power-func",
"Runtime": "python3.12",
"Environment": {
"Variables": {
"ENV": "production",
"APP_NAME": "goku-power-service",
"DB_HOST": "goku-db.ap-northeast-1.rds.amazonaws.com",
"DB_PORT": "5432",
"LOG_LEVEL": "info"
}
},
"LastModified": "2026-03-26T09:00:00.000+0000"
}
$ aws lambda get-function-configuration \
> --function-name goku-power-func \
> --region ap-northeast-1 \
> --query 'Environment.Variables'
{
"ENV": "production",
"APP_NAME": "goku-power-service",
"DB_HOST": "goku-db.ap-northeast-1.rds.amazonaws.com",
"DB_PORT": "5432",
"LOG_LEVEL": "info"
}
# -----------------------------------------------
# Store the API key and DB password used by
# Vegeta's service in SSM Parameter Store
# Store sensitive values as SecureString,
# non-sensitive as String
# -----------------------------------------------
# Save a non-sensitive parameter (String)
aws ssm put-parameter \
--name "/vegeta/api_endpoint" \
--value "https://api.vegeta-elite.example.com/v1" \
--type String \
--description "API endpoint for Vegeta's service" \
--region ap-northeast-1
# Save sensitive parameters (SecureString)
aws ssm put-parameter \
--name "/vegeta/api_key" \
--value "vegeta-super-elite-apikey-9000" \
--type SecureString \
--description "API key for Vegeta's service (KMS encrypted)" \
--region ap-northeast-1
aws ssm put-parameter \
--name "/vegeta/db_password" \
--value "elite-warrior-pass-456" \
--type SecureString \
--description "DB password for Vegeta" \
--region ap-northeast-1
# Retrieve the non-sensitive parameter
aws ssm get-parameter \
--name "/vegeta/api_endpoint" \
--region ap-northeast-1
# Retrieve and decrypt the SecureString
aws ssm get-parameter \
--name "/vegeta/api_key" \
--with-decryption \
--region ap-northeast-1
# Retrieve all parameters under /vegeta/ in bulk
aws ssm get-parameters-by-path \
--path "/vegeta/" \
--with-decryption \
--region ap-northeast-1 \
--query 'Parameters[*].{Name:Name,Value:Value}'
$ aws ssm put-parameter \
> --name "/vegeta/api_endpoint" \
> --value "https://api.vegeta-elite.example.com/v1" \
> --type String \
> --region ap-northeast-1
{
"Version": 1,
"Tier": "Standard"
}
$ aws ssm put-parameter \
> --name "/vegeta/api_key" \
> --value "vegeta-super-elite-apikey-9000" \
> --type SecureString \
> --region ap-northeast-1
{
"Version": 1,
"Tier": "Standard"
}
$ aws ssm get-parameter \
> --name "/vegeta/api_key" \
> --with-decryption \
> --region ap-northeast-1
{
"Parameter": {
"Name": "/vegeta/api_key",
"Type": "SecureString",
"Value": "vegeta-super-elite-apikey-9000",
"Version": 1,
"LastModifiedDate": "2026-03-26T09:10:00.000+0000",
"ARN": "arn:aws:ssm:ap-northeast-1:111122223333:parameter/vegeta/api_key",
"DataType": "text"
}
}
$ aws ssm get-parameters-by-path \
> --path "/vegeta/" \
> --with-decryption \
> --region ap-northeast-1 \
> --query 'Parameters[*].{Name:Name,Value:Value}'
[
{
"Name": "/vegeta/api_endpoint",
"Value": "https://api.vegeta-elite.example.com/v1"
},
{
"Name": "/vegeta/api_key",
"Value": "vegeta-super-elite-apikey-9000"
},
{
"Name": "/vegeta/db_password",
"Value": "elite-warrior-pass-456"
}
]
# -----------------------------------------------
# Store the DB credentials used by Piccolo's
# Lambda function in Secrets Manager as JSON
# and configure automatic rotation
# -----------------------------------------------
# Create DB credentials in JSON format in Secrets Manager
aws secretsmanager create-secret \
--name "piccolo/rds-credentials" \
--description "RDS credentials for Piccolo's service" \
--secret-string '{"username":"piccolo","password":"namekian-secret-789","engine":"postgres","host":"piccolo-db.ap-northeast-1.rds.amazonaws.com","port":5432,"dbname":"piccolo_prod"}' \
--region ap-northeast-1
# Retrieve the secret value
aws secretsmanager get-secret-value \
--secret-id "piccolo/rds-credentials" \
--region ap-northeast-1 \
--query 'SecretString'
# Update the secret value (e.g., when changing the password)
aws secretsmanager put-secret-value \
--secret-id "piccolo/rds-credentials" \
--secret-string '{"username":"piccolo","password":"namekian-new-secret-321","engine":"postgres","host":"piccolo-db.ap-northeast-1.rds.amazonaws.com","port":5432,"dbname":"piccolo_prod"}' \
--region ap-northeast-1
# List all secrets
aws secretsmanager list-secrets \
--region ap-northeast-1 \
--query 'SecretList[*].{Name:Name,ARN:ARN,LastChanged:LastChangedDate}'
$ aws secretsmanager create-secret \
> --name "piccolo/rds-credentials" \
> --description "RDS credentials for Piccolo's service" \
> --secret-string '{"username":"piccolo","password":"namekian-secret-789",...}' \
> --region ap-northeast-1
{
"ARN": "arn:aws:secretsmanager:ap-northeast-1:111122223333:secret:piccolo/rds-credentials-AbCxYz",
"Name": "piccolo/rds-credentials",
"VersionId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
}
$ aws secretsmanager get-secret-value \
> --secret-id "piccolo/rds-credentials" \
> --region ap-northeast-1 \
> --query 'SecretString'
"{\"username\":\"piccolo\",\"password\":\"namekian-secret-789\",\"engine\":\"postgres\",\"host\":\"piccolo-db.ap-northeast-1.rds.amazonaws.com\",\"port\":5432,\"dbname\":\"piccolo_prod\"}"
$ aws secretsmanager list-secrets \
> --region ap-northeast-1 \
> --query 'SecretList[*].{Name:Name,ARN:ARN,LastChanged:LastChangedDate}'
[
{
"Name": "piccolo/rds-credentials",
"ARN": "arn:aws:secretsmanager:ap-northeast-1:111122223333:secret:piccolo/rds-credentials-AbCxYz",
"LastChanged": "2026-03-26T09:20:00.000+0000"
}
]
# ----------------------------------------------- # Sample code for Lambda functions (Python) used # by Bulma and Trunks to retrieve configuration # values and credentials at runtime from # SSM Parameter Store and Secrets Manager # Requires ssm:GetParameter and # secretsmanager:GetSecretValue IAM permissions # ----------------------------------------------- # Lambda function code: bulma_config_handler.py
# -----------------------------------------------
# bulma_config_handler.py
# Lambda function to retrieve Bulma's configuration
# Fetches values at runtime from SSM Parameter Store
# and Secrets Manager
# -----------------------------------------------
import json
import os
import boto3
# Initializing boto3 clients outside the handler reduces cold start overhead
ssm_client = boto3.client('ssm', region_name='ap-northeast-1')
secrets_client = boto3.client('secretsmanager', region_name='ap-northeast-1')
def get_ssm_parameter(param_name, with_decryption=True):
"""Retrieves a parameter from SSM Parameter Store."""
response = ssm_client.get_parameter(
Name=param_name,
WithDecryption=with_decryption
)
return response['Parameter']['Value']
def get_secret(secret_id):
"""Retrieves a secret from Secrets Manager and returns it as a dict."""
response = secrets_client.get_secret_value(SecretId=secret_id)
secret_string = response['SecretString']
# Convert the JSON-formatted secret string to a dict
return json.loads(secret_string)
def lambda_handler(event, context):
# -----------------------------------------------
# Retrieve Bulma's service configuration from SSM Parameter Store
# -----------------------------------------------
# Retrieve a non-sensitive configuration value (String)
api_endpoint = get_ssm_parameter('/bulma/api_endpoint', with_decryption=False)
# Retrieve the sensitive API key (SecureString)
api_key = get_ssm_parameter('/bulma/api_key', with_decryption=True)
# -----------------------------------------------
# Retrieve Trunks' DB credentials from Secrets Manager
# -----------------------------------------------
db_credentials = get_secret('trunks/rds-credentials')
# Build the database connection string from the retrieved credentials
db_url = "postgresql://{username}:{password}@{host}:{port}/{dbname}".format(
username=db_credentials['username'],
password=db_credentials['password'],
host=db_credentials['host'],
port=db_credentials['port'],
dbname=db_credentials['dbname']
)
# Retrieve non-sensitive configuration from environment variables
env = os.environ.get('ENV', 'development')
log_level = os.environ.get('LOG_LEVEL', 'info')
return {
'statusCode': 200,
'body': json.dumps({
'message': 'Retrieved Bulma configuration successfully',
'env': env,
'log_level': log_level,
'api_endpoint': api_endpoint,
# api_key and db_url are used in processing but not included in the response
})
}
$ aws lambda invoke \
> --function-name bulma-config-func \
> --region ap-northeast-1 \
> response.json && cat response.json
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
{
"statusCode": 200,
"body": "{\"message\": \"Retrieved Bulma configuration successfully\", \"env\": \"production\", \"log_level\": \"info\", \"api_endpoint\": \"https://api.bulma-capsule.example.com/v1\"}"
}
Common Mistakes
Mistake 1: Path parameter name does not start with /, causing NotFound errors
When using path-style (hierarchical) parameter names in SSM Parameter Store, the leading / is required. Parameters created without a leading / cannot be retrieved with get-parameters-by-path.
# Less common approach: saving a path-style parameter without the leading / aws ssm put-parameter \ --name "vegeta/api_key" \ --value "vegeta-super-elite-apikey-9000" \ --type SecureString # Trying to retrieve by path returns nothing aws ssm get-parameters-by-path \ --path "/vegeta/" # → No parameters found (the parameter does not exist under /vegeta/)
When managing parameters in path style, register the parameter name starting with /, such as /vegeta/api_key.
# Common approach: start the parameter name with /
aws ssm put-parameter \
--name "/vegeta/api_key" \
--value "vegeta-super-elite-apikey-9000" \
--type SecureString
aws ssm get-parameters-by-path \
--path "/vegeta/" \
--with-decryption \
--query 'Parameters[*].{Name:Name,Value:Value}'
Mistake 2: Using the Secrets Manager JSON value directly without parsing it
SecretString from Secrets Manager is returned as a JSON string. Trying to use it directly as a dictionary for DB connection info will cause an error.
import boto3
secrets_client = boto3.client('secretsmanager', region_name='ap-northeast-1')
def lambda_handler(event, context):
response = secrets_client.get_secret_value(
SecretId='piccolo/rds-credentials'
)
# Less common approach: SecretString is still a JSON string and cannot be used directly
db_creds = response['SecretString']
db_host = db_creds['host'] # → TypeError: string indices must be integers
Use json.loads() to convert the string to a dict before accessing its values.
import json
import boto3
secrets_client = boto3.client('secretsmanager', region_name='ap-northeast-1')
def lambda_handler(event, context):
response = secrets_client.get_secret_value(
SecretId='piccolo/rds-credentials'
)
# Common approach: convert to dict with json.loads() before use
db_creds = json.loads(response['SecretString'])
db_host = db_creds['host']
db_password = db_creds['password']
Mistake 3: Storing sensitive information in environment variables as plain text
Lambda environment variables can be viewed in plain text from the management console. Storing sensitive values such as passwords, API keys, and tokens directly in environment variables risks exposure through console access or CloudFormation template logs.
# Less common approach: storing sensitive information in environment variables as plain text
aws lambda update-function-configuration \
--function-name goku-power-func \
--environment "Variables={
DB_PASSWORD=kamehameha123,
API_KEY=goku-secret-apikey-9999
}"
Store sensitive information in SSM Parameter Store (SecureString) or Secrets Manager, grant the Lambda execution role permission to retrieve them, and fetch the values at runtime.
# Common approach: store sensitive information in Parameter Store as SecureString
aws ssm put-parameter \
--name "/goku/db_password" \
--value "kamehameha123" \
--type SecureString
aws ssm put-parameter \
--name "/goku/api_key" \
--value "goku-secret-apikey-9999" \
--type SecureString
# Pass only the non-sensitive parameter paths as environment variables
aws lambda update-function-configuration \
--function-name goku-power-func \
--environment "Variables={
ENV=production,
SSM_DB_PASSWORD_PATH=/goku/db_password,
SSM_API_KEY_PATH=/goku/api_key
}"
Summary
Lambda environment variables can be configured with aws lambda update-function-configuration --environment and accessed in Python functions via os.environ.get('KEY'). However, because environment variables can be viewed in plain text from the management console, sensitive values such as passwords, API keys, and tokens should not be stored directly as environment variables. Instead, store them in SSM Parameter Store or Secrets Manager and retrieve them at runtime. The SecureString type in SSM Parameter Store is encrypted with KMS and has a free tier (Standard Tier), making it cost-effective. Secrets Manager is paid ($0.40 per secret per month) but provides automatic rotation (aws secretsmanager rotate-secret), making it well-suited for automatically updating RDS passwords on a schedule. For a Lambda function to access SSM or Secrets Manager, its execution role must be granted the ssm:GetParameter or secretsmanager:GetSecretValue IAM permissions. For IAM role configuration, see IAM Roles and Policies. For creating Lambda functions, see Creating and Deploying Lambda Functions.
If you find any errors or copyright issues, please contact us.