You can use environment variables to flexibly adjust the behaviors of functions in Function Compute without modifying the 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 environment variables in the Function Compute console. This topic also provides sample code.

Data security

When you create or update environment variables, Function Compute encrypts and stores the environment variables based on 256-bit Advanced Encryption Standard (AES-256). When the function instance is initialized, Function Compute decrypts the environment variables and then injects the environment variables into the function instance environment.

Limits

  • Rules for character sets
    • A key must start with a letter and can contain only letters and digits.
    • A value can only contain printable ASCII characters.
  • Size

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

  • Reserved environment variables

    To prevent system confusion, when you configure environment variables, you cannot use the environment variables that are reserved by Function Compute, including FC_*, accessKeyID, accessKeySecret, securityToken, and topic.

    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_SERVICE_NAME: the name of the service to which the function belongs.
    • FC_CUSTOM_LISTEN_PORT: the custom listening port of the function.
    • FC_INSTANCE_ID: the ID of the function instance.
    • FC_QUALIFIER: the alias of the service to which the function belongs. Default value: LATEST.
    Important System environment variables accessKeyID, accessKeySecret, securityToken, ALIBABA_CLOUD_ACCESS_KEY_ID, ALIBABA_CLOUD_ACCESS_KEY_SECRET, and ALIBABA_CLOUD_SECURITY_TOKEN are sensitive information about temporary keys. Do not disclose them to third parties.

Scenarios

  • Share code across platform or service

    The configurations of the same function code may vary between the test environment and the 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

    You can use environment variables to configure security-sensitive authentication information, such as your Alibaba Cloud AccessKey pair, and a username and password that are 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 Services & Functions.
  2. In the top navigation bar, select a region. On the Services page, click the desired service.
  3. On the Functions page, find the function that you modify and click Configure in the Actions column.
  4. In the Environment Variables section of the Modify Function Settings page, select a method to configure environment variables based on your business requirements. After you configure environment variables, click Save.
    • Form Editor (default method)
      1. Click + Add Variable.
      2. Configure the key-value pairs of the environment variables.
        • Variable: Enter a custom variable.
        • Value: Enter a variable value.

        The following figure shows an example.

        sc_edit_environment_variables
    • 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 figure shows an example.
        {
            "BUCKET_NAME": "MY_BUCKET",
            "TABLE_NAME": "MY_TABLE"
        }
  5. Check whether the environment variables are created.
    1. On the details page of the function, click the Code tab.
    2. Write code in the code editor, click Save and Deploy. After the code is deployed, click Test Function on the Code tab.
      The following sample code provides an example on how to verify the 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 Log Output.
      The displayed log shows that the environment variables are created.

Configure environment variables by using Serverless Devs

Before you start

Procedure

  1. Create a code directory for test and specify a name for the directory. In this example, test is used.
  2. Go to the test directory and create a file named index.py based on the preceding code.
  3. Create the s.yaml file.
    The file contains the following content:
    edition: 1.0.0
    name: transform_fun
    access: default
    vars:
      region: cn-shenzhen
    services:
      fc-Demo-envdemo:
        component: devsapp/fc
        props:
          region: ${vars.region}
          service:
            name: Demo    # Declare a service named Demo.
            internetAccess: true
          function:
            name: envdemo   # Declare a function named envdemo in the Demo service.
            handler: index.handler    # Configure a handler for the function.
            runtime: python3          # Specify the runtime for the function.
            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. 
  4. Run s deploy to deploy your project.
    After s deploy is run, you can log on to the Function Compute console to view the service and function that you created, and the environment variables that you 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 snippets provide examples on how to create, update, and obtain environment variables:

  • Create environment variables
    # coding: utf-8
    import fc2
    
    client = fc2.Client(
        endpoint='your endpoint', #The endpoint. For more information about endpoints, visit https://www.alibabacloud.com/help/en/function-compute/latest/endpoints. 
        accessKeyID='your accessKeyID', #The AccessKey ID for identity authentication. You can create AccessKey IDs in the RAM console. 
        accessKeySecret='your accessKeySecret') #The AccessKey secret for identity authentication. You can create AccessKey secrets in the RAM console. 
    
    client.create_service('test')
    
    client.create_function(
        'test', 'test_env', 'python3',  'main.handler',
        codeDir='/path/to/code/', environmentVariables={'testKey': 'testValue'})
    
    #test: the name of the service.
    #test_env: the name of the function.
    #python3: the runtime environment.
    #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

The following sample code provides an example on how to read the configured environment variables and print the values of the environment variables in different runtimes. In the sample code, the {"key":"val"} environment variable is used as an example.

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');
Console.WriteLine(Environment.GetEnvironmentVariable("key"));