

# Working with Lambda environment variables
<a name="configuration-envvars"></a>

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.

**Note**  
To increase security, we recommend that you use Amazon Secrets Manager instead of environment variables to store database credentials and other sensitive information like API keys or authorization tokens. For more information, see [Use Secrets Manager secrets in Lambda functions](with-secrets-manager.md).

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.

## Creating Lambda environment variables
<a name="create-environment-variables"></a>

You can configure environment variables in Lambda using the Lambda console, the Amazon Command Line Interface (Amazon CLI), Amazon Serverless Application Model (Amazon SAM), or using an Amazon SDK.

------
#### [ Console ]

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 other [version-specific configuration settings](configuration-versions.md).

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.

**To set environment variables in the Lambda console**

1. Open the [Functions page](https://console.amazonaws.cn/lambda/home#/functions) of the Lambda console.

1. Choose a function.

1. Choose the **Configuration** tab, then choose **Environment variables**.

1. Under **Environment variables**, choose **Edit**.

1. Choose **Add environment variable**.

1. Enter a key and value.

**Requirements**
   + Keys start with a letter and are at least two characters.
   + Keys only contain letters, numbers, and the underscore character (`_`).
   + Keys aren't [reserved by Lambda](#configuration-envvars-runtime).
   + The total size of all environment variables doesn't exceed 4 KB.

1. Choose **Save**.

**To generate a list of environment variables in the console code editor**

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.

1. Choose the **Code** tab.

1. Scroll down to the **ENVIRONMENT VARIABLES** section of the code editor. Existing environment variables are listed here:  
![\[\]](http://docs.amazonaws.cn/en_us/lambda/latest/dg/images/env-var.png)

1. To create new environment variables, choose the choose the plus sign (![\[\]](http://docs.amazonaws.cn/en_us/lambda/latest/dg/images/add-plus.png)):  
![\[\]](http://docs.amazonaws.cn/en_us/lambda/latest/dg/images/create-env-var.png)

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, see [Securing Lambda environment variables](configuration-envvars-encryption.md).

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.

------
#### [ Amazon CLI ]

The following example sets two environment variables on a function named `my-function`.

```
aws lambda update-function-configuration \
  --function-name my-function \
  --environment "Variables={BUCKET=amzn-s3-demo-bucket,KEY=file.txt}"
```

When you apply environment variables with the `update-function-configuration` command, the entire contents of the `Variables` 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 the `get-function-configuration` command.

```
aws lambda get-function-configuration \
  --function-name my-function
```

You should see the following output:

```
{
    "FunctionName": "my-function",
    "FunctionArn": "arn:aws-cn:lambda:us-west-2:111122223333:function:my-function",
    "Runtime": "nodejs24.x",
    "Role": "arn:aws-cn: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 of `get-function-configuration` as a parameter to `update-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 the `KMSKeyARN` option.

```
aws lambda update-function-configuration \
  --function-name my-function \
  --kms-key-arn arn:aws-cn:kms:us-west-2:111122223333:key/055efbb4-xmpl-4336-ba9c-538c7d31f599
```

------
#### [ Amazon SAM ]

You can use the [Amazon Serverless Application Model](https://docs.amazonaws.cn//serverless-application-model/latest/developerguide/serverless-getting-started.html ) to configure environment variables for your function. Update the [Environment](https://docs.amazonaws.cn//serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-environment) and [Variables](https://docs.amazonaws.cn//AWSCloudFormation/latest/UserGuide/aws-properties-lambda-function-environment.html#cfn-lambda-function-environment-variables) properties in your `template.yaml` file and then run [sam deploy](https://docs.amazonaws.cn//serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-deploy.html).

**Example template.yaml**  

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: 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: nodejs24.x
      Architectures:
        - x86_64
      EphemeralStorage:
        Size: 10240
      Environment:
        Variables:
          BUCKET: amzn-s3-demo-bucket
          KEY: file.txt
      # Other function properties...
```

------
#### [ Amazon SDKs ]

To manage environment variables using an Amazon SDK, use the following API operations.
+ [UpdateFunctionConfiguration](https://docs.amazonaws.cn/lambda/latest/api/API_UpdateFunctionConfiguration.html)
+ [GetFunctionConfiguration](https://docs.amazonaws.cn/lambda/latest/api/API_GetFunctionConfiguration.html)
+ [CreateFunction](https://docs.amazonaws.cn/lambda/latest/api/API_CreateFunction.html)

To learn more, refer to the [Amazon SDK documentation](https://www.amazonaws.cn/developer/tools/) for your preferred programming language.

------

## Example scenario for environment variables
<a name="configuration-envvars-example"></a>

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.

![\[\]](http://docs.amazonaws.cn/en_us/lambda/latest/dg/images/console-env.png)


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 key `LOG_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 of `DEBUG` in Python or `debug` in Node.js.

------
#### [ Python ]

**Example Python code to set log level**  

```
import os
import logging

# Initialize the logger
logger = logging.getLogger()

# Get the log level from the environment variable and default to INFO if not set
log_level = os.environ.get('LOG_LEVEL', 'INFO')

# Set the log level
logger.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')
```

------
#### [ Node.js (ES module format) ]

**Example Node.js code to set log level**  
This example uses the `winston` logging library. Use npm to add this library to your function's deployment package. For more information, see [Creating a .zip deployment package with dependencies](nodejs-package.md#nodejs-package-create-dependencies).  

```
import winston from 'winston';

// Initialize the logger using the log level from environment variables, defaulting to INFO if not set
const 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');
   
};
```

------

## Retrieving Lambda environment variables
<a name="retrieve-environment-variables"></a>

To retrieve environment variables in your function code, use the standard method for your programming language.

------
#### [ Node.js ]

```
let region = process.env.AWS_REGION
```

------
#### [ Python ]

```
import os
  region = os.environ['AWS_REGION']
```

**Note**  
In some cases, you may need to use the following format:  

```
region = os.environ.get('AWS_REGION')
```

------
#### [ Ruby ]

```
region = ENV["AWS_REGION"]
```

------
#### [ Java ]

```
String region = System.getenv("AWS_REGION");
```

------
#### [ Go ]

```
var region = os.Getenv("AWS_REGION")
```

------
#### [ C\$1 ]

```
string region = Environment.GetEnvironmentVariable("AWS_REGION");
```

------
#### [ PowerShell ]

```
$region = $env:AWS_REGION
```

------

Lambda stores environment variables securely by encrypting them at rest. You can [configure Lambda to use a different encryption key](configuration-envvars-encryption.md), encrypt environment variable values on the client side, or set environment variables in an Amazon CloudFormation template with Amazon Secrets Manager.

## Defined runtime environment variables
<a name="configuration-envvars-runtime"></a>

Lambda [runtimes](lambda-runtimes.md) set several environment variables during initialization. Most of the environment variables provide information about the function or runtime. The keys for these environment variables are *reserved* and cannot be set in your function configuration.

**Reserved environment variables**
+ `_HANDLER` – The handler location configured on the function.
+ `_X_AMZN_TRACE_ID` – The [X-Ray tracing header](services-xray.md). This environment variable changes with each invocation.
  + This environment variable is not defined for OS-only runtimes (the `provided` runtime family). You can set `_X_AMZN_TRACE_ID` for custom runtimes using the `Lambda-Runtime-Trace-Id` response header from the [Next invocation](runtimes-api.md#runtimes-api-next).
  + For Java runtime versions 17 and later, this environment variable is not used. Instead, Lambda stores tracing information in the `com.amazonaws.xray.traceHeader` system property.
+ `AWS_DEFAULT_REGION` – The default Amazon Web Services Region where the Lambda function is executed.
+ `AWS_REGION` – The Amazon Web Services Region where the Lambda function is executed. If defined, this value overrides the `AWS_DEFAULT_REGION`.
  + For more information about using the Amazon Web Services Region environment variables with Amazon SDKs, see [Amazon Region](https://docs.amazonaws.cn/sdkref/latest/guide/feature-region.html#feature-region-sdk-compat) in the *Amazon SDKs and Tools Reference Guide*.
+ `AWS_EXECUTION_ENV` – The [runtime identifier](lambda-runtimes.md), prefixed by `AWS_Lambda_` (for example, `AWS_Lambda_java8`). This environment variable is not defined for OS-only runtimes (the `provided` 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 is `on-demand`, `provisioned-concurrency`, `snap-start`, or `lambda-managed-instances`. For information, see [Configuring provisioned concurrency](provisioned-concurrency.md), [Improving startup performance with Lambda SnapStart](snapstart.md), or [Lambda Managed Instances](lambda-managed-instances.md).
+ `AWS_LAMBDA_LOG_GROUP_NAME`, `AWS_LAMBDA_LOG_STREAM_NAME` – The name of the Amazon CloudWatch Logs group and stream for the function. The `AWS_LAMBDA_LOG_GROUP_NAME` and `AWS_LAMBDA_LOG_STREAM_NAME` [environment variables](#configuration-envvars-runtime) 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's [execution role](lambda-intro-execution-role.md).
+ `AWS_LAMBDA_RUNTIME_API` – ([Custom runtime](runtimes-custom.md)) The host and port of the [runtime API](runtimes-api.md).
+ `LAMBDA_TASK_ROOT` – The path to your Lambda function code.
+ `LAMBDA_RUNTIME_DIR` – The path to runtime libraries.
+ `AWS_LAMBDA_MAX_CONCURRENCY` – (Lambda Managed Instances only) The maximum number of concurrent invocations Lambda will send to one execution environment.
+ `AWS_LAMBDA_METADATA_API` – The [metadata endpoint](configuration-metadata-endpoint.md) server address in the format `{ipv4_address}:{port}` (for example, `169.254.100.1:9001`).
+ `AWS_LAMBDA_METADATA_TOKEN` – A unique authentication token for the current execution environment used to authenticate requests to the [metadata endpoint](configuration-metadata-endpoint.md). Lambda generates this token automatically at initialization.

The following additional environment variables aren't reserved and can be extended in your function configuration.

**Unreserved environment variables**
+ `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](lambda-nodejs.md)) The Node.js library path (`/opt/nodejs/node12/node_modules/:/opt/nodejs/node_modules:$LAMBDA_RUNTIME_DIR/node_modules`).
+ `NODE_OPTIONS` – ([Node.js](lambda-nodejs.md)) For Node.js runtimes, you can use `NODE_OPTIONS` to re-enable experimental features that Lambda disables by default.
+ `PYTHONPATH` – ([Python](lambda-python.md)) The Python library path (`$LAMBDA_RUNTIME_DIR`).
+ `GEM_PATH` – ([Ruby](lambda-ruby.md)) 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 to `LOG_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](lambda-csharp.md)) Set this variable to enable or disable .NET specific runtime optimizations. Values include `always`, `never`, and `provisioned-concurrency`. For more information, see [Configuring provisioned concurrency for a function](provisioned-concurrency.md).
+ `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.

# Securing Lambda environment variables
<a name="configuration-envvars-encryption"></a>

For securing your environment variables, you can use server-side encryption to protect your data at rest and client-side encryption to protect your data in transit.

**Note**  
To increase database security, we recommend that you use Amazon Secrets Manager instead of environment variables to store database credentials. For more information, see [Use Secrets Manager secrets in Lambda functions](with-secrets-manager.md).

**Security at rest**  
Lambda always provides server-side encryption at rest with an Amazon KMS key. By default, Lambda uses an Amazon managed key. If this default behavior suits your workflow, you don't need to set up anything else. Lambda creates the Amazon managed key in your account and manages the permissions for you. Amazon doesn't charge you to use this key.

If you prefer, you can provide an Amazon KMS customer managed key instead. You might do this to have control over rotation of the KMS key or to meet the requirements of your organization for managing KMS keys. When you use a customer managed key, only users in your account with access to the KMS key can view or manage environment variables on the function.

Customer managed keys incur standard Amazon KMS charges. For more information, see [Amazon Key Management Service pricing](https://www.amazonaws.cn/kms/pricing/).

**Security in transit**  
For additional security, you can enable helpers for encryption in transit, which ensures that your environment variables are encrypted client-side for protection in transit.

**To configure encryption for your environment variables**

1. Use the Amazon Key Management Service (Amazon KMS) to create any customer managed keys for Lambda to use for server-side and client-side encryption. For more information, see [Creating keys](https://docs.amazonaws.cn/kms/latest/developerguide/create-keys.html) in the *Amazon Key Management Service Developer Guide*.

1. Using the Lambda console, navigate to the **Edit environment variables** page.

   1. Open the [Functions page](https://console.amazonaws.cn/lambda/home#/functions) of the Lambda console.

   1. Choose a function.

   1. Choose **Configuration**, then choose **Environment variables** from the left navigation bar.

   1. In the **Environment variables** section, choose **Edit**.

   1. Expand **Encryption configuration**.

1. (Optional) Enable console encryption helpers to use client-side encryption to protect your data in transit.

   1. Under **Encryption in transit**, choose **Enable helpers for encryption in transit**.

   1. For each environment variable that you want to enable console encryption helpers for, choose **Encrypt** next to the environment variable.

   1.  Under Amazon KMS key to encrypt in transit, choose a customer managed key that you created at the beginning of this procedure.

   1. Choose **Execution role policy** and copy the policy. This policy grants permission to your function's execution role to decrypt the environment variables.

      Save this policy to use in the last step of this procedure.

   1. Add code to your function that decrypts the environment variables. To see an example, choose **Decrypt secrets snippet**.

1. (Optional) Specify your customer managed key for encryption at rest.

   1. Choose **Use a customer master key**.

   1. Choose a customer managed key that you created at the beginning of this procedure.

1. Choose **Save**.

1. Set up permissions.

   If you're using a customer managed key with server-side encryption, grant permissions to any users or roles that you want to be able to view or manage environment variables on the function. For more information, see [Managing permissions to your server-side encryption KMS key](#managing-permissions-to-your-server-side-encryption-key).

   If you're enabling client-side encryption for security in transit, your function needs permission to call the `kms:Decrypt` API operation. Add the policy that you saved previously in this procedure to the function's [execution role](lambda-intro-execution-role.md).

## Managing permissions to your server-side encryption KMS key
<a name="managing-permissions-to-your-server-side-encryption-key"></a>

No Amazon KMS permissions are required for your user or the function's execution role to use the default encryption key. To use a customer managed key, you need permission to use the key. Lambda uses your permissions to create a grant on the key. This allows Lambda to use it for encryption.
+ `kms:ListAliases` – To view keys in the Lambda console.
+ `kms:CreateGrant`, `kms:Encrypt` – To configure a customer managed key on a function.
+ `kms:Decrypt` – To view and manage environment variables that are encrypted with a customer managed key.

You can get these permissions from your Amazon Web Services account or from a key's resource-based permissions policy. `ListAliases` is provided by the [managed policies for Lambda](access-control-identity-based.md). Key policies grant the remaining permissions to users in the **Key users** group.

Users without `Decrypt` permissions can still manage functions, but they can't view environment variables or manage them in the Lambda console. To prevent a user from viewing environment variables, add a statement to the user's permissions that denies access to the default key, a customer managed key, or all keys.

**Example IAM policy – Deny access by key ARN**    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Deny",
            "Action": [
                "kms:Decrypt"
            ],
            "Resource": "arn:aws-cn:kms:us-west-2:111122223333:key/3be10e2d-xmpl-4be4-bc9d-0405a71945cc"
        }
    ]
}
```

For details on managing key permissions, see [Key policies in Amazon KMS](https://docs.amazonaws.cn/kms/latest/developerguide/key-policies.html) in the *Amazon Key Management Service Developer Guide*.