All Products
Search
Document Center

Function Compute:Configure environment variables

Last Updated:May 11, 2024

You can use environment variables to flexibly adjust behavior of functions in Function Compute without the need to modify code. Environment variables are stored as key-value pairs as part of function configurations. Different functions have different environment variables. This topic describes the basic information about environment variables and how to configure and use environment variables. Sample code is provided in this topic.

Security

When you create and update environment variables, Function Compute encrypts the environment variables by using Advanced Encryption Standard 256 (AES 256) before the environment variables are stored. When function instances are initialized, their environment variables are decrypted and injected to the environments of the function instances.

Limits

  • Character sets

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

  • Size

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

  • Reserved system environment variables

    To avoid system confusion, you cannot use FC_*, which is a reserved system environment variable, when you configure environment variables.

    You can use the following system environment variables:

    • FC_FUNC_CODE_PATH: the path to deploy code.

    • 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

    The ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN system environment variables are information about temporary keys. Do not disclose them to third parties.

Scenarios

  • Share code across platforms or services

    A set of code can have different configurations in different environments, such as the test environment and production environment. You can use environment variables to select different Object Storage Service (OSS) buckets, databases, or tables. This way, you can deploy code to different platforms without modification.

  • 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 that is used to connect to a database.

  • Configure system variables

    You can use system libraries more flexibly when you configure directories such as PATH and HOME.

Configure environment variables in the Function Compute console

Before you start

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 configuration page, click the Configuration tab.

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

    • Form Editor (default)

      1. Click + Add Variable.

      2. Configure 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 a key-value pair in the following JSON format:

        {
            "key": "value"
        }

        The following sample code shows an example:

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

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

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

      The following sample code provides an example on how to verify 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, view logs.

      The log shows that 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 is similar to a game console and does not have specific business capabilities. The component is similar to a game card. You can insert different game cards into the game console to play different games. Similarly, you can use different components to implement different business capabilities.
        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, Serverless Devs 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 two 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 provide examples on 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 do not save the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
        In this example, the AccessKey pair is stored in environment variables to implement identity verification. 
        # Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables in your on-premises environment before you run the sample code. 
        # In runtimes of Function Compute, 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, which is created in the RAM console and used for identity authentication. 
        accessKeySecret=os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET') # The AccessKey secret, which 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 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)           
  • Obtain environment variables

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

Use environment variables in code

Assume that you configured {"key":"val"} as an environment variable. The following code shows how each runtime reads and prints the value of the variable.

var value = process.env.key
console.log(value)
import os
value = os.environ.get('key')
print(value)
System.out.println("value: "+ System.getenv("key"));
$value = getenv('key');

FAQ

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

Yes, you can configure different environment variables for different versions of a function. For example, after you configure environment variables for a function of the LATEST version and publish the version, you can modify environment variables in the LATEST version. This way, environment variables of a function between the LATEST version and the published version are different.

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

You can encrypt and save environment variables in Key Management Service (KMS). Make sure that you encrypt environment variables before you store them in KMS. Before you execute a function, you can call the KMS API to decrypt environment variables and configure the variables in the runtime of the function. For more information, see What is Key Management Service?