All Products
Search
Document Center

Function Compute:Configure environment variables

Last Updated:Jan 20, 2025

You can use environment variables to flexibly adjust the behavior of functions in FC without modifying any code. Environment variables are stored as key-value pairs in function configurations. Every function operates with its own set of environment variables. This topic provides an overview of environment variables and describes how to configure them.

Security

When you create and update environment variables, Function Compute uses Advanced Encryption Standard 256 (AES 256) to encrypt those variables before they are stored. When a function instance is initialized, its environment variables are decrypted and then injected to the instance environment.

Limits

  • Character set

    • A key must start with a letter and contain only letters and digits.

  • Size

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

  • System environment variable

    To prevent system confusion, avoid using the reserved system environment variable FC_* when you configure environment variables.

    You can use the following system environment variables:

    • FC_FUNC_CODE_PATH: the code deployment directory.

    • ALIBABA_CLOUD_ACCESS_KEY_ID: the AccessKey ID of the role.

    • ALIBABA_CLOUD_ACCESS_KEY_SECRET: the AccessKey secret of the role.

    • ALIBABA_CLOUD_SECURITY_TOKEN: the temporary token for the role.

    • FC_ACCOUNT_ID: the user ID.

    • FC_FUNCTION_HANDLER: the handler.

    • FC_FUNCTION_MEMORY_SIZE: the memory size of the function. Unit: MB.

    • FC_FUNCTION_NAME: the name of the function.

    • FC_REGION: the region in which the function resides.

    • FC_CUSTOM_LISTEN_PORT: the custom listening port of the function.

    • FC_INSTANCE_ID: the ID of the function instance.

    Important

    ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN contain sensitive information related to credentials that you must not disclose to third parties.

Scenarios

  • Share code across platforms or services

    The configurations of the same codebase may vary between a test environment and a production environment. You can use environment variables to select different Object Storage Service (OSS) buckets, databases, or tables to store your code. This allows you to seamlessly deploy code to various platforms without any prior modifications.

  • Configure an AccessKey pair

    You can use environment variables to configure sensitive authentication information, such as your Alibaba Cloud AccessKey pair or a username-password pair for database connections.

  • Configure system variables

    You can configure the PATH and HOME variables in system directories.

Configure environment variables in the Function Compute console

Prerequisites

Function creation is completed. For more information, see Create a function.

Procedure

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

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the Function Details page, click the Configurations tab.

  4. In the left-side navigation pane, click the Environment Variables tab. On the Environment Variables tab, click Modify. In the Environment Variables panel that is displayed, select a method to configure the variable, perform the following steps, and then click Deploy.

    • Form Editor (default)

      1. Click + Add Variable.

      2. Configure the key-value pairs of environment variables.

        • Variable: Enter a custom variable.

        • Value: Enter a variable value.

    • JSON Editor

      1. Click JSON Editor.

      2. In the code editor, enter key-value pairs in the following JSON format:

        {
            "key": "value"
        }

        Example:

        {
            "BUCKET_NAME": "MY_BUCKET",
            "TABLE_NAME": "MY_TABLE"
        }
  5. Verify whether the environment variables are created.

    1. On the Function Details page, click the Code tab.

    2. In the code editor, write code and then click Deploy. After the code is deployed, click Test Function.

      The following sample code demonstrates how to verify the creation of environment variables by using a Python event function:

      # -*- 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, click Log Output to view the logs.

      As you can see from the printed log, the environment variables are created.

Configure environment variables by using Serverless Devs

Prerequisites

Procedure

  1. Create a code directory for testing. In this example, the test directory is created.

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

    The following sample code shows the code directory.

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

    The index.py file is a code file. For sample code, see Configure environment variables in the Function Compute console.

    The s.yaml file is a function configuration file. Example:

    edition: 3.0.0
    name: hello-world-app
    # access specifies the key information required by the current application.
    # For more information about how to configure keys, visit https://www.serverless-devs.com/serverless-devs/command/config.
    # For more information about the sequence to use keys, visit https://www.serverless-devs.com/serverless-devs/tool#.
    access: "default"
    
    vars: # The global variable.
      region: "cn-hangzhou"
    
    resources:
      hello_world:
        # If you want to perform operations only on hello_world, you can add hello_world to the command line. Example:
        # Build only for hello_world: s hello_world build
        # If you run the s build command without adding hello_world, Serverless Devs performs the build operations on all business modules at the same level as hello_world in the current YAML file, such as the next_function module in the following comment.
        component: fc3 # The name of the component. Serverless Devs can be thought of as a game console and does not have specific business capabilities without components. However, just as a game console can be enhanced with different game cards, Serverless Devs can be extended with various components. Each component is like a game card, enabling the implementation of distinct business capabilities. By combining different components, you can unlock a wide range of business functionalities, much like how a game console can play different games with different cards.
        # actions:       # The custom execution logic. For more information about actions, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E8%A1%8C%E4%B8%BA%E6%8F%8F%E8%BF%B0actions.
        props:
          region: ${vars.region}              # For more information about how to use variables, visit https://docs.serverless-devs.com/serverless-devs/yaml#%E5%8F%98%E9%87%8F%E8%B5%8B%E5%80%BC.
          functionName: envdemo            # Declare a function named envdemo.
          description: 'hello world by serverless devs'
          runtime: python3                # Configure a runtime for the function.
          code: ./code
          handler: index.handler              # Configure a handler for the function.
          memorySize: 128
          timeout: 30
          environmentVariables:     # Configure the following environment variables for the function:
              BUCKET_NAME: MY_BUCKET
              TABLE_NAME: MY_TABLE
          codeUri: ./               # Deploy the function in the current directory. When Serverless Devs deploys the function, it packages and uploads the current directory.
  3. Run the s deploy command to deploy the project.

    After the command is executed, you can log on to the Function Compute console to view the created function and the environment variables configured for the function.

Configure environment variables by using SDKs

In this example, the SDK for Python is used. The environmentVariables parameter specifies environment variables. The values of this parameter are stored in the form of a dictionary. The following code snippets demonstrate how to create, update, and obtain environment variables:

  • Create environment variables

    # coding: utf-8
    import fc2
    import os
    
    client = fc2.Client(
        endpoint='your endpoint', # The endpoint. 
        # We recommend that you avoid saving the AccessKey ID and AccessKey secret in your project code. If this sensitive information is leaked, the security of all resources in your account could be compromised. 
        # In this example, the AccessKey pair is stored in environment variables to implement identity authentication. 
        # Before you run the sample code, configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment. 
        # In Function Compute runtimes, the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are automatically configured after you configure the execution permissions. 
        accessKeyID=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'), # The AccessKey ID. It is created in the Resource Access Management (RAM) console and used for identity authentication. 
        accessKeySecret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET') # The AccessKey secret. It is created in the RAM console and used for identity authentication. 
    
    client.create_service('test')
    
    client.create_function(
        'test', 'test_env', 'python3',  'main.handler',
        codeDir='/path/to/code/', environmentVariables={'testKey': 'testValue'})
    
    #test: the service name.
    #test_env: the function name.
    #python3: the runtime.
    #main.handler: the handler.
    #codeDir: the code directory.
    #environmentVariables: the environment variables that you want to use.
    
    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)           
  • Obtain environment variables

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

Use environment variables in code

For more information about how to use environment variables in code, see Use environment variables in code.

FAQ

Can I configure different environment variables for different versions of a function?

Yes. For example, after you configure environment variables for the LATEST version of a function and publish that version, you can still modify the environment variables in the LATEST version. As a result, the environment variables between the LATEST version and the published version are different.

What do I do if I prefer not to display the value of an environment variable in plaintext? How do I encrypt sensitive data when I configure environment variables?

You can encrypt your environment variables and then store them in Key Management Service. Before you execute a function, you can call the KMS API to decrypt these environment variables and configure them in the function runtime. For more information, see What is Key Management Service?