All Products
Search
Document Center

Function Compute:Configure a native OSS trigger

Last Updated:Apr 14, 2026

You can create and configure a native OSS trigger in the Function Compute console. When a specific event occurs in OSS, the trigger automatically invokes your function. This lets you easily respond to events such as file uploads and quickly implement a complete workflow without adding event-listening logic to your code.

Example scenario

You can configure an OSS trigger and set its object prefix to source. When an image is uploaded to the source directory in the specified OSS bucket, the trigger automatically invokes the function. The function resizes the image and saves it to the processed directory in the same bucket. For example, the function processes source/a.png and saves the result as processed/a.png.

Prerequisites

Limitations

  • A single bucket can have a maximum of 10 native OSS triggers.

    Note

    If you need to associate more OSS triggers with a bucket, you can create EventBridge-based OSS triggers. However, we recommend against associating more than 10 triggers with a single bucket. If you need more, consider creating a new bucket and configuring triggers for it.

  • Native OSS triggers and EventBridge-based OSS triggers do not support wildcard or regular expression matching for object prefixes and suffixes.

  • A native OSS trigger supports only one object prefix and one object suffix. To configure multiple prefixes or suffixes, use an EventBridge-based OSS trigger.

Step 1: Create an OSS trigger

  1. Log on to the Function Compute console. In the left-side navigation pane, click Functions.

  2. In the top navigation bar, select a region. On the Functions page, click the function that you want to manage.

  3. On the function details page, select the Trigger tab and click Create Trigger. In the Create Trigger panel, configure the parameters and click OK.

    Parameter

    Actions

    Example

    Trigger Type

    Select OSS.

    OSS

    Name

    Enter a custom name for the trigger.

    oss-trigger

    Version or Alias

    The default value is LATEST. If you want to create a trigger for a different version or alias, you must first select it from the Version or Alias drop-down list on the function details page. For more information about versions and aliases, see Manage versions and Manage aliases.

    LATEST

    Bucket Name

    Select the OSS bucket that you created.

    testbucket

    Object Prefix

    Enter the prefix of the object names to match. We recommend that you specify both an object prefix and an object suffix to prevent recursive trigger invocations that can cause extra charges. In addition, if different triggers in the same bucket share the same event type, their prefixes and suffixes must not be identical. For more information, see Triggering rules for OSS triggers.

    Important

    The object prefix cannot start with a forward slash (/). Otherwise, the trigger cannot be invoked.

    source

    Object Suffix

    Enter the suffix of the object names to match. We strongly recommend that you specify both a prefix and a suffix to prevent recursive trigger invocations that can cause extra charges. In addition, if different triggers in the same bucket share the same event type, their prefixes and suffixes must not be identical. For more information, see Triggering rules for OSS triggers.

    png

    Trigger Event

    Select one or more trigger events. For more information about the event types for OSS, see OSS event definitions.

    This example uses oss:ObjectCreated:PutObject.

    oss:ObjectCreated:PutObject, oss:ObjectCreated:PostObject, oss:ObjectCreated:CompleteMultipartUpload, oss:ObjectCreated:PutSymlink

    Role Name

    Select AliyunOSSEventNotificationRole.

    Note

    If this is your first time creating this type of trigger, click Authorize Now in the dialog box that appears after you click OK.

    AliyunOSSEventNotificationRole

    After the trigger is created, it is displayed on the Triggers tab. To modify or delete a trigger, see Trigger Management.

Step 2: (Optional) Configure function input parameters

The OSS event source passes data to your function as an event object. You can parse and process this object in your code. You can also manually pass a sample event to the function to simulate a trigger and test your code.

  1. On the Code tab of the function details page, click the image.png icon next Test Function and select Configure Test Parameters from the drop-down list.

  2. In the Configure Test Parameters panel, select the Create New Test Event or Modify Existing Test Event tab. Enter an event name and the event content, and then click OK.

    Note

    Configure the event content based on the information that you provided when you created the trigger. Make sure that the specified object, source/a.png in this example, exists in the bucket. Otherwise, the function will not be invoked, or the invocation will fail.

    The event is an input parameter for a Function Compute function. When an object is created or deleted in the specified OSS bucket, OSS sends the event data to the bound function in JSON format. The following shows an example:

    {
        "events": [
            {
                "eventName": "ObjectCreated:PutObject",
                "eventSource": "acs:oss",
                "eventTime": "2022-08-13T06:45:43.000Z",
                "eventVersion": "1.0",
                "oss": {
                    "bucket": {
                        "arn": "acs:oss:cn-hangzhou:123456789:testbucket",
                        "name": "testbucket",
                        "ownerIdentity": "164901546557****"
                    },
                    "object": {
                        "deltaSize": 122539,
                        "eTag": "688A7BF4F233DC9C88A80BF985AB****",
                        "key": "source/a.png",
                        "objectMeta": {
                           "mimeType": "application/zip",
                           "userMeta": {
                              "x-oss-meta-last-modified":"20250213"
                           }
                        },
                        "size": 122539
                    },
                    "ossSchemaVersion": "1.0",
                    "ruleId": "9adac8e253828f4f7c0466d941fa3db81161****"
                },
                "region": "cn-hangzhou",
                "requestParameters": {
                    "sourceIPAddress": "140.205.XX.XX"
                },
                "responseElements": {
                    "requestId": "58F9FF2D3DF792092E12044C"
                },
                "userIdentity": {
                    "principalId": "164901546557****"
                }
            }
        ]
    }

    The following table describes the parameters in an event object.

    Parameter

    Type

    Value

    Description

    eventName

    String

    ObjectCreated:PutObject

    The event type.

    eventSource

    String

    acs:oss

    The event source. The value is fixed to acs:oss.

    eventTime

    String

    2022-08-13T06:45:43.000Z

    The time when the event occurred, in ISO 8601 format.

    eventVersion

    String

    1.0

    The version of the event protocol.

    oss

    Map

    Contains the OSS event details.

    bucket

    Map

    The value of the bucket parameter.

    name

    String

    testbucket

    The name of the bucket.

    arn

    String

    acs:oss:cn-hangzhou:123456789:testbucket

    The unique identifier of the bucket.

    ownerIdentity

    String

    164901546557****

    The ID of the user who created the bucket.

    object

    Map

    The content of the object parameter.

    size

    Int

    122539

    The size of the object. Unit: Byte.

    deltaSize

    Int

    122539

    The change in the size of the object. Unit: Byte.

    • If a new object is added, this value is the object size.

    • If an existing object is overwritten with an object of the same name, this value is the size difference between the new and old objects.

    eTag

    String

    688A7BF4F233DC9C88A80BF985AB****

    The ETag of the object.

    key

    String

    source/a.png

    The full path of the object.

    objectMeta

    Map

    objectMeta parameter content.

    mimeType

    String

    application/zip

    The file type of the object. For more information, see mimeType.

    userMeta

    Map

    The user metadata that identifies the purpose or attributes of the object.

    x-oss-meta-last-modified

    String

    20250213

    User metadata consists of key-value pairs. The metadata key must start with x-oss-meta-. For example, the pair "x-oss-meta-last-modified":"20250213" indicates that the local file was last modified on February 13, 2025. For more information, see User metadata.

    ossSchemaVersion

    String

    1.0

    The OSS schema version.

    ruleId

    String

    9adac8e253828f4f7c0466d941fa3db81161****

    The ID of the trigger rule that the event matched.

    region

    String

    cn-hangzhou

    The bucket's region.

    requestParameters

    Map

    The request parameters.

    sourceIPAddress

    String

    140.205.XX.XX

    The source IP address of the request.

    responseElements

    Map

    The response elements.

    requestId

    String

    58F9FF2D3DF792092E12044C

    The request ID.

    userIdentity

    Map

    The identity of the user who made the request.

    principalId

    String

    164901546557****

    The ID of the Alibaba Cloud account that initiated the request.

Step 3: Write and test function code

After you create the OSS trigger, you can write and test the function code to verify that it works correctly. In a real-world scenario, the trigger automatically invokes the function when the specified OSS event occurs.

Warning

You must prevent recursive invocations in your code. A common recursive scenario occurs when a function is triggered by an object upload to an OSS bucket. After the function runs, it generates one or more new objects and writes them back to the same bucket. This write operation triggers the function again, creating an infinite loop. For more information, see Triggering rules for OSS triggers.

  1. On the Code tab of the function details page, enter your code in the editor and click Deploy.

    • The following sample code is for runtimes that support online editing.

      Note

      We recommend that you use an internal OSS endpoint to read data from and write data to OSS buckets in your function. If you use a public endpoint, you incur internet data transfer charges. For more information about internal endpoints, see Regions and endpoints.

      "use strict";
      /*
      This sample code shows you how to perform the following operations:
      * 1. Parse OSS event information from the event.
      * 2. Initialize the OSS client based on the parsed information.
      * 3. Resize the source image and save it to a destination directory in the same bucket.
      */
      
      const OSS = require("ali-oss");
      
      exports.handler = async function(event, context, callback) {
          console.log("The content in context entity is: \n");
          console.dir(context);
      
          const {accessKeyId, accessKeySecret, securityToken} = context.credentials;
      
          const events = JSON.parse(event.toString()).events;
          console.log("The content in event entity is: \n");
          console.dir(events);
      
          let objectName = events[0].oss.object.key;
          let region = events[0].region;
          let bucketName = events[0].oss.bucket.name;
      
          // Connect to the target OSS bucket.
          const client = new OSS({
              region: region,
              accessKeyId: accessKeyId,
              accessKeySecret: accessKeySecret,
              stsToken: securityToken,
              bucket: bucketName,
              endpoint: "https://oss-" + region + "-internal.aliyuncs.com"
          });
      
          console.log("The client entity is: \n");
          console.dir(events);
      
          const targetImage = objectName.replace("source/", "processed/")
          // Resize the image to a fixed width and height of 128 px.
          const processStr = "image/resize,m_fixed,w_128,h_128"
          // Resize the source image and save the processed image to the destination path.
          const result = await client.processObjectSave(
              objectName,
              targetImage,
              processStr,
              bucketName
          );
          console.log(result.res.status);
      
          callback(null, "done");
      }
      """
      This sample code shows you how to perform the following operations:
      * Get OSS processing-related information from the event.
      * Initialize the OSS client with the target bucket.
      * Resize the source image and save it to a destination directory.
      """
      
      # -*- coding: utf-8 -*-
      import oss2, json
      import base64
      
      def handler(event, context):
          # Obtain key information from context.credentials.
          print("The content in context entity is: \n")
          print(context)
          creds = context.credentials
      
          # Configure authentication for the OSS SDK.
          auth = oss2.StsAuth(
              creds.access_key_id,
              creds.access_key_secret,
              creds.security_token)
      
          print("The content in event entity is: \n")
          print(event)
          # Load event content.
          oss_raw_data = json.loads(event)
          # Get OSS event parameters passed by the OSS trigger.
          oss_info_map = oss_raw_data['events'][0]['oss']
          # Get the OSS bucket name.
          bucket_name = oss_info_map['bucket']['name']
          # Set the OSS endpoint.
          endpoint = 'oss-' + oss_raw_data['events'][0]['region'] + '-internal.aliyuncs.com'
          # Initialize the OSS client.
          bucket = oss2.Bucket(auth, endpoint, bucket_name)
          object_name = oss_info_map['object']['key']
      
          # Download the original image from the OSS bucket.
          remote_stream = bucket.get_object(object_name)
          if not remote_stream:
              print(f'{object_name} does not exist in bucket {bucket_name}')
              return
          # Processed images are saved to the processed/ directory.
          processed_path = object_name.replace('source/', 'processed/')
      
          # Resize the image to a fixed width and height of 128 px.
          style = 'image/resize,m_fixed,w_128,h_128'
          # Specify the name of the processed image. If the image is not in the root directory of the bucket, you must specify the full path of the image. Example: exampledir/example.jpg.
          process = "{0}|sys/saveas,o_{1},b_{2}".format(style,
              oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(processed_path))),
              oss2.compat.to_string(base64.urlsafe_b64encode(oss2.compat.to_bytes(bucket_name))))
          result = bucket.process_object(object_name, process)
          print(result)
      /*
      *This sample code shows you how to perform the following operations:
      * 1. Parse the endpoint, bucket, and object from the event.
      * 2. Initialize the OSS client based on the parsed information.
      * 3. Resize the source image and save the processed image to a destination directory in the same bucket.
      */
      <?php
      
      use RingCentral\Psr7\Response;
      use OSS\OssClient;
      use OSS\Core\OssException;
      
      function base64url_encode($data)
      {
          return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
      }
      
      function handler($event, $context) {
        $event           = json_decode($event, $assoc = true);
        /*
          An AccessKey pair of an Alibaba Cloud account has permissions on all API operations. We recommend that you use a RAM user to call API operations or perform routine O&M.
          Do not hard-code the AccessKey ID and AccessKey secret in your project code. Otherwise, the AccessKey pair may be leaked, which compromises the security of all resources in your account.
          This example shows how to obtain the AccessKey pair from the context.
        */
        $accessKeyId     = $context["credentials"]["accessKeyId"];
        $accessKeySecret = $context["credentials"]["accessKeySecret"];
        $securityToken   = $context["credentials"]["securityToken"];
        $evt        = $event['events']{0};
        $bucketName = $evt['oss']['bucket']['name'];
        $endpoint   = 'oss-' . $evt['region'] . '-internal.aliyuncs.com';
        $objectName = $evt['oss']['object']['key'];
        $targetObject = str_replace("source/", "processed/", $objectName);
      
          try {
              // Connect to OSS.
              $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
              // Resize the image to a fixed width and height of 128 px.
              $style = "image/resize,m_fixed,w_128,h_128";
              $process = $style.
                 '|sys/saveas'.
                 ',o_'.base64url_encode($targetObject).
                 ',b_'.base64url_encode($bucketName);
              // Resize the image and save it to the destination object.
              $result = $ossClient->processObject($bucketName, $objectName, $process);
              // Print the processing result.
              print($result);
          } catch (OssException $e) {
              print_r(__FUNCTION__ . ": FAILED\n");
              printf($e->getMessage() . "\n");
          }
      
          print(__FUNCTION__ . ": OK" . "\n");
      
          return $targetObject;
      }
  2. Test the function.

    Method 1: If you configured the event input parameter to simulate an event source, click Test Function.

    Method 2: On the Configuration > Trigger page, click the Bucket Name to go to the corresponding bucket. Upload an image that matches the specified object prefix and suffix. After the function runs, you can view the execution logs on the Logs tab and check the result in the destination folder of the bucket.

FAQ

References