All Products
Search
Document Center

Function Compute:Configure environment variables

Last Updated:Apr 15, 2026

You can use environment variables to adjust the behavior of an FC function without changing its code. Environment variables are string key-value pairs stored in the function's configuration. Each function has its own set of environment variables. This topic describes the basics of environment variables and how to configure them.

Security

When you create or update environment variables, Function Compute encrypts them at rest using the Advanced Encryption Standard 256 (AES-256). When a function instance is initialized, the variables are decrypted and injected into the instance environment.

Limitations

  • Character set rules

    • A key must start with a letter and can contain only letters, digits, and underscores (_).

  • Size limit

    The total size of all environment variables cannot exceed 4 KB.

  • Reserved system environment variables

    To prevent system conflicts, you cannot use environment variables with the reserved prefix FC_*.

    Function Compute supports the following system environment variables:

    • FC_FUNC_CODE_PATH: The code deployment directory.

    • ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN: The temporary credentials obtained from the function's execution role, including the AccessKey ID, AccessKey secret, and temporary token.

    • FC_ACCOUNT_ID: The user ID.

    • FC_FUNCTION_HANDLER: The function handler.

    • FC_FUNCTION_MEMORY_SIZE: The memory size configured for the function, in MB.

    • FC_FUNCTION_NAME: The function name.

    • FC_REGION: The region where the function resides.

    • FC_CUSTOM_LISTEN_PORT: The custom listening port of the function.

    • FC_INSTANCE_ID: The ID of the function instance.

    • FC_VER_ID: The ID of the function version. This variable is available for built-in runtimes on Debian 10 and earlier.

    • FC_FUNCTION_VERSION: The ID of the function version. This variable is available for built-in runtimes on Debian 11 and later.

Use cases

  • Share code across platforms or services

    You can use environment variables to manage different configurations for test and production environments, such as specifying distinct Object Storage Service (OSS) buckets, databases, or tables. This allows you to deploy the same codebase across multiple platforms without modification.

  • Configure credentials

    You can set database connection credentials, your Alibaba Cloud AccessKey, or other sensitive authentication information using environment variables.

  • Configure system variables

    You can use system libraries more flexibly by configuring directories such as PATH and HOME.

Configure environment variables

Console

Prerequisites

A function is created. For more information, see Create a function.

Procedure

  1. Log on to the Function Compute console. In the left-side navigation pane, choose Function Management > Functions.

  2. In the top navigation bar, select a region. On the Functions, click the target function.

  3. On the function details page, click the Configuration tab, and then in the Advanced Settings section, click Modify.

  4. In the Advanced Settings panel, under Environment Variables, configure the variables using one of the following methods, and then click Deploy.

    • Use the form editor

      1. Click + Add Variable.

      2. Configure a key-value pair for the environment variable:

        • Variable: Enter a custom key.

        • Value: Enter a custom value.

    • Use the JSON editor

      1. Click Use JSON format to edit.

      2. In the text box, enter the key-value pairs in JSON format, as shown in the following example:

        {
            "key": "value"
        }

        Example:

        {
            "BUCKET_NAME": "MY_BUCKET",
            "TABLE_NAME": "MY_TABLE"
        }
  5. Verify that the environment variables have taken effect.

    1. On the function details page, click the Code tab.

    2. In the code editor, write your code, click Deploy. After the deployment succeeds, click Test Function.

      The following sample code for a Python event function shows how to verify the environment variables:

      # -*- coding: utf-8 -*-
      import logging
      import os
      
      def handler(event, context):
          logger = logging.getLogger()
          value = os.environ.get('BUCKET_NAME')
          logger.info('BUCKET_NAME: {}'.format(value))
          value = os.environ.get('TABLE_NAME')
          logger.info('TABLE_NAME: {}'.format(value))
          return "done"
    3. On the Code tab, view the Log Output. After the function executes successfully, the configured environment variables appear in the logs.

Serverless Devs

Prerequisites

Serverless Devs is installed and configured. For more information, see Quick start.

Procedure

  1. Create a code directory for testing, such as test.

  2. Go to the test directory and create an index.py file and an s.yaml file.

    The code directory is structured as follows:

    .
    ├── code
    │   └── index.py
    └── s.yaml

    The index.py file contains your function code. For the sample code, see the example in the Console section.

    The s.yaml file is the function's configuration file. The following is an example:

    edition: 3.0.0
    name: hello-world-app
    # access: specifies the required credential information for the application.
    # For more information about how to configure credentials, see https://www.serverless-devs.com/serverless-devs/command/config
    # For more information about the credential priority, see https://www.serverless-devs.com/serverless-devs/tool#credential-priority-and-specifications
    access: "default"
    
    vars: # Global variables
      region: "cn-hangzhou"
    
    resources:
      hello_world:
        # To perform an operation only on a specific service like hello_world, specify its name in the command. Example:
        # Build only for the hello_world service: s hello_world build
        # If you run the s build command without specifying a service, Serverless Devs performs the build operation on all services that are at the same level as hello_world in the YAML file.
        component: fc3 # The component name. Serverless Devs uses components to extend its capabilities. This component enables Function Compute features.
        # actions: # Custom execution logic. For more information, see https://docs.serverless-devs.com/serverless-devs/yaml#actions.
        props:
          region: ${vars.region} # For more information about how to use variables, see https://docs.serverless-devs.com/serverless-devs/yaml#variable-assignment.
          functionName: envdemo # Declares a function named envdemo.
          description: 'hello world by serverless devs'
          runtime: python3 # Specifies the function runtime.
          code: ./code
          handler: index.handler # Specifies the function handler.
          memorySize: 128
          timeout: 30
          environmentVariables: # Configures two environment variables for the function.
              BUCKET_NAME: MY_BUCKET
              TABLE_NAME: MY_TABLE
          codeUri: ./ # Deploys the function from the current directory "./". During deployment, Serverless Devs packages and uploads the current directory.
  3. Run the s deploy command to deploy the project.

    After a successful deployment, you can log in to the Function Compute console to view the created function and its environment variables.

SDK

The following examples use the Python SDK. The environmentVariables parameter, which accepts a dictionary, specifies the environment variables. The sample code shows how to create, update, and retrieve them.

  • Create environment variables

    # coding: utf-8
    import fc2
    import os
    
    client = fc2.Client(
        endpoint='your endpoint', # The endpoint.
        # We recommend not storing your AccessKey ID and AccessKey secret in your code.
        # Leaking this sensitive information can compromise the security of your resources.
        # This example uses environment variables for authentication.
        # Before running this code, set the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables locally.
        accessKeyID=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), # Your AccessKey ID, used for authentication. You can create and manage it in the RAM console.
        accessKeySecret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET') # Your AccessKey secret, used for authentication. You can create and manage it in the RAM console.
    )
    
    client.create_service('test')
    
    client.create_function(
        'test', # The service name.
        'test_env', # The function name.
        'python3',  # The runtime.
        'main.handler', # The handler.
        codeDir='/path/to/code/', # The code directory.
        environmentVariables={'testKey': 'testValue'} # The environment variables to configure.
    )
    
    res = client.get_function('test', 'test_env')
    
    print(res.data)
      
  • Update environment variables

    client.update_function(
        'test', 'test_env', 'python3',  'main.handler',
        codeDir='/path/to/code/', environmentVariables={'newKey': 'newValue'})
    res = client.get_function('test', 'test_env')
    print(res.data)           
  • Get environment variables

    resp = client.get_function('test', 'test_env')
    env = func['environmentVariables']

Use environment variables in your code

Assuming you have configured the environment variable {"key":"val"}, the following examples show how to read its value in different runtimes.

var value = process.env.key
console.log(value)
import os
value = os.environ.get('key')
print(value)
$value = getenv('key');
System.out.println("value: "+ System.getenv("key"));
string value = Environment.GetEnvironmentVariable("key");
Console.WriteLine("value: {0}", value);
var value = os.Getenv("key")
fmt.Printf("value: %s\n", value)

FAQ

Can I set different environment variables for different function versions?

Yes. After you set environment variables for the LATEST version and publish a new version, you can modify the LATEST version's variables. This results in the LATEST version having different settings from the published one.

How can I prevent environment variable values from being displayed in plaintext in the console? How do I encrypt sensitive data?

You can store environment variables in Key Management Service to ensure sensitive information is stored encrypted. Before the function executes, your code can call the KMS API to decrypt the information and set it in the function's runtime environment. For more information, see What is Key Management Service (KMS)?.

How do I change the time zone using an environment variable?

When you create a function, you can select a time zone. By default, function instances run in Coordinated Universal Time (UTC). After the function is created, you can change the time zone by setting the TZ environment variable. For example, to use China Standard Time (UTC+8), set TZ to Asia/Shanghai.