All Products
Search
Document Center

Function Compute:Configure a native OSS trigger

Last Updated:Mar 25, 2024

You can create a native Object Storage Service (OSS) trigger in the Function Compute console to allow specific OSS 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 prefix to source in the trigger rule. When an image is stored in the source directory of the specified OSS bucket, the function is automatically triggered. 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.

Before you start

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, use EventBridge-based OSS triggers. We recommend that you do not associate more than 10 OSS triggers with a bucket. If you need more than 10 OSS triggers, you can create a new bucket and create OSS triggers based on the new bucket.

  • In both native OSS triggers and EventBridge-based OSS triggers, fuzzy matching and regular expression matching are not supported based on object prefixes and suffixes you configure. If you want to configure multiple object prefixes and suffixes, you can 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, click the Configurations tab. In the left-side navigation pane, click Triggers. Then, click Create Trigger.

  4. In the Create Trigger panel, configure parameters and click OK.

    Parameter

    Description

    Example

    Trigger Type

    The type of the trigger. Select OSS.

    OSS

    Name

    Enter the trigger name.

    oss-trigger

    Version or Alias

    The version or alias. The default value is LATEST. If you want to create a trigger of another version or alias, select the 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

    The name of the OSS bucket. Select an OSS bucket from the drop-down list.

    testbucket

    Object Prefix

    The prefix of the object that you want to match. We recommend that you configure Object Prefix and Object Suffix to prevent extra costs that are generated by nested loops. If you specify the same event type for different triggers of a bucket, the prefix and suffix cannot be the same. For more information, see Rules for triggering native OSS triggers.

    Important

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

    source

    Object Suffix

    The suffix of the objects that you want to match. We recommend that you configure Object Prefix and Object Suffix to prevent extra costs that are generated by nested loops. If you specify the same event type for different triggers of a bucket, the prefix and suffix cannot be the same. For more information, see Triggering rules.

    png

    Trigger Event

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

    For example, you can select oss:ObjectCreated:PutObject.

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

    Role Name

    The name of the role. In this example, AliyunOSSEventNotificationRole is selected.

    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 a trigger, see Manage triggers.

Step 2: Configure input parameters of the function

The OSS event source is passed to the function in the form of event, which acts as an input parameter. You can manually pass event to the function to trigger the function.

  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, click the Create New Test Event or Modify Existing Test Event tab, enter the event name and event content, 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 the 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. Sample code:

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

    Parameter

    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 occurred. The time follows 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

    The 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 who created the bucket.

    object

    Map

    The 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 in which 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, function execution is triggered.

Warning

Avoid loops in the code. Example of a loop: When an object is uploaded to an OSS bucket, the upload operation triggers a function to generate a new object, which is written to the OSS bucket. The write operation triggers this function again. As a result, an invocation loop is formed. For more information, see Rules for triggering native OSS triggers.

  1. On the Code tab of the Function Details page, write code in the code editor and 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 buckets in your function, we recommend that you use an internal endpoint of OSS to access the OSS resources. If you use a public endpoint, you are charged for data transferred over the Internet. For more information about formats of internal endpoints of OSS, 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 source images and persist processed images to the specified destination path in the OSS bucket to implement image backup. 
      
      
      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 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/")
          // Resize 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 source images and persist processed images to the specified destination path in the OSS bucket to implement image backup. 
      
      
      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):
          # 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 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/')
      
          # Resize 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 source images and persist processed images to the specified destination path in the OSS bucket to implement image backup. 
      *
      *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 Function Compute 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 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);
              // 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);
              // 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. Click Test Function.

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

Troubleshooting

Additional information