All Products
Search
Document Center

Function Compute:Create your first event function

Last Updated:Feb 10, 2025

Event functions respond to various events from cloud services, such as file uploads to Object Storage Service (OSS) or alerts from monitoring products. With event functions, you focus solely on writing the processing logic without managing underlying computing resources. Function Compute instances run on-demand and scale automatically, releasing resources post-event to optimize costs.

Scenario example

Imagine you need to save files to OSS. To expedite uploads, you compress the files into a ZIP format before uploading. For convenience, you require an automated process to decompress the files upon upload and save them back to OSS.

Traditionally, you would need to build and integrate multiple programs to monitor and process file changes on OSS, considering the deployment and maintenance of these programs. Event functions simplify this by allowing you to concentrate on the file processing program. When a file is uploaded to OSS and meets your predefined conditions, the function triggers automatically, processes the file, and then releases computing resources to save on costs.

If you don't have an OSS Bucket, this guide will walk you through the event function implementation process using the following example:

Create a simulated OSS file upload event to invoke an event function that processes the file and prints the file name, Bucket details, and other information to the console.

By following this example, you will:

  1. Complete the process of creating an event function, writing a request handler, and testing the function using the console.

  2. Familiarize yourself with key concepts such as the Function Compute runtime environment, including the built-in runtime.

  3. Understand the request handler parameters event and context.

Prerequisites

Create an Alibaba Cloud Account

To get started, register for an Alibaba Cloud account and complete the identity authentication process.

Activate the Function Compute service

If you have registered an Alibaba Cloud account and completed identity authentication after August 27, 2024, you can directly access the Function Compute service without needing to activate it. Upon your first visit to the Function Compute console, you will also be prompted to claim a free resource plan. For more information, see Trial quota.

For accounts registered before August 27, 2024, follow these steps to activate the service:

  1. Visit the or the Function Compute home page.

  2. Click Console to navigate to the service activation page. Then, click Activate Now to activate the service and access the Function Compute console.

    Note
    • It is recommended to use an Alibaba Cloud account to activate the service and manage functions with RAM users, granting them the necessary permissions based on the principle of least privilege. For more information, see Policy and Examples.

  3. (Optional) Upon your first logon to the Function Compute console, you must click Confirm in the Alibaba Cloud Service Access Authorization dialog box. This step is necessary to create a service-linked role that enables Function Compute to access related Alibaba Cloud services for future operations.

    Once successfully created, Function Compute can access your VPC, ECS, SLS, and Container Registry cloud resources. For more information about service-linked roles, see the referenced document.

Operation guide

1. Select function type

  1. Log on to the Function Compute console. At the top menu bar, select your desired region, such as China (Hangzhou). From the left-side navigation pane, click Functions, then click Create Function.

  2. On the Create Function page, select Event Function. You can customize the Function Name.image

2. Select runtime environment

Python

Select the Runtime Environment option, then choose Built-in Runtime - Python 3.10.

image

For event functions, it is recommended to use the built-in runtime as the function runtime environment because the built-in runtime includes the dependencies necessary to respond to events from other cloud products (such as the oss2 module for Python). For more information, see Environment description. If you use a custom runtime or custom image as the function runtime environment, you need to install the required dependencies yourself. For a detailed comparison of various runtime environments, see Function runtime environment selection.

Node.js

Select the Runtime Environment as Built-in Runtime - Node.js 20.

image

For event functions, it is recommended to use the built-in runtime as the function runtime environment because the built-in runtime includes the dependencies necessary to respond to events from other cloud products (such as the ali-oss module for Node.js). For more information, see Environment description. If you use a custom runtime or custom image as the function runtime environment, you need to install the required dependencies yourself. For a detailed comparison of various runtime environments, see Function runtime environment selection.

3. Create function

Select Hello, World Sample Code to create the function. Leave the Advanced Configuration and Environment Variables settings at their default values. Click Create and wait for the function to be created.

image

After creation, you can view the generated sample code in the WebIDE on the code tab. The following figure uses Python as an example.

image.png

The Hello, World sample code automatically generates a function template with an entry program. You can build your business code based on this template in subsequent steps.

4. Modify sample code and deploy

Interpreted languages like Python and Node.js support direct code modification and deployment in the WebIDE, while compiled languages like Java require local code package compilation and upload, not supporting WebIDE.

Python

In the console's WebIDE, open index.py, replace the existing code with the code provided below, and then click Deploy Code to apply the changes.

# -*- coding: utf-8 -*-
import logging
import json
# import oss2  # If you need to create an OSS client, uncomment this line
logger = logging.getLogger()


def handler(event, context):  # The request handler is the entry point for code execution
    logger.info("Parsing event information...")
    input_events = json.loads(event)
    if not input_events.get('events'):  # Check the format of the incoming event
        raise Exception("Event format error: events array does not exist or is of length 0")

    event_obj = input_events['events'][0]
    bucket_name = event_obj['oss']['bucket']['name']  # Parse OSS Bucket name
    object_name = event_obj['oss']['object']['key']  # Parse file name
    region = context.region  # Parse the region where the function is located
    logger.info(f"OSS bucket name is {bucket_name}, file name is {object_name}, Region is {region}")
    # If you already have an OSS Bucket, you can uncomment the following line to create an OSS client instance
    # bucket = get_bucket(region, bucket_name, context)
    bucket = None
    result = process_event(bucket, object_name)  # Call the subprogram to execute the event processing logic
    return result


def process_event(bucket, object_name):
    logger.info("Starting event processing...")
    # Here you can write the event processing logic
    # zip_file = download_file(bucket, object_name)
    # result = extract_and_upload(bucket, zip_file)
    logger.info("Event processing completed...")
    result = 0
    return result  # Returning 0 indicates that the event was processed successfully


# def get_bucket(region, bucket_name, context):
#     # Here, create an OSS Bucket client instance. The required identity authentication information can be obtained from the context
#     creds = context.credentials  # Obtain temporary keys
#     auth = oss2.StsAuth(
#         creds.access_key_id,
#         creds.access_key_secret,
#         creds.security_token)
#     endpoint = f'oss-{region}-internal.aliyuncs.com'
#     bucket = oss2.Bucket(auth, endpoint, bucket_name)
#     return bucket


# def download_file(bucket, object_name):
#     # This is sample code for downloading files from OSS
#     try:
#         file_obj = bucket.get_object(object_name)
#         return file_obj
#     except oss2.exceptions.OssError as e:
#         logger.error(f"File download failed {e}")


# def extract_and_upload(bucket, file_obj):
#     # Here you can define the logic for decompressing and uploading files to OSS
#     return 0;

Understand function code

  • def handler(event, context):

    • handler: This Python function serves as the request handler. While your code may include multiple functions, the request handler is the primary entry point for executing code. Ensure that the name of the request handler remains the same when making code modifications, to allow Function Compute to identify it accurately. For more information, see What is a request handler.

      image.png

    • event: The event parameter conveys relevant information when a function is triggered by an event. For instance, if a file is uploaded to OSS, the event includes details such as the Bucket name and file name, all formatted as a JSON object. For details on the information that the event parameter includes for different types of events, see Trigger event format.

    • The context object, which is passed to the function via the context parameter, includes details about the invocation, function configuration, and identity authentication. This authentication information is derived from the role permissions set for the function. Once the role is configured, Function Compute (FC) retrieves a temporary key (STS Token) through the AssumeRole operation and then supplies this key to your function within the credentials field of the context object. For more information, see Grant Function Compute access to other cloud services. To learn what information the context object contains, see Context.

  • logger.info(): You can use the standard logging function of the programming language to output logs. For example, in Python, use the logging module to output information to the log. This example uses statements to print the Bucket name, file name, and Region name. After the function call ends, you can view the log output through the console. For more information, see Log.

<

Node.js

In the console's WebIDE, open index.mjs, replace the existing code with the code provided below, and then click Deploy Code to apply the changes.

'use strict';
// import OSSClient from 'ali-oss'; // If you need to create an OSS client, uncomment this line

export const handler = async (event, context) => { // The request handler is the entry point for code execution
  console.log("Parsing event information...");
  const inputEvents = JSON.parse(event);
  if (!Array.isArray(inputEvents.events) || inputEvents.events.length === 0) { // Check the format of the incoming event
    throw new Error("Event format error: events array does not exist or is of length 0");
  }
  const eventObj = inputEvents.events[0];
  const bucketName = eventObj.oss.bucket.name; // Parse OSS Bucket name
  const objectName = eventObj.oss.object.key; // Parse file name
  const region = context.region;  // Parse the region where the function is located
  console.log(`OSS bucket name is ${bucketName}, object file name is ${objectName}, Region is ${region}`);
  // If you already have an OSS Bucket, you can uncomment the following line to create an OSS client instance
  // const bucket = getBucket(region, context)
  const bucket = null;
  const result = processEvent(bucket, objectName); // Call the subprogram to execute the event processing logic
  return result;
};


async function processEvent (bucket, objectName) {
  console.log("Starting event processing...");
  // Here you can write the event processing logic
  // const zipFile = downloadFile(bucket, objectName);
  // const result = extractAndUpload(bucket, zipFile);
  console.log("Event processing completed");
  const result = 0;
  return result;
}


// function getBucket (region, context) {
//   // Here, create an OSS Bucket client instance. The required identity authentication information can be obtained from the context
//   const bucket = new OSSClient({
//     region: region,
//     accessKeyId: context.credentials.accessKeyId,
//     accessKeySecret: context.credentials.accessKeySecret,
//     securityToken: context.credentials.securityToken
//   });
//   return bucket;
// }


// async function downloadFile (bucket, objectName) {
//   try {
//     // Sample code for downloading files from OSS
//     const result = await bucket.get(objectName, objectName);
//     console.log(result);
//     return result;
//   } catch (e) {
//     console.log(e);
//   }
// }

// async function extractAndUpload (bucket, zipFile) {
//     // Here you can define the logic for decompressing and uploading files to OSS
//     return 0;
// }

Understand function code

  • export const handler = async (event, context)

    • handler refers to the Node.js function that serves as the request handler. Although your code may include multiple Node.js functions, the request handler is the primary entry point for executing code. To ensure Function Compute can accurately recognize it, maintain the request handler's name when making code changes. For more information, see What is a request handler.

      2025-01-23_15-42-21 (1)

    • event: When an event triggers the function, the relevant information of the event is passed in through the event parameter (for example, in the event of uploading a file to OSS, event contains the Bucket name and Object name, etc.), formatted as a JSON object. For more information on what information the event contains for various events, see Trigger event format.

    • The context object, which is passed to the function via the context parameter, includes details about the invocation, function configuration, and identity authentication. This authentication data is derived from the role permissions set for the function. Once the role is configured, Function Compute (FC) retrieves a temporary key (STS Token) through the AssumeRole operation and then supplies this key to your function within the credentials field of the context object. For more information, see Grant Function Compute access to other cloud services. To learn what information the context object contains, see Context.

  • The console.log() function is the standard method for logging in many programming languages. In Node.js, for instance, you can use the console module to write information to the log. This particular example demonstrates how to print the Bucket name, file name, and Region name. Once the function execution completes, you can review the log output in the console. For more information, see Log.

5. Test function

To simulate a file upload to OSS triggering the function, define a simulated event and use it to initiate the function.

Beyond simulated events, real OSS events can also trigger the function for testing purposes. For more information, see What to do next.
  1. Create a simulated event: On the Function Details page, click the Code tab. Then, click the drop-down box next to Test Function and select Configure Test Parameters. In the Event Template, choose Object Storage Service (OSS) to automatically generate a simulated event that mirrors a real OSS event.

    You can customize the Event Name and parameters within the event object, such as the OSS Bucket name and file name. Once finished, click Confirm.

    image.png

    Example OSS Simulated Event

    The example event content shown in the screenshot above is as follows. Paste it into the test parameters text box and proceed to the next step.

    {
        "events": [
            {
                "eventName": "ObjectCreated:PutObject",
                "eventSource": "acs:oss",
                "eventTime": "2024-08-13T06:45:43.000Z",
                "eventVersion": "1.0",
                "oss": {
                    "bucket": {
                        "arn": "acs:oss:cn-hangzhou:164901546557****:test-bucket",
                        "name": "test-bucket",
                        "ownerIdentity": "164901546557****"
                    },
                    "object": {
                        "deltaSize": 122539,
                        "eTag": "688A7BF4F233DC9C88A80BF985AB****",
                        "key": "source/example.zip",
                        "size": 122539
                    },
                    "ossSchemaVersion": "1.0",
                    "ruleId": "9adac8e253828f4f7c0466d941fa3db81161****"
                },
                "region": "cn-hangzhou",
                "requestParameters": {
                    "sourceIPAddress": "140.205.XX.XX"
                },
                "responseElements": {
                    "requestId": "58F9FF2D3DF792092E12044C"
                },
                "userIdentity": {
                    "principalId": "164901546557****"
                }
            }
        ]
    }
  2. Click Test Function to trigger the function immediately. After a successful execution, review the Return Result. A return code of 0 indicates the event was processed successfully. To examine the log details from the function execution, click Log Output.

    During function testing, Function Compute passes the simulated event content to the request handler handler via the event parameter and executes the code you defined, which includes parsing the event parameter and processing the file.

    image.png

6. (Optional) Clean up resources

Function Compute charges are based on actual resource consumption. Resources created for functions will not incur charges when not in use. However, be mindful of potential costs from other associated cloud products or resources, such as data storage in OSS and NAS, any created triggers, or provisioned instances.

To delete a function, log on to the Function Compute console, click Functions, select the appropriate region, and in the Operation column for the desired function, choose More > Delete. In the ensuing dialog box, ensure that the function has no associated resources like triggers or provisioned instances, then confirm the deletion.

image

What to do next

Having created an event function through the console, modified the request handler, and tested the function with a simulated event, you may follow these steps according to your business needs:

  • Add Triggers:

    • If you don't have an OSS Bucket, this topic provides a simulated OSS file upload event for testing. To integrate with your actual business, you should add an OSS trigger to the function. For more information, see Configure native OSS triggers.

    • Beyond Object Storage Service, various Alibaba Cloud services such as message queues, Tablestore, and SLS can also trigger Function Compute. For a comprehensive list of supported triggers, see Introduction to triggers.

  • Add Dependencies: While the built-in runtime includes common dependency libraries for event processing, it might not suffice for your specific business needs. The easiest solution is to package your code and additional dependency libraries into a ZIP file and upload it to Function Compute. For detailed instructions, see Deploy code package. To reduce the code package size and accelerate function cold starts, consider managing dependencies through layers. For more details, see Create custom layers.

  • Configure Logs: For easier debugging, troubleshooting, or to fulfill security audit requirements, configuring logs for your function is advisable. For step-by-step guidance, see Configure logs.

References

  • Besides the console, you can use the Serverless Devs command-line tool to create functions. For more information, see Quick Start.

  • For a deeper understanding of event functions, consider the following practice tutorials: