Event functions respond to various events from cloud services, such as files uploaded to Object Storage Service (OSS) or monitoring alerts. Write only the processing logic: no event integration, no compute to buy or manage. Instances start, scale, and stop on demand, so you pay only for what you use.
Example scenario
You have some files that you need to save to OSS. To speed up uploads, you first compress the files into ZIP format and then upload them, but you want to use the files directly rather than as a ZIP package, so you need an automated process to extract the files and save them back to OSS.
With the traditional implementation approach, you need to build and integrate multiple programs to monitor and process file changes on OSS, while also having to consider how to deploy and maintain these programs. With event functions, you can focus on the file handler. Each time a file is uploaded to OSS, an event is generated. If the event matches the conditions you set, the function is automatically triggered and runs your handler, and then automatically releases compute resources when finished to save costs.
Considering that you may not currently have an OSS bucket, this topic uses the following example to walk you through the implementation process of an event function:
Create an event that simulates an OSS file upload. This event calls an event function to process the file and prints information such as the file name and its bucket to the console.
By implementing this example, you will experience the following:
-
Complete the entire process of creating an event function, writing a request handler, and testing the function in the console;
-
learn key concepts such as Function Compute runtime environments and built-in runtimes;
-
learn about the request parameters event and context in a request handler.
Prerequisites
Register an Alibaba Cloud account
Register an Alibaba Cloud account and complete identity verification.
Activate the Function Compute service
If you registered an Alibaba Cloud account on or after August 27, 2024 and completed identity verification, you can use the Function Compute product directly without activation. When you log on to the Function Compute console for the first time, you can also claim a free resource plan of a certain quota by following the on-screen instructions. For more information, see Trial quota.
If your Alibaba Cloud account was registered before August 27, 2024, follow the steps below to activate the service.
-
Go to the Function Compute home page.
-
Click Console to go to the Activate Service page, and then click Activate Now to activate the service and go to the Function Compute console.
Use an Alibaba Cloud account to activate the service, and use a Resource Access Management (RAM) user to manage applications such as functions. Grant the RAM user the access policies required by your business following the Principle of Least Privilege (PoLP). For more information, see Policies and sample policies.
-
(Optional) When you log on to the Function Compute console for the first time, in the Alibaba Cloud Service Authorization dialog box that appears, click OK to create a service-linked role so that you can later use Function Compute to access related cloud services.
After the role is created, Function Compute can access your cloud resources such as Virtual Private Cloud (VPC), Elastic Compute Service (ECS), Simple Log Service (SLS), and Container Registry. For more information about service-linked roles, see Service-linked role of Function Compute.
Procedure
1. Select a function type
-
Log on to the Function Compute console. In the left-side navigation pane, choose . In the top menu bar, select the region where you want to create the function, click Create Function, and then select and create Event Function as prompted.
2. Select a runtime environment
Python
For Runtime, select Built-in Runtime > Python > Python 3.10.
For event functions, use the built-in runtime as the function runtime environment. This is because the built-in runtime includes the dependencies required to respond to events from other cloud products (for example, the oss2 module for Python). For more information, see Overview. If you use the custom runtime or custom image as the function runtime environment, you also need to install the required dependencies yourself. For a detailed comparison of various runtime environments, see Runtime environment selection.
Node.js
For Runtime, select Built-in Runtime > Node.js > Node.js 20.
For event functions, use the built-in runtime as the function runtime environment. This is because the built-in runtime includes the dependencies required to respond to events from other cloud products (for example, the ali-oss module for Node.js). For more information, see Overview. If you use the custom runtime or custom image as the function runtime environment, you also need to install the required dependencies yourself. For a detailed comparison of various runtime environments, see Runtime environment selection.
3. Create a function
Select the Hello, world! sample to create a function. Keep the default values for Advanced Settings, click Create, and then wait for the function to be created.
After the function is created, you can view the generated sample code in the WebIDE on the Code tab, using Python as an example.
# -*- coding: utf-8 -*-
import logging
import json
# To enable the initializer feature (https://www.alibabacloud.com/help/document_detail/2513452.html)
# please implement the initializer function as below:
# def initializer(context):
# logger = logging.getLogger()
# logger.info('initializing')
def handler(event, context):
# evt = json.loads(event)
logger = logging.getLogger()
logger.info('hello world')
return 'hello world'
The Hello, world! sample code automatically generates a function template with an entry program. Build your business code directly on this template through the following steps.
4. Modify the sample code and deploy
Interpreted languages such as Python and Node.js support modifying and deploying code directly in the WebIDE, whereas compiled languages such as Java only support compiling the code package locally and then uploading it, and do not support the WebIDE.
Python
In the WebIDE of the console, open index.py, replace the current code with the following code, and then click Deploy to make the modified code take effect.
index.py
# -*- coding: utf-8 -*-
import logging
import json
# import oss2 # Uncomment this line if you need to create an OSS client
logger = logging.getLogger()
def handler(event, context): # The 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 input event
raise Exception("Invalid event format: The events array does not exist or has a length of 0")
event_obj = input_events['events'][0]
bucket_name = event_obj['oss']['bucket']['name'] # Parse the OSS bucket name
object_name = event_obj['oss']['object']['key'] # Parse the file name
region = context.region # Parse the function region
logger.info(f"OSS bucket name: {bucket_name}, File name: {object_name}, Region: {region}")
# If you already have an OSS bucket, you can uncomment the following to create an OSS client instance
# bucket = get_bucket(region, bucket_name, context)
bucket = None
result = process_event(bucket, object_name) # Call a helper function to execute the event processing logic
return result
def process_event(bucket, object_name):
logger.info("Starting event processing...")
# You can write your event processing logic here
# zip_file = download_file(bucket, object_name)
# result = extract_and_upload(bucket, zip_file)
logger.info("Event processing completed...")
result = 0
return result # A return value of 0 indicates that the event is successfully processed
# def get_bucket(region, bucket_name, context):
# # Create an OSS bucket client instance here. The required identity authentication information can be obtained from the context
# creds = context.credentials # Obtain the temporary key
# 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 the sample code for downloading a file from OSS
# try:
# file_obj = bucket.get_object(object_name)
# return file_obj
# except oss2.exceptions.OssError as e:
# logger.error(f"Failed to download the file {e}")
# def extract_and_upload(bucket, file_obj):
# # You can define the logic for decompressing and uploading files to OSS here
# return 0;
Understanding the function code
-
def handler(event, context):
-
handler: This Python function is the handler. Your code may contain multiple Python functions, but the handler is always the entry point for code execution. When you modify the code, keep the handler name unchanged so that Function Compute can identify it correctly. For more information, see What is a handler?.
On the function details page of the Function Compute console, click the Function Details tab, select the Configuration sub-tab to view or edit the Request Handler field. The field format is [filename].[function_name], for example index.handler.
-
event: When an event triggers the function, information about the event (such as the bucket name and file name in an OSS file upload event) is passed in through the event parameter. This parameter is a JSON object. To learn about what information the event contains for various types of events, see Trigger event format.
-
context: The context object in which the function runs is passed to the function through the context parameter, and contains information such as the invocation, function configuration, and authentication. The authentication information comes from the role permissions configured for the function. After you configure a role for the function, Function Compute obtains a temporary key (STS token) by calling AssumeRole, and then passes the temporary key to your function through the context object's credentials field. For more information, see Use a function role to access other cloud services. To learn about what information the context object contains, see Context.
-
logger.info(): Use the standard logging feature of a programming language to output logs. For example, in Python, you can use methods such as the logging module to write information to logs. This example uses a statement to print the bucket name, file name, and region name. After the function call ends, you can view the log output in the console. For more information, see Logs.
Node.js
In the WebIDE of the console, open index.mjs, replace the current code with the following code, and then click Deploy to make the modified code take effect.
index.mjs
'use strict';
// import OSSClient from 'ali-oss'; // Uncomment this line if you need to create an OSS client
export const handler = async (event, context) => { // The 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 input event
throw new Error("Invalid event format: The events array does not exist or has a length of 0");
}
const eventObj = inputEvents.events[0];
const bucketName = eventObj.oss.bucket.name; // Parse the OSS bucket name
const objectName = eventObj.oss.object.key; // Parse the file name
const region = context.region; // Parse the function region
console.log(`OSS bucket name: ${bucketName}, File name: ${objectName}, Region: ${region}`);
// If you already have an OSS bucket, you can uncomment the following to create an OSS client instance
// const bucket = getBucket(region, context)
const bucket = null;
const result = processEvent(bucket, objectName); // Call a helper function to execute the event processing logic
return result;
};
async function processEvent (bucket, objectName) {
console.log("Starting event processing...");
// You can write your event processing logic here
// const zipFile = downloadFile(bucket, objectName);
// const result = extractAndUpload(bucket, zipFile);
console.log("Event processing completed");
const result = 0;
return result;
}
// function getBucket (region, context) {
// // Create an OSS bucket client instance here. 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 {
// // This is the sample code for downloading a file from OSS
// const result = await bucket.get(objectName, objectName);
// console.log(result);
// return result;
// } catch (e) {
// console.log(e);
// }
// }
// async function extractAndUpload (bucket, zipFile) {
// // You can define the logic for decompressing and uploading files to OSS here
// return 0;
// }
Understanding the function code
-
export const handler = async (event, context)
-
handler: This Node.js function is the handler. Your code may contain multiple Node.js functions, but the handler is always the entry point for code execution. When you modify the code, keep the handler name unchanged so that Function Compute can identify it correctly. For more information, see What is a handler?.

-
event: When an event triggers the function, information about the event (such as the bucket name and file name in an OSS file upload event) is passed in through the event parameter. This parameter is a JSON object. To learn about what information the event contains for various types of events, see Trigger event format.
-
context: The context object in which the function runs is passed to the function through the context parameter, and contains information such as the invocation, function configuration, and authentication. The authentication information comes from the role permissions configured for the function. After you configure a role for the function, Function Compute obtains a temporary key (STS token) by calling AssumeRole, and then passes the temporary key to your function through the context object's credentials field. For more information, see Use a function role to access other cloud services. To learn about what information the context object contains, see Context.
-
console.log(): Use the standard logging feature of a programming language to output logs. For example, in Node.js, you can use the console module to write information to logs. This example uses a statement to print the bucket name, file name, and region name. After the function call ends, you can view the log output in the console. For more information, see Logs.
5. Test the function
To simulate the scenario where a file upload to OSS triggers the function, define a mock event and use it to trigger the function.
In addition to testing with a mock event, you can also trigger the function with a real OSS event for testing. For more information, see Advanced operations.
-
Create a mock event: On the Function Details page, click the Code tab, click the drop-down list to the right of Test Function, and select Configure Test Parameters. In Event Template, select Object Storage Service (OSS). A mock event is then automatically generated, and the format of this event is the same as that of a real OSS event.
Customize the Event Name and the parameter values in the event object (for example, the OSS bucket name and file name). When finished, click OK.
OSS mock event example
The content of the example event is as follows. Paste it into the text box for the test parameters, and then proceed with the subsequent operations.
{
"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****"
}
}
]
}
-
On the Code tab, click Test Function to immediately trigger the function execution. After execution succeeds, view Response. The sample code returns 0, which indicates that the event is successfully processed. Click Log Output to view the log information output during function execution.
When you test the function, Function Compute passes the content of the mock event through the event parameter to the request handler handler, and runs the code you defined in the previous step, which parses the event parameter and processes the file.
The log output shows the following key information in sequence: FunctionCompute python3 runtime inited, followed by four [INFO] level log entries.
-
Parsing event information...
-
OSS bucket name: test-bucket, File name: source/example.zip, Region: cn-hangzhou
-
Starting event processing...
-
Event processing completed...
This indicates that the function has parsed the OSS information in the mock event and completed file processing.
6. (Optional) Clean up resources
Function Compute bills you based on actual resource usage, and a created function resource does not incur charges if it is not used. However, pay attention to the other cloud products or resources that you associated with the function when you created it, such as data stored in OSS and Apsara File Storage NAS (NAS).
To delete the function, log on to the Function Compute console. In the left-side navigation pane, choose , and then select the region. In the Actions column of the target function, click Delete. In the dialog box that appears, confirm that no resources such as triggers are bound to the function, and then confirm the deletion.
Advanced operations
Now you have created an event function through the console, modified the request handler, and tested the function with a mock event. Based on your business needs, you can refer to the following advanced operations:
-
Add a trigger:
-
Considering that you may not have an OSS bucket, the examples in this topic test by using a simulated OSS file upload event. If you want to apply this to your actual business later, you need to add an OSS trigger to the function. For more information, see Configure a native OSS trigger.
-
In addition to Object Storage Service, events from many Alibaba Cloud services (such as various message queue services, Tablestore, and SLS) can also trigger Function Compute. For a list of supported triggers, see Trigger overview.
-
Add dependencies: Although the built-in runtime includes the commonly used dependency libraries involved in event processing, they may still not meet the requirements of your actual business. In this case, the simplest approach is to package the code and additional dependency libraries into a ZIP file as a code package, upload it, and deploy it to Function Compute. For more information, see Deploy a code package. If you want to reduce the size of the code package to speed up the cold start of the function, you can manage dependencies through layers. For more information, see Create a custom layer.
-
Configure logging: To facilitate debugging and troubleshooting of the function or to meet requirements such as security auditing, we recommend that you configure logging for the function. For detailed steps, see Configure the logging feature.
References
-
In addition to creating a function in the console, you can also use the Serverless Devs command line interface to complete the preceding operations. For more information, see Get started with Function Compute using Serverless Devs.
-
Refer to the following hands-on tutorials to learn more about event functions: