Environment variables can dynamically pass configuration information to the function code to avoid writing it to the function code. As a part of function configuration, environment variables are stored as key-value pairs. Different functions have different environmental variables and do not affect each other. This topic describes the basic information about environment variables, deployment methods in the console, and sample code.

Prerequisites

Create a function

security

After you configure environment variables, the environment variables are configured to the operating system environment when a function is executed. You can read the configured environment variables from the system environment variables.

When you create or update environment variables, Function Compute encrypts and stores the environment variables by using Advanced Encryption Standard (AES) 256. When you execute the function, the environment variables are automatically decrypted in reverse. This ensures data security.

Scenario

  • Deploy a function on different platforms or services

    The configurations of the same function code may be different in the test environment and production environment. For example, you can use environment variables to select different Object Storage Service (OSS) buckets, databases, or tables. This way, you can deploy the same function to different platforms or environments without modifying the function code.

  • Configure a key

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

  • Configure system variables

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

Limits

  • Character set rules
    • A key must start with a letter and can contain letters and digits.
    • A value must contain printable ASCII characters and cannot contain other characters such as Chinese characters.
  • Size limits

    The total size of environment variables cannot exceed 4 KB.

  • Reserved variables

    To prevent confusion, you cannot use the environment variables that Function Compute reserves. Reserved variables include FC_*, accessKeyID, accessKeySecret, securityToken, and topic.

Configure environment variables in the Function Compute console

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where the service resides.
  4. On the Services page, click the target service.
  5. On the Functions page, find the function that you want to manage and click Configure in the Actions column.
  6. In the Environment Variables section, select a method for configuring environment variables as needed, and then click Save.
    • Use form editing (default method)
      1. Click + Add Variable.
      2. Configure key-value pairs for environment variables:
        • Key: custom
        • Value: custom.

        Sample policy:

        sc_edit_environment_variables
    • Edit using JSON format
      1. Click Edit in JSON Format.
      2. In the text box, enter a JSON-formatted key-value pair in the following format:
        {
            "key": "value"
        }
        The following code shows an example:
        {
            "BUCKET_NAME": "MY_BUCKET",
            "TABLE_NAME": "MY_TABLE"
        }
    After successfully saved, the page is redirected to the function details page.
  7. Verify that the environment variable is created.
    1. On the function details page, click the Function Code tab.
    2. Write the code in the code editor, click Deploy Code, and then click Test Function.
      The following code shows how different functions are triggered.
      • Triggered by event
        module.exports.handler = function(event, context, callback) {
          var bucket_name = process.env['BUCKET_NAME']
          var table_name = process.env['TABLE_NAME']
          console.log('BUCKET_NAME: ',bucket_name)
          console.log('TABLE_NAME: ',table_name)
          callback(null, "success")
        }
      • Triggered by HTTP events
        exports.handler = (req, resp, context) => {
            var bucket_name = process.env['BUCKET_NAME'];
            var table_name = process.env['TABLE_NAME'];
            console.log('BUCKET_NAME: ', bucket_name);
            console.log('TABLE_NAME: ', table_name);
        }
      Note You cannot use an online IDE for RAM roles and custom image environments. The online IDE is applicable to PHP, Python, Node.JS, and Custom Runtime.
    3. On the Function Code tab, view the Log Output section.
      You can see from the print log that the environment variable has been created successfully. sc_result

Configure environment variables by using Serverless Devs

  1. Run the following sample code to configure a function and environment variables:
    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
            internetAccess: true
          function:
            name: envdemo
            handler: index.handler
            runtime: python2.7
            environmentVariables:
              OSSEndpoint: oss-cn-hangzhou.aliyuncs.com
              BucketName: s-local-test
            codeUri: ./

    The meaning of the above example is: declare a service named Demo, and under this service, declare a function named envdemo, configure the function entry to index.handler, and the runtime of the function to Python 2.7. the CodeUri property to the current directory. During deployment, Serverless Devs packages and uploads the directory specified by CodeUri. You can place dependencies in the directory pointed to by CodeUri.

    The function also configures environment variables named OSSEndpoint and BucketName. The values are oss-cn-hangzhou.aliyuncs.com and fun-local-test respectively.

  2. Execute s deploy deployment.
    After the deployment is successful, you can log on to the Function Compute console to view the created service named FunDemo and the envdemo function. The function is configured with the BUCKET_NAME and TABLE_NAME environment variables.

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 alphabetical order. The following code provides an example on how to create, update, and obtain environment variables:

  • Create an environment variable
    # coding: utf-8
    
    import fc2
    client = fc2.Client(
        endpoint='your endpoint',
        accessKeyID='your accessKeyID',
        accessKeySecret='your accessKeySecret')
    client.create_service('test')
    client.create_function(
        'test', 'test_env', 'python2.7',  'main.handler',
        codeDir='/path/to/code/', environmentVariables={'testKey': 'testValue'})
    res = client.get_function('test', 'test_env')
    print res.data                   
  • Update an environment variable
    client.update_function(
        'test', 'test_env', 'python2.7',  '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']

Sample code

Assume that the environment variable {"key":"val"} is configured. The following code provides an example on how to read the environment variable and print the value of the environment 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');
Console.WriteLine(Environment.GetEnvironmentVariable("key"));