You can use environment variables to adjust your function's behavior without updating code. An environment variable is a pair of strings that is stored in a function's version-specific configuration. The Lambda runtime makes environment variables available to your code and sets additional environment variables that contain information about the function and invocation request.
To increase security, we recommend that you use AWS Secrets Manager instead of environment variables to store database credentials and other sensitive information like API keys or authorization tokens. For more information, seeUse Secrets Manager secrets in Lambda functions.
Environment variables are not evaluated before the function invocation. Any value you define is considered a literal string and not expanded. Perform the variable evaluation in your function code.
You can configure environment variables in Lambda using the Lambda console, the AWS Command Line Interface (AWS CLI), AWS Serverless Application Model (AWS SAM), or using an AWS SDK.
You define environment variables on the unpublished version of your function. When you publish a version, the environment variables are locked for that version along with otherversion-specific configuration settings.
You create an environment variable for your function by defining a key and a value. Your function uses the name of the key to retrieve the value of the environment variable.
Open theFunctions page of the Lambda console.
Choose a function.
Choose theConfiguration tab, then chooseEnvironment variables.
UnderEnvironment variables, chooseEdit.
ChooseAdd environment variable.
Enter a key and value.
Keys start with a letter and are at least two characters.
Keys only contain letters, numbers, and the underscore character (_
).
Keys aren'treserved by Lambda.
The total size of all environment variables doesn't exceed 4 KB.
ChooseSave.
You can generate a list of environment variables in the Lambda code editor. This is a quick way to reference your environment variables while you code.
Choose theCode tab.
Scroll down to theENVIRONMENT VARIABLES section of the code editor. Existing environment variables are listed here:
To create new environment variables, choose the choose the plus sign ():
Environment variables remain encrypted when listed in the console code editor. If you enabled encryption helpers for encryption in transit, then those settings remain unchanged. For more information, seeSecuring Lambda environment variables.
The environment variables list is read-only and is available only on the Lambda console. This file is not included when you download the function's .zip file archive, and you can't add environment variables by uploading this file.
The following example sets two environment variables on a function namedmy-function
.
aws lambda update-function-configuration \ --function-namemy-function
\ --environment"Variables={BUCKET=amzn-s3-demo-bucket,KEY=file.txt}"
When you apply environment variables with theupdate-function-configuration
command, the entire contents of theVariables
structure is replaced. To retain existing environment variables when you add a new one, include all existing values in your request.
To get the current configuration, use theget-function-configuration
command.
aws lambda get-function-configuration \ --function-namemy-function
You should see the following output:
{ "FunctionName": "my-function", "FunctionArn": "arn:aws:lambda:us-east-2:111122223333:function:my-function", "Runtime": "nodejs22.x", "Role": "arn:aws:iam::111122223333:role/lambda-role", "Environment":{ "Variables":{ "BUCKET": "amzn-s3-demo-bucket", "KEY": "file.txt" } }, "RevisionId": "0894d3c1-2a3d-4d48-bf7f-abade99f3c15", ...}
You can pass the revision ID from the output ofget-function-configuration
as a parameter toupdate-function-configuration
. This ensures that the values don't change between when you read the configuration and when you update it.
To configure a function's encryption key, set theKMSKeyARN
option.
aws lambda update-function-configuration \ --function-namemy-function
\ --kms-key-arnarn:aws:kms:us-east-2:111122223333:key/055efbb4-xmpl-4336-ba9c-538c7d31f599
You can use theAWS Serverless Application Model to configure environment variables for your function. Update theEnvironment andVariables properties in yourtemplate.yaml
file and then runsam deploy.
AWSTemplateFormatVersion: '2010-09-09'Transform: AWS::Serverless-2016-10-31Description: An AWS Serverless Application Model template describing your function.Resources:my-function
: Type: AWS::Serverless::Function Properties: CodeUri: . Description: '' MemorySize: 128 Timeout: 120 Handler: index.handler Runtime: nodejs22.x Architectures: - x86_64 EphemeralStorage: Size: 10240 Environment: Variables:BUCKET: amzn-s3-demo-bucket
KEY: file.txt
# Other function properties...
To manage environment variables using an AWS SDK, use the following API operations.
To learn more, refer to theAWS SDK documentation for your preferred programming language.
You can use environment variables to customize function behavior in your test environment and production environment. For example, you can create two functions with the same code but different configurations. One function connects to a test database, and the other connects to a production database. In this situation, you use environment variables to pass the hostname and other connection details for the database to the function.
The following example shows how to define the database host and database name as environment variables.
If you want your test environment to generate more debug information than the production environment, you could set an environment variable to configure your test environment to use more verbose logging or more detailed tracing.
For example, in your test environment, you could set an environment variable with the keyLOG_LEVEL
and a value indicating a log level of debug or trace. In your Lambda function's code, you can then use this environment variable to set the log level.
The following code examples in Python and Node.js illustrate how you can achieve this. These examples assume your environment variable has a value ofDEBUG
in Python ordebug
in Node.js.
import osimport logging# Initialize the loggerlogger = logging.getLogger()# Get the log level from the environment variable and default to INFO if not setlog_level = os.environ.get('LOG_LEVEL', 'INFO')# Set the log levellogger.setLevel(log_level)def lambda_handler(event, context): # Produce some example log outputs logger.debug('This is a log with detailed debug information - shown only in test environment') logger.info('This is a log with standard information - shown in production and test environments')
This example uses thewinston
logging library. Use npm to add this library to your function's deployment package. For more information, seeCreating a .zip deployment package with dependencies.
import winston from 'winston';// Initialize the logger using the log level from environment variables, defaulting to INFO if not setconst logger = winston.createLogger({ level: process.env.LOG_LEVEL || 'info', format: winston.format.json(), transports: [new winston.transports.Console()]});export const handler = async (event) =>{ // Produce some example log outputs logger.debug('This is a log with detailed debug information - shown only in test environment'); logger.info('This is a log with standard information - shown in production and test environment'); };
To retrieve environment variables in your function code, use the standard method for your programming language.
let region = process.env.AWS_REGION
import os region = os.environ['AWS_REGION']
region = ENV["AWS_REGION"]
String region = System.getenv("AWS_REGION");
var region = os.Getenv("AWS_REGION")
string region = Environment.GetEnvironmentVariable("AWS_REGION");
$region = $env:AWS_REGION
Lambda stores environment variables securely by encrypting them at rest. You canconfigure Lambda to use a different encryption key, encrypt environment variable values on the client side, or set environment variables in an AWS CloudFormation template with AWS Secrets Manager.
Lambdaruntimes set several environment variables during initialization. Most of the environment variables provide information about the function or runtime. The keys for these environment variables arereserved and cannot be set in your function configuration.
_HANDLER
– The handler location configured on the function.
_X_AMZN_TRACE_ID
– TheX-Ray tracing header. This environment variable changes with each invocation.
This environment variable is not defined for OS-only runtimes (theprovided
runtime family). You can set_X_AMZN_TRACE_ID
for custom runtimes using theLambda-Runtime-Trace-Id
response header from theNext invocation.
For Java runtime versions 17 and later, this environment variable is not used. Instead, Lambda stores tracing information in thecom.amazonaws.xray.traceHeader
system property.
AWS_DEFAULT_REGION
– The default AWS Region where the Lambda function is executed.
AWS_REGION
– The AWS Region where the Lambda function is executed. If defined, this value overrides theAWS_DEFAULT_REGION
.
For more information about using the AWS Region environment variables with AWS SDKs, seeAWS Region in theAWS SDKs and Tools Reference Guide.
AWS_EXECUTION_ENV
– Theruntime identifier, prefixed byAWS_Lambda_
(for example,AWS_Lambda_java8
). This environment variable is not defined for OS-only runtimes (theprovided
runtime family).
AWS_LAMBDA_FUNCTION_NAME
– The name of the function.
AWS_LAMBDA_FUNCTION_MEMORY_SIZE
– The amount of memory available to the function in MB.
AWS_LAMBDA_FUNCTION_VERSION
– The version of the function being executed.
AWS_LAMBDA_INITIALIZATION_TYPE
– The initialization type of the function, which ison-demand
,provisioned-concurrency
, orsnap-start
. For information, see Configuring provisioned concurrency orImproving startup performance with Lambda SnapStart.
AWS_LAMBDA_LOG_GROUP_NAME
,AWS_LAMBDA_LOG_STREAM_NAME
– The name of the Amazon CloudWatch Logs group and stream for the function. TheAWS_LAMBDA_LOG_GROUP_NAME
andAWS_LAMBDA_LOG_STREAM_NAME
environment variables are not available in Lambda SnapStart functions.
AWS_ACCESS_KEY
,AWS_ACCESS_KEY_ID
,AWS_SECRET_ACCESS_KEY
,AWS_SESSION_TOKEN
– The access keys obtained from the function'sexecution role.
AWS_LAMBDA_RUNTIME_API
– (Custom runtime) The host and port of theruntime API.
LAMBDA_TASK_ROOT
– The path to your Lambda function code.
LAMBDA_RUNTIME_DIR
– The path to runtime libraries.
The following additional environment variables aren't reserved and can be extended in your function configuration.
LANG
– The locale of the runtime (en_US.UTF-8
).
PATH
– The execution path (/usr/local/bin:/usr/bin/:/bin:/opt/bin
).
LD_LIBRARY_PATH
– The system library path (/var/lang/lib:/lib64:/usr/lib64:$LAMBDA_RUNTIME_DIR:$LAMBDA_RUNTIME_DIR/lib:$LAMBDA_TASK_ROOT:$LAMBDA_TASK_ROOT/lib:/opt/lib
).
NODE_PATH
– (Node.js) The Node.js library path (/opt/nodejs/node12/node_modules/:/opt/nodejs/node_modules:$LAMBDA_RUNTIME_DIR/node_modules
).
PYTHONPATH
– (Python) The Python library path ($LAMBDA_RUNTIME_DIR
).
GEM_PATH
– (Ruby) The Ruby library path ($LAMBDA_TASK_ROOT/vendor/bundle/ruby/3.3.0:/opt/ruby/gems/3.3.0
).
AWS_XRAY_CONTEXT_MISSING
– For X-Ray tracing, Lambda sets this toLOG_ERROR
to avoid throwing runtime errors from the X-Ray SDK.
AWS_XRAY_DAEMON_ADDRESS
– For X-Ray tracing, the IP address and port of the X-Ray daemon.
AWS_LAMBDA_DOTNET_PREJIT
– (.NET) Set this variable to enable or disable .NET specific runtime optimizations. Values includealways
,never
, andprovisioned-concurrency
. For more information, seeConfiguring provisioned concurrency for a function.
TZ
– The environment's time zone (:UTC
). The execution environment uses NTP to synchronize the system clock.
The sample values shown reflect the latest runtimes. The presence of specific variables or their values can vary on earlier runtimes.