All Products
Search
Document Center

Function Compute:Configure a native OSS trigger

Last Updated:Feb 13, 2025

You can create and configure a native OSS trigger within the Function Compute console. This setup automatically activates the function when specific OSS events, such as file uploads, occur, enabling you to seamlessly handle these events without integrating event listening logic into your code.

Sample scenario

By configuring an OSS trigger with a file prefix of source, any image stored in the source directory of a specified OSS bucket will automatically trigger the function. The function then resizes the image and saves it to the processed directory within the same bucket, converting source/a.png to processed/a.png.

Prerequisites

Limits

  • A native OSS trigger can be linked to a maximum of 10 triggers per bucket.

    Note

    To associate more than 10 OSS triggers with a bucket, consider creating EventBridge-based OSS triggers. It is advisable to limit the number of triggers per bucket to 10. For additional triggers, create a new bucket and set up triggers for that bucket.

  • Native OSS triggers and EventBridge-based OSS triggers do not support fuzzy or regular matching for file prefixes and suffixes.

  • A native OSS trigger supports only one file prefix and one file suffix. For multiple prefixes and suffixes, use EventBridge-based OSS triggers.

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, click the Configurations tab. In the left-side navigation pane, click Triggers. Then, click Create Trigger.

  4. In the Create Trigger panel, enter the necessary information, and then click OK.

    Configuration item

    Operation

    Example in this topic

    Trigger Type

    Select Object Storage Service (OSS).

    Object Storage Service (OSS)

    Name

    Enter a custom trigger name.

    oss-trigger

    Version Or Alias

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

    LATEST

    Bucket Name

    Select the OSS bucket that you created.

    testbucket

    File Prefix

    Enter the prefix of the file name to match. We recommend that you configure file prefixes and suffixes to avoid additional costs caused by nested loops. If you specify the same event type for different triggers in a bucket, the prefixes or suffixes cannot be the same. For more information, see OSS trigger rules.

    Important

    The file prefix cannot start with /, otherwise the OSS trigger cannot be triggered.

    source

    File Suffix

    Enter the suffix of the file name to match. We strongly recommend that you configure prefixes and suffixes to avoid additional costs caused by nested loops. If you specify the same event type for different triggers in a bucket, the prefixes or suffixes cannot be the same. For more information, see OSS trigger rules.

    png

    Triggering Event

    Select one or more triggering events. For more information about event types of Object Storage Service (OSS), see OSS event definitions.

    In this example, select oss:ObjectCreated:PutObject.

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

    Role Name

    Select AliyunOSSEventNotificationRole.

    Note

    If you create this type of trigger for the first time, you need to select Authorize Now in the pop-up dialog box 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 input parameters

The OSS event source is passed to the function as an input parameter in the form of an event. You can parse the event parameter in code to process the event. Alternatively, you can manually pass the event to the function to simulate a triggering event and test the function 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, you can either select Create New Test Event or Edit Existing Test Event , input the event name and content, and then click OK.

    Note

    Ensure the event content matches the trigger creation details. Verify that the specified file (e.g., source/a.png) exists in the bucket; otherwise, the function won't trigger or will fail to execute.

    The event serves as the input parameter for Function Compute. Upon the creation or deletion of an object in the designated OSS bucket, the event data, in JSON format, is transmitted to the linked function. The format is detailed below.

    {
        "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 event parameters.

    Parameter

    Type

    Example value

    Description

    eventName

    String

    ObjectCreated:PutObject

    The event type.

    eventSource

    String

    acs:oss

    The event source, which is fixed as acs:oss.

    eventTime

    String

    2022-08-13T06:45:43.000Z

    The time when the event occurred. The time follows the ISO 8601 standard format.

    eventVersion

    String

    1.0

    The version number of the event protocol.

    oss

    Map

    The content of the OSS event.

    bucket

    Map

    The content of the bucket parameter.

    name

    String

    testbucket

    The name of the bucket.

    arn

    String

    acs:oss:cn-hangzhou:123456789:testbucket

    The ARN of the bucket.

    ownerIdentity

    String

    164901546557****

    The ID of the user that created the bucket.

    object

    Map

    The content of the object parameter.

    size

    Int

    122539

    The size of the object in bytes.

    deltaSize

    Int

    122539

    The size difference of the object in bytes.

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

    • If a new object overwrites an existing object that has the same name, the value of this parameter indicates the size difference between the new object and the original object.

    eTag

    String

    688A7BF4F233DC9C88A80BF985AB****

    The object tag.

    key

    String

    source/a.png

    The name of the object.

    objectMeta

    Map

    The content of the objectMeta parameter.

    mimeType

    String

    application/zip

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

    userMeta

    Map

    User-defined metadata used to identify the purpose or properties of the object.

    x-oss-meta-last-modified

    String

    20250213

    Custom metadata is a set of key-value pairs. The metadata name must start with x-oss-meta-. In this example, the value "x-oss-meta-last-modified":"20250213" indicates that the last modification time of the local file is February 13, 2025. For more information, see User-defined metadata.

    ossSchemaVersion

    String

    1.0

    The version number of the OSS schema.

    ruleId

    String

    9adac8e253828f4f7c0466d941fa3db81161****

    The rule ID that matches the event.

    region

    String

    cn-hangzhou

    The region where the bucket resides.

    requestParameters

    Map

    The request parameters.

    sourceIPAddress

    String

    140.205.XX.XX

    The IP address from which the request is sent.

    responseElements

    Map

    The response details.

    requestId

    String

    58F9FF2D3DF792092E12044C

    The request ID.

    userIdentity

    Map

    The user attribute.

    principalId

    String

    164901546557****

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

Step 3: Write and test the function code

Once the OSS trigger is created, you can write and test the function code to ensure its accuracy. The function is triggered when an OSS event occurs.

Warning

Avoid code loops. A common loop occurs when a file upload in OSS triggers a function, which then writes back to the OSS bucket, causing another trigger. For more details, see OSS Trigger Rules.

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

    • Below is sample code for runtimes that support online editing.

      Note

      To avoid costs from Internet access, use OSS's internal endpoint for reading and writing data within your function. For endpoint formats, see OSS Regions and Endpoints.

      "use strict";
      /*
      This code sample mainly implements the following functions:
      * 1. Parse the OSS event trigger related information from the event.
      * 2. According to the above information, initialize the OSS client.
      * 3. Resize the source image and then store the processed image into the same bucket's copy folder to backup the image.
      */
      
      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
          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 then store the processed image into the target image path.
          const result = await client.processObjectSave(
              objectName,
              targetImage,
              processStr,
              bucketName
          );
          console.log(result.res.status);
      
          callback(null, "done");
      }
      """
      This sample code is mainly doing the following things:
      * Get OSS processing related information from event.
      * Initiate OSS client with target bucket.
      * Resize the source image and then store the processed image into the same bucket's copy folder to backup the image.
      
      """
      
      # -*- coding: utf-8 -*-
      import oss2, json
      import base64
      
      def handler(event, context):
          # Access keys can be fetched through context.credentials
          print("The content in context entity is: \n")
          print(context)
          creds = context.credentials
      
          # Setup auth, required by 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 related parameters passed by oss trigger.
          oss_info_map = oss_raw_data['events'][0]['oss']
          # Get oss bucket name.
          bucket_name = oss_info_map['bucket']['name']
          # Set oss service endpoint.
          endpoint = 'oss-' + oss_raw_data['events'][0]['region'] + '-internal.aliyuncs.com'
          # Initiate oss client.
          bucket = oss2.Bucket(auth, endpoint, bucket_name)
          object_name = oss_info_map['object']['key']
      
          # Download original image from 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 will be saved to processed/
          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 stored 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 code sample mainly implements the following functions:
      * 1. Parse out endpoint, bucket, object from request.
      * 2. According to the information obtained above, initialize the OSS client.
      * 3. Resize the source image and then store the processed image into the same bucket's copy folder to backup the image.
      */
      <?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);
        /*
          The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M.
          We recommend that you do not save AccesKey pairs (AccessKey IDs and AccessKey secrets) in your project code. Otherwise, the AccessKey pairs may be leaked and the security of all resources in your account may be compromised.
          In this example, the AccessKey pair is obtained 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 128px.
              $style = "image/resize,m_fixed,w_128,h_128";
              $process = $style.
                 '|sys/saveas'.
                 ',o_'.base64url_encode($targetObject).
                 ',b_'.base64url_encode($bucketName);
              // Resize image and save the processed images to the destination path.
              $result = $ossClient->processObject($bucketName, $objectName, $process);
              // Display the processed 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: To simulate the event source by configuring the function entry parameter event, click Test Function .

    Method 2: Navigate to the Configuration > Triggers page, click Bucket Name to access the relevant bucket, and upload an image that matches the predefined prefix and suffix. Once the process is complete, you can review the function logs under the function log tab and verify the outcomes in the bucket's target folder.

    image

    image

FAQ

References