All Products
Search
Document Center

Function Compute:Configure a native OSS trigger

Last Updated:May 07, 2024

You can create a native Object Storage Service (OSS) trigger in the Function Compute console to allow specific events to trigger function execution. This allows you to easily respond to events such as file uploads. You can quickly implement a complete process without adding event listening logic to your code.

Sample scenarios

You can configure an OSS trigger and set the Object Prefix parameter to source. The function is automatically triggered when an image is stored in the source directory of the specified OSS bucket. The function resizes the image and stores the processed image in the processed directory of the same bucket. For example, the source/a.png image is processed as processed/a.png.

Limits

  • You can associate a maximum of 10 native OSS triggers with a bucket.

    Note

    If you want to associate more OSS triggers with the bucket, create EventBridge-based OSS triggers. We recommend that you do not associate more than 10 OSS triggers with a bucket. If you require more than 10 OSS triggers, we recommend that you create a new bucket and create OSS triggers based on the new bucket.

  • Fuzzy match and regular expression match based on object prefixes and suffixes are not supported in both native and EventBridge-based OSS triggers. If you want to configure multiple object prefixes and suffixes, you can use an EventBridge-based OSS trigger.

Prerequisites

Step 1: Create an OSS trigger

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

  2. In the top navigation bar, select a region. On the Services page, click the desired service.

  3. On the Functions page, click the function that you want to manage.
  4. On the function details page, click the Triggers tab, select the version or alias from the Version or Alias drop-down list, and then click Create Trigger.
  5. In the Create Trigger panel, configure parameters and click OK. The following table describes the parameters.

    Parameter

    Description

    Example

    Trigger Type

    Specify the type of the trigger. In this example, select OSS.

    OSS

    Name

    Enter a trigger name.

    oss-trigger

    Version or Alias

    Specify the version or alias of the service. The default value is LATEST. If you want to create a trigger for another version or alias, select a version or alias 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 a bucket. In this example, select the bucket that you created from the drop-down list.

    testbucket

    Object Prefix

    Enter the prefix of an object name that you want to match. We recommend that you configure prefixes and suffixes to prevent extra 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 Triggering rules.

    Important

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

    source

    Object Suffix

    Enter the suffix of an object name that you want to match. We recommend that you configure prefixes and suffixes to prevent extra 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 Triggering rules.

    png

    Trigger Event

    Select one or more trigger events from the drop-down list. For more information about OSS event types, see OSS events.

    oss:ObjectCreated:PutObject, oss:ObjectCreated:PostObject, and oss:ObjectCreated:CompleteMultipartUpload

    Role Name

    Select AliyunOSSEventNotificationRole.

    Note

    After you configure the preceding parameters, click OK. If this is the first time that you create a trigger of this type, click Authorize Now in the message that appears.

    AliyunOSSEventNotificationRole

    After the trigger is created, it is displayed on the Triggers tab. To modify or delete an existing trigger, see Manage triggers.

Step 2: Configure input parameters of the function

An OSS event is passed to the function as an input parameter named event. You can manually pass event to the function to trigger the function.

  1. On the function details page, click the Code tab, click the xialatubiao icon next to Test Function, and then 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, configure Event Name and the event content in the code editor, and then click OK.

    Note

    Configure the event content based on the information about the trigger. Make sure that the specified object exists in the bucket. In this example, the object is source/a.png. Otherwise, the function cannot be triggered, or the function fails to be executed.

    event is an input parameter of Function Compute. When an object is created in the specified OSS bucket, the event data is sent to the corresponding function in the JSON format. The following code provides an example on how to configure event:

    {
        "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",
                        "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 fields in event.

    Field

    Data type

    Example

    Description

    eventName

    String

    ObjectCreated:PutObject

    The event type.

    eventSource

    String

    acs:oss

    The event source. Set the value to acs.oss.

    eventTime

    String

    2022-08-13T06:45:43.000Z

    The time when the event occurs. The time is in the ISO 8601 standard format.

    eventVersion

    String

    1.0

    The version of the event protocol.

    oss

    Map

    The content of the OSS event.

    bucket

    Map

    Details of the OSS bucket.

    name

    String

    testbucket

    The name of the bucket.

    arn

    String

    acs:oss:cn-hangzhou:123456789:testbucket

    The Alibaba Cloud Resource Name (ARN) of the bucket.

    ownerIdentity

    String

    164901546557****

    The ID of the user that created the bucket.

    object

    Map

    Details of the OSS object.

    size

    Int

    122539

    The size of the OSS object. Unit: bytes.

    deltaSize

    Int

    122539

    The variation of the size of the OSS object. Unit: bytes.

    • If an 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 object name.

    ossSchemaVersion

    String

    1.0

    The version of the OSS schema.

    ruleId

    String

    9adac8e253828f4f7c0466d941fa3db81161****

    The ID of the rule 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 elements.

    requestId

    String

    58F9FF2D3DF792092E12044C

    The request ID.

    userIdentity

    Map

    The property of the user.

    principalId

    String

    164901546557****

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

Step 3: Write function code and test the function

After you create the trigger, you can write function code and test the function to verify whether the code is correct. When an OSS event occurs, the function execution is triggered.

Warning

You must prevent loops in code. For example, when objects are uploaded to an OSS bucket, the upload operation triggers a function. Then, this function generates one or more objects to be written to the OSS bucket, and the write operation triggers this function again. This leads to a loop. For more information, see Triggering rules.

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

    • This section provides sample code for runtimes that support online editing.

      Note

      If you want to read data from and write data to OSS resources in your function, we recommend that you use an internal endpoint of OSS to access the OSS resources. If you use the public endpoint, you are charged Internet fees. For more information about the format of OSS internal endpoints, see Regions and endpoints.

      "use strict";
      /*
      The sample code is used to implement the following features:
      * 1. Parse the OSS event trigger information from event. 
      * 2. Initialize the OSS client based on the obtained information. 
      * 3. Resize the source images and persist the images to the specified destination path in the OSS bucket to back up the images. 
      
      
      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 back up 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 OSS bucket. 
          // 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/")
          // Scale images to a fixed width and height of 128 px. 
          const processStr = "image/resize,m_fixed,w_128,h_128"
          // Resize the source images and then store the processed images to the destination directory. 
          const result = await client.processObjectSave(
              objectName,
              targetImage,
              processStr,
              bucketName
          );
          console.log(result.res.status);
      
          callback(null, "done");
      }
      """
      The sample code is used to implement the following features:
      * Parse the OSS event trigger information from event. 
      * Initialize the OSS bucket client based on the obtained information. 
      * Resize the source images and persist the images to the specified destination path in the OSS bucket to back up images. 
      
      
      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 back up the image.
      
      """
      
      # -*- coding: utf-8 -*-
      import oss2, json
      import base64
      
      def handler(event, context):
          # You can use context.credentials to obtain the key information. 
          # Access keys can be fetched through context.credentials
          print("The content in context entity is: \n")
          print(context)
          creds = context.credentials
      
          # Configure the permissions for the OSS SDK. 
          # 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/')
      
          # Scale images 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 add 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)
      /*The sample code is used to implement the following features:
      *   1. Parse the endpoint, bucket, and object information from the request. 
      *   2. Initialize the OSS client based on the obtained information. 
      *   3. Resize the source images and persist the images to the specified destination path in the OSS bucket to back up the images. 
      *
      *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 can be used to access all API operations. Using these credentials to perform operations in Function Compute is a high-risk operation. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. 
          We recommend that you do not save the AccessKey ID and AccessKey secret to your project code. Otherwise, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. 
          In this example, the Access Key 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. 
              // Connect to OSS.
              $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false, $securityToken);
              // Scale 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);
              // 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. On the Code tab, click Test Function.

    After the function is executed, you can view the result on the Code tab.

FAQ

References