All Products
Search
Document Center

Function Compute:Configure a native OSS trigger

Last Updated:Nov 24, 2023

You can create an Object Storage Service (OSS) trigger to connect OSS to Function Compute. When a specific OSS event occurs, the function is triggered. This topic describes how to configure an OSS trigger in the Function Compute console and test the function code.

Sample scenarios

You can configure an OSS trigger and set Object Prefix 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

For native OSS triggers, a bucket can be associated with up to 10 triggers.

Note

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

Before you start

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 the parameters and click OK.

    Parameter

    Description

    Example

    Trigger Type

    The type of the trigger. Select OSS.

    OSS

    Name

    The name of the trigger.

    oss-trigger

    Version or Alias

    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

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

    testbucket

    Object Prefix

    Enter the prefix of the object names that you want to match. We recommend that you configure prefixes and suffixes to avoid extra costs that are generated by nested loops. If you specify the same event type for different triggers of a bucket, the prefixes or suffixes cannot be the same. For more information, see Rules for triggering native OSS triggers.

    Important

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

    source

    Object Suffix

    Enter the suffix of the object name that you want to match. We recommend that you configure Object Prefix and Object Suffix to avoid extra costs that are generated by function execution loops. If you specify the same event type for different triggers of a bucket, the prefixes or suffixes cannot be the same. For more information, see Rules for triggering native OSS triggers.

    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.

    In this example, oss:ObjectCreated:PutObject is selected.

    oss:ObjectCreated:PutObject

    Role Name

    The name of the role. 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

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 function details page, click the Code tab, click the xialatubiao icon next to 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, configure Event Name and the 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 the 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 details.

    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 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

Avoid loop in the 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 Rules for triggering native OSS triggers.

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

    • This section provides the sample code in the runtimes that support the online editor.

      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 for the data transferred over the Internet. For more information about the format of the 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 the source images and persist the 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/")
          // 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 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 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 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 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 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 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. 
              // 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

Q: How do I set Trigger Event if I want to trigger the function execution only once when an object is uploaded to OSS?

A: You can set Trigger Event to oss:ObjectCreated:PutObject, oss:ObjectCreated:PostObject, and oss:ObjectCreated:CompleteMultipartUpload.

If you call the multipart upload operation, the oss:ObjectCreated:InitiateMultipartUpload, oss:ObjectCreated:UploadPart, and oss:ObjectCreated:CompleteMultipartUpload events are triggered in sequence. For example, if you set Trigger Event to oss:ObjectCreated:*, the function is triggered five times if you upload a 12 MB object by using OSS Browser, and set the part size to 5 MB. The following five events are triggered: oss:ObjectCreated:InitiateMultipartUpload, oss:ObjectCreated:UploadPart, oss:ObjectCreated:UploadPart, oss:ObjectCreated:UploadPart, and oss:ObjectCreated:CompleteMultipartUpload.

For more information about how to trigger OSS triggers, see What do I do if a trigger cannot trigger function execution?

More information

In addition to the Function Compute console, you can configure triggers by using the following methods:
  • Use Serverless Devs to configure triggers. For more information, see Serverless Devs.
  • Use SDKs to configure triggers. For more information, see SDKs.

To modify or delete an existing trigger, see Manage triggers.