All Products
Search
Document Center

Function Compute:Use event functions to process events from Alibaba Cloud services

Last Updated:Apr 01, 2026

In this tutorial, you create an event function that processes OSS upload events, test it using a simulated event, and learn how the event and context handler parameters work — all without needing an OSS bucket.

Prerequisites

Register an Alibaba Cloud account

Before you begin, ensure that you have:

  • An Alibaba Cloud account with real-name authentication completed

  • Function Compute activated

Activate Function Compute

Activating Function Compute:

If your account was registered on or after August 27, 2024 and has completed real-name authentication, Function Compute is automatically activated. Log on to the Function Compute console to get a free trial.

If your account was registered before August 27, 2024, activate Function Compute manually:

  1. Go to the Function Compute product page.

  2. Click Console, then click Buy Now to activate Function Compute and open the Function Compute console.

  3. (Optional) If this is your first time logging on, click OK in the Alibaba Cloud Service Authorization dialog to create a service-linked role. This grants Function Compute access to other Alibaba Cloud services, including Virtual Private Cloud (VPC), Elastic Compute Service (ECS), Simple Log Service, and Container Registry. For more information, see Service-linked role of Function Compute.

Activate Function Compute with your Alibaba Cloud account, then manage functions using a Resource Access Management (RAM) user with minimal required permissions. For details, see Policies and sample policies.

How it works

When an event occurs — such as a file upload to Object Storage Service (OSS) or an alert from a monitoring service — a preconfigured trigger invokes your event function automatically. Function Compute provisions instances on demand, scales them as needed, and destroys them after processing. You pay only for the resources consumed.

The scenario this tutorial simulates: files are uploaded as ZIP archives to OSS for transfer efficiency, and an event function decompresses them and saves the output back to OSS.

image

This tutorial uses a simulated OSS upload event — no actual OSS bucket required. The function parses the event, extracts bucket and file metadata, and prints the results to the Function Compute console.

Step 1: Select the function type

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions. In the top navigation bar, select a region, such as China (Hangzhou).

  2. Click Create Function.

  3. On the Create Function page, click Event Function. Enter a Function Name or keep the default.

image

Step 2: Select the runtime

Built-in runtimes include preinstalled dependencies for responding to events from other Alibaba Cloud services. For example, the built-in Python runtime includes oss2 for OSS access, and the built-in Node.js runtime includes ali-oss. Select the runtime for your preferred language:

Python

For Runtime, select Built-in Runtimes > Python > Python 3.10.

image
If you use a custom runtime or a Custom Container runtime instead, install the required dependencies manually. For a comparison of runtime types, see Function runtime environment selection. For more information about built-in runtime environments, see Overview (Python) or Overview (Node.js).

Node.js

For Runtime, select Built-in Runtimes > Node.js > Node.js 20.

image

Step 3: Create the function

Use the Hello, world! sample code. Keep the defaults for Advanced Settings and Environment Variables, then click Create.

image

After creation, WebIDE opens on the Code tab and shows the generated handler template. You'll replace this template with the event-processing code in the next step.

image.png

Step 4: Deploy the event-processing code

Interpreted languages like Python and Node.js support editing and deploying code directly in WebIDE. Compiled languages like Java require local compilation and package upload.

Python

Open index.py in WebIDE, replace the existing code with the following, and click Deploy.

index.py

# -*- coding: utf-8 -*-
import logging
import json
# import oss2  # Uncomment this section if you want to create an OSS client instance.
logger = logging.getLogger()


def handler(event, context): # The handler serves as 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("Invalid event format: events array is missing or empty")
    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 region where the function is located.
    logger.info(f"OSS bucket: {bucket_name}, file: {object_name}, region: {region}")
    # If you already have an OSS bucket, uncomment the following section to create an OSS client instance.
    # bucket = get_bucket(region, bucket_name, context)
    bucket = None
    result = process_event(bucket, object_name)  # Invoke event processing subroutine.
    return result


def process_event(bucket, object_name):
    logger.info("Starting event processing...")
    # Add logic here for event processing.
    # zip_file = download_file(bucket, object_name)
    # result = extract_and_upload(bucket, zip_file)
    logger.info("Event processing completed")
    result = 0
    return result  # 0 indicates successful event processing.


# def get_bucket(region, bucket_name, context):
#     # Create an OSS bucket client instance. The required authentication information can be obtained from the context.
#     creds = context.credentials  # Obtain the Security Token Service (STS) token.
#     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):
#     # Example 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"File download failed: {e}")


# def extract_and_upload(bucket, file_obj):
#     # Add logic here to decompress files and upload them to OSS.
#     return 0;

Node.js

Open index.mjs in WebIDE, replace the existing code with the following, and click Deploy.

index.mjs

'use strict';
// import OSSClient from 'ali-oss'; // Uncomment this section if you want to create an OSS client instance.

export const handler = async (event, context) => { // The handler serves as 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("Invalid event format: events array is missing or empty");
  }
  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 region where the function is located.
  console.log(`OSS bucket: ${bucketName}, object: ${objectName}, region: ${region}`);
  // If you already have an OSS bucket, uncomment the following section to create an OSS client instance.
  // const bucket = getBucket(region, context)
  const bucket = null;
  const result = processEvent(bucket, objectName); // Invoke event processing subroutine.
  return result;
};


async function processEvent (bucket, objectName) {
  console.log("Starting event processing...");
  // Add logic here for event processing.
  // 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. The required 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 {
//     // Example 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) {
//     // Add logic here to decompress files and upload them to OSS.
//     return 0;
// }

About the handler parameters (optional)

The handler is the entry point for all function executions. Keep the handler name unchanged so Function Compute can locate it correctly.

`event`

Carries event-related data when a trigger invokes the function — for example, the bucket name and file name in an OSS upload event. The parameter is a JSON object. For the exact structure per trigger type, see Formats of event for different triggers.

`context`

Carries function invocation details, configuration, and authentication credentials. Function Compute calls the AssumeRole operation to get a Security Token Service (STS) token based on the role assigned to your function, then passes it via the credentials field in the context object. For the complete context structure, see Context (Python) or Context (Node.js).

Logging

Use the standard logging library for your runtime to write logs during execution. This sample logs the bucket name, file name, and region. View logs on the Log Output tab after the function runs.

  • Python: logging module, logger.info(). For details, see Logs.

  • Node.js: console module, console.log(). For details, see Logs.

For more information, see What is a handler? (Python) or What is a handler? (Node.js).

Step 5: Test the function

The following steps use a simulated OSS event, which doesn't require an actual OSS bucket. To test with real OSS events instead, see Advanced operations.

  1. On the Function Details page, click the Code tab. Click the drop-down icon next to Test Function and select Configure Test Parameters.

  2. In the Configure Test Parameters panel, select OSS from the Event Template drop-down list. A simulated event is generated in the same JSON format as a real OSS event. Optionally, set an Event Name and customize field values such as the bucket name and file name. Click OK.

    image.png

    Example simulated OSS event

    The following event matches the configuration shown in the screenshot above. Paste it into the test parameters to follow along:

    {
        "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****"
                }
            }
        ]
    }
  3. Click Test Function. Function Compute passes the simulated event to the handler via the event parameter and runs the deployed code.

  4. After execution, check the Response tab. A return value of 0 indicates successful processing. Click Log Output to review the log entries generated during execution.

    image.png

Step 6: (Optional) Clean up resources

Function Compute charges only when functions are invoked, so idle functions don't incur costs. If you no longer need the function, delete it to avoid charges from other resources it may reference (such as data in OSS or File Storage NAS (NAS)).

To delete the function, log on to the Function Compute console. In the left-side navigation pane, click Functions and select a region. Find the function, click the vertical ellipsis icon in the Actions column, and select Delete. Confirm that the function is not bound to any resources, then click Delete.

image

Advanced operations

You've created an event function, deployed event-processing code, and tested it with a simulated event. For production use cases, consider the following:

  • Add a trigger: The demo above used a simulated event. To process real OSS upload events, add an OSS trigger to your function. For details, see Configure a native OSS trigger. Function Compute also supports triggers from message queue services, Tablestore, Simple Log Service, and other Alibaba Cloud services. For all supported types, see Trigger overview.

  • Add dependencies: Each built-in runtime includes common event-processing libraries, but your use case may require additional ones. Package your code and extra dependencies into a ZIP file and deploy it to Function Compute. For steps, see Deploy a code package. To reduce package size and mitigate cold starts, manage shared dependencies as layers. For details, see Create a custom layer.

  • Configure logging: Set up the logging feature to simplify debugging, troubleshooting, and security auditing. For steps, see Configure the logging feature.

What's next

References