

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 教學課程：使用 Amazon S3 觸發條件調用 Lambda 函數
<a name="with-s3-example"></a>

在本教學課程中，您將使用主控台建立 Lambda 函數，並設定 Amazon Simple Storage Service (Amazon S3) 儲存貯體的觸發條件。每當有物件新增至 Amazon S3 儲存貯體，該函數都會執行，然後將物件類型輸出至 Amazon CloudWatch Logs。

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3_tut_config.png)


本教學課程示範如何。

1. 建立 Amazon S3 儲存貯體。

1. 建立一個 Lambda 函數，用於傳回 Amazon S3 儲存貯體物件的物件類型。

1. 設定一個 Lambda 觸發條件，用於在有物件上傳至儲存貯體時調用函數。

1. 先使用虛擬事件測試函數，再使用觸發條件進行測試。

完成這些步驟後，您將了解如何設定 Lambda 函數，讓函數在 Amazon S3 儲存貯體中有物件新增或刪除時執行。您只能使用  AWS 管理主控台 來完成本教學課程。

## 建立 Amazon S3 儲存貯體
<a name="with-s3-example-create-bucket"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps1.png)


**建立 Amazon S3 儲存貯體**

1. 開啟 [Amazon S3 主控台](https://console.aws.amazon.com/s3)，然後選取**一般用途儲存貯體**頁面。

1. 選取最 AWS 區域 接近您地理位置的 。可使用螢幕頂端的下拉式清單來變更區域。在本教學課程稍後的階段，您必須在同一區域中建立 Lambda 函數。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/console_region_select.png)

1. 選擇**建立儲存貯體**。

1. 在 **General configuration (一般組態)** 下，執行下列動作：

   1. 在**儲存貯體類型**欄位中，選取**一般用途**。

   1. 在**儲存貯體名稱**欄位中，輸入符合 Amazon S3 [儲存貯體命名規則](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html)的全域唯一名稱。儲存貯體名稱只能包含小寫字母、數字、句點 (.) 和連字號 (-)。

1. 其他所有選項維持設為預設值，然後選擇**建立儲存貯體**。

## 將測試物件上傳至儲存貯體
<a name="with-s3-example-upload-test-object"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps2.png)


**上傳測試物件**

1. 開啟 Amazon S3 主控台的[儲存貯體](https://console.aws.amazon.com/s3/buckets)頁面，然後選擇您在上一個步驟中建立的儲存貯體。

1. 選擇**上傳**。

1. 選擇**新增檔案**，然後選取要上傳的物件。您可以選取任何檔案 (例如 `HappyFace.jpg`)。

1. 選擇**開啟**，然後選擇**上傳**。

在本教學課程的稍後部分，您將使用此物件測試 Lambda 函數。

## 建立許可政策
<a name="with-s3-example-create-policy"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps3.png)


建立許可政策，以允許 Lambda 從 Amazon S3 儲存貯體取得物件，以及寫入 Amazon CloudWatch Logs。

**建立政策**

1. 開啟 IAM 主控台中的[政策頁面](https://console.aws.amazon.com/iam/home#/policies)。

1. 選擇**建立政策**。

1. 選擇 **JSON** 索引標籤，然後將下列政策貼到 JSON 編輯器。

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "logs:PutLogEvents",
                   "logs:CreateLogGroup",
                   "logs:CreateLogStream"
               ],
               "Resource": "arn:aws:logs:*:*:*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "s3:GetObject"
               ],
               "Resource": "arn:aws:s3:::*/*"
           }
       ]
   }
   ```

------

1. 選擇下**一步：標籤**。

1. 選擇下**一步：檢閱**。

1. 在**檢閱政策下**，針對政策**名稱**，輸入 **s3-trigger-tutorial**。

1. 選擇**建立政策**。

## 建立執行角色
<a name="with-s3-example-create-role"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps4.png)


[執行角色](lambda-intro-execution-role.md)是授予 Lambda 函數存取 AWS 服務 和資源許可的 AWS Identity and Access Management (IAM) 角色。在此步驟中，使用您在上一個步驟中建立的許可政策來建立執行角色。

**建立執行角色並附加自訂許可政策**

1. 開啟 IAM 主控台中的[角色頁面](https://console.aws.amazon.com/iam/home#/roles)。

1. 選擇 **建立角色**。

1. 信任的實體類型請選擇 **AWS 服務**，使用案例則選擇 **Lambda**。

1. 選擇**下一步**。

1. 在政策搜尋方塊中，輸入 **s3-trigger-tutorial**。

1. 在搜尋結果中，選取您建立的政策 (`s3-trigger-tutorial`)，然後選擇**下一步**。

1. 在**角色詳細資料**底下，**角色名稱**請輸入 **lambda-s3-trigger-role**，然後選擇**建立角色**。

## 建立 Lambda 函式
<a name="with-s3-example-create-function"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps5.png)


使用 Python 3.14 執行時間在主控台中建立 Lambda 函數。

**建立 Lambda 函數**

1. 開啟 Lambda 主控台中的[函數頁面](https://console.aws.amazon.com/lambda/home#/functions)。

1. 請確定您使用 AWS 區域 與建立 Amazon S3 儲存貯體相同的 。您可使用螢幕頂端的下拉式清單來變更區域。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/console_region_select.png)

1. 選擇**建立函數**。

1. 選擇**從頭開始撰寫**

1. 在**基本資訊**下，請執行下列動作：

   1. 在**函數名稱**輸入 `s3-trigger-tutorial`

   1. 針對**執行期**，選擇 **Python 3.14。**

   1. 對於 **Architecture** (架構)，選擇 **x86\$164**。

1. 在**變更預設執行角色**索引標籤中，執行下列操作：

   1. 展開索引標籤，然後選擇**使用現有角色**。

   1. 選擇您之前建立的 `lambda-s3-trigger-role`。

1. 選擇**建立函數**。

## 部署函數程式碼
<a name="with-s3-example-deploy-code"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps6.png)


本教學課程使用 Python 3.14 執行時間，但我們也提供其他執行時間的範例程式碼檔案。您可以在下列方塊中選取索引標籤，查看您感興趣的執行期程式碼。

該 Lambda 函數收到 Amazon S3 傳來的 `event` 參數後，會從該參數擷取上傳物件的金鑰名稱以及儲存貯體的名稱。然後，函數會使用 中的 [get\$1object](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/get_object.html) 方法 適用於 Python (Boto3) 的 AWS SDK 擷取物件的中繼資料，包括上傳物件的內容類型 (MIME 類型）。

**部署函數程式碼**

1. 在以下方塊中選擇 **Python** 索引標籤，然後複製程式碼。

------
#### [ .NET ]

**適用於 .NET 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 .NET 搭配 Lambda 來使用 S3 事件。  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   ﻿using System.Threading.Tasks;
   using Amazon.Lambda.Core;
   using Amazon.S3;
   using System;
   using Amazon.Lambda.S3Events;
   using System.Web;
   
   // Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
   [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
   
   namespace S3Integration
   {
       public class Function
       {
           private static AmazonS3Client _s3Client;
           public Function() : this(null)
           {
           }
   
           internal Function(AmazonS3Client s3Client)
           {
               _s3Client = s3Client ?? new AmazonS3Client();
           }
   
           public async Task<string> Handler(S3Event evt, ILambdaContext context)
           {
               try
               {
                   if (evt.Records.Count <= 0)
                   {
                       context.Logger.LogLine("Empty S3 Event received");
                       return string.Empty;
                   }
   
                   var bucket = evt.Records[0].S3.Bucket.Name;
                   var key = HttpUtility.UrlDecode(evt.Records[0].S3.Object.Key);
   
                   context.Logger.LogLine($"Request is for {bucket} and {key}");
   
                   var objectResult = await _s3Client.GetObjectAsync(bucket, key);
   
                   context.Logger.LogLine($"Returning {objectResult.Key}");
   
                   return objectResult.Key;
               }
               catch (Exception e)
               {
                   context.Logger.LogLine($"Error processing request - {e.Message}");
   
                   return string.Empty;
               }
           }
       }
   }
   ```

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 Go 搭配 Lambda 來使用 S3 事件。  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   package main
   
   import (
   	"context"
   	"log"
   
   	"github.com/aws/aws-lambda-go/events"
   	"github.com/aws/aws-lambda-go/lambda"
   	"github.com/aws/aws-sdk-go-v2/config"
   	"github.com/aws/aws-sdk-go-v2/service/s3"
   )
   
   func handler(ctx context.Context, s3Event events.S3Event) error {
   	sdkConfig, err := config.LoadDefaultConfig(ctx)
   	if err != nil {
   		log.Printf("failed to load default config: %s", err)
   		return err
   	}
   	s3Client := s3.NewFromConfig(sdkConfig)
   
   	for _, record := range s3Event.Records {
   		bucket := record.S3.Bucket.Name
   		key := record.S3.Object.URLDecodedKey
   		headOutput, err := s3Client.HeadObject(ctx, &s3.HeadObjectInput{
   			Bucket: &bucket,
   			Key:    &key,
   		})
   		if err != nil {
   			log.Printf("error getting head of object %s/%s: %s", bucket, key, err)
   			return err
   		}
   		log.Printf("successfully retrieved %s/%s of type %s", bucket, key, *headOutput.ContentType)
   	}
   
   	return nil
   }
   
   func main() {
   	lambda.Start(handler)
   }
   ```

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 Java 搭配 Lambda 來使用 S3 事件。  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   package example;
   
   import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
   import software.amazon.awssdk.services.s3.model.HeadObjectResponse;
   import software.amazon.awssdk.services.s3.S3Client;
   
   import com.amazonaws.services.lambda.runtime.Context;
   import com.amazonaws.services.lambda.runtime.RequestHandler;
   import com.amazonaws.services.lambda.runtime.events.S3Event;
   import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord;
   
   import org.slf4j.Logger;
   import org.slf4j.LoggerFactory;
   
   public class Handler implements RequestHandler<S3Event, String> {
       private static final Logger logger = LoggerFactory.getLogger(Handler.class);
       @Override
       public String handleRequest(S3Event s3event, Context context) {
           try {
             S3EventNotificationRecord record = s3event.getRecords().get(0);
             String srcBucket = record.getS3().getBucket().getName();
             String srcKey = record.getS3().getObject().getUrlDecodedKey();
   
             S3Client s3Client = S3Client.builder().build();
             HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey);
   
             logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType());
   
             return "Ok";
           } catch (Exception e) {
             throw new RuntimeException(e);
           }
       }
   
       private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) {
           HeadObjectRequest headObjectRequest = HeadObjectRequest.builder()
                   .bucket(bucket)
                   .key(key)
                   .build();
           return s3Client.headObject(headObjectRequest);
       }
   }
   ```

------
#### [ JavaScript ]

**適用於 JavaScript (v3) 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 JavaScript 搭配 Lambda 來使用 S3 事件。  

   ```
   import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3";
   
   const client = new S3Client();
   
   export const handler = async (event, context) => {
   
       // Get the object from the event and show its content type
       const bucket = event.Records[0].s3.bucket.name;
       const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
   
       try {
           const { ContentType } = await client.send(new HeadObjectCommand({
               Bucket: bucket,
               Key: key,
           }));
   
           console.log('CONTENT TYPE:', ContentType);
           return ContentType;
   
       } catch (err) {
           console.log(err);
           const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
           console.log(message);
           throw new Error(message);
       }
   };
   ```
使用 TypeScript 搭配 Lambda 來使用 S3 事件。  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   import { S3Event } from 'aws-lambda';
   import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3';
   
   const s3 = new S3Client({ region: process.env.AWS_REGION });
   
   export const handler = async (event: S3Event): Promise<string | undefined> => {
     // Get the object from the event and show its content type
     const bucket = event.Records[0].s3.bucket.name;
     const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
     const params = {
       Bucket: bucket,
       Key: key,
     };
     try {
       const { ContentType } = await s3.send(new HeadObjectCommand(params));
       console.log('CONTENT TYPE:', ContentType);
       return ContentType;
     } catch (err) {
       console.log(err);
       const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`;
       console.log(message);
       throw new Error(message);
     }
   };
   ```

------
#### [ PHP ]

**適用於 PHP 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 PHP 搭配 Lambda 來使用 S3 事件。  

   ```
   <?php
   
   use Bref\Context\Context;
   use Bref\Event\S3\S3Event;
   use Bref\Event\S3\S3Handler;
   use Bref\Logger\StderrLogger;
   
   require __DIR__ . '/vendor/autoload.php';
   
   
   class Handler extends S3Handler 
   {
       private StderrLogger $logger;
       public function __construct(StderrLogger $logger)
       {
           $this->logger = $logger;
       }
       
       public function handleS3(S3Event $event, Context $context) : void
       {
           $this->logger->info("Processing S3 records");
   
           // Get the object from the event and show its content type
           $records = $event->getRecords();
           
           foreach ($records as $record) 
           {
               $bucket = $record->getBucket()->getName();
               $key = urldecode($record->getObject()->getKey());
   
               try {
                   $fileSize = urldecode($record->getObject()->getSize());
                   echo "File Size: " . $fileSize . "\n";
                   // TODO: Implement your custom processing logic here
               } catch (Exception $e) {
                   echo $e->getMessage() . "\n";
                   echo 'Error getting object ' . $key . ' from bucket ' . $bucket . '. Make sure they exist and your bucket is in the same region as this function.' . "\n";
                   throw $e;
               }
           }
       }
   }
   
   $logger = new StderrLogger();
   return new Handler($logger);
   ```

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 Python 搭配 Lambda 來使用 S3 事件。  

   ```
   # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   # SPDX-License-Identifier: Apache-2.0
   import json
   import urllib.parse
   import boto3
   
   print('Loading function')
   
   s3 = boto3.client('s3')
   
   
   def lambda_handler(event, context):
       #print("Received event: " + json.dumps(event, indent=2))
   
       # Get the object from the event and show its content type
       bucket = event['Records'][0]['s3']['bucket']['name']
       key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')
       try:
           response = s3.get_object(Bucket=bucket, Key=key)
           print("CONTENT TYPE: " + response['ContentType'])
           return response['ContentType']
       except Exception as e:
           print(e)
           print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
           raise e
   ```

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 Ruby 搭配 Lambda 來使用 S3 事件。  

   ```
   require 'json'
   require 'uri'
   require 'aws-sdk'
   
   puts 'Loading function'
   
   def lambda_handler(event:, context:)
     s3 = Aws::S3::Client.new(region: 'region') # Your AWS region
     # puts "Received event: #{JSON.dump(event)}"
   
     # Get the object from the event and show its content type
     bucket = event['Records'][0]['s3']['bucket']['name']
     key = URI.decode_www_form_component(event['Records'][0]['s3']['object']['key'], Encoding::UTF_8)
     begin
       response = s3.get_object(bucket: bucket, key: key)
       puts "CONTENT TYPE: #{response.content_type}"
       return response.content_type
     rescue StandardError => e
       puts e.message
       puts "Error getting object #{key} from bucket #{bucket}. Make sure they exist and your bucket is in the same region as this function."
       raise e
     end
   end
   ```

------
#### [ Rust ]

**適用於 Rust 的 SDK**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在[無伺服器範例](https://github.com/aws-samples/serverless-snippets/tree/main/integration-s3-to-lambda)儲存庫中設定和執行。
使用 Rust 搭配 Lambda 來使用 S3 事件。  

   ```
   // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
   // SPDX-License-Identifier: Apache-2.0
   use aws_lambda_events::event::s3::S3Event;
   use aws_sdk_s3::{Client};
   use lambda_runtime::{run, service_fn, Error, LambdaEvent};
   
   
   /// Main function
   #[tokio::main]
   async fn main() -> Result<(), Error> {
       tracing_subscriber::fmt()
           .with_max_level(tracing::Level::INFO)
           .with_target(false)
           .without_time()
           .init();
   
       // Initialize the AWS SDK for Rust
       let config = aws_config::load_from_env().await;
       let s3_client = Client::new(&config);
   
       let res = run(service_fn(|request: LambdaEvent<S3Event>| {
           function_handler(&s3_client, request)
       })).await;
   
       res
   }
   
   async fn function_handler(
       s3_client: &Client,
       evt: LambdaEvent<S3Event>
   ) -> Result<(), Error> {
       tracing::info!(records = ?evt.payload.records.len(), "Received request from SQS");
   
       if evt.payload.records.len() == 0 {
           tracing::info!("Empty S3 event received");
       }
   
       let bucket = evt.payload.records[0].s3.bucket.name.as_ref().expect("Bucket name to exist");
       let key = evt.payload.records[0].s3.object.key.as_ref().expect("Object key to exist");
   
       tracing::info!("Request is for {} and object {}", bucket, key);
   
       let s3_get_object_result = s3_client
           .get_object()
           .bucket(bucket)
           .key(key)
           .send()
           .await;
   
       match s3_get_object_result {
           Ok(_) => tracing::info!("S3 Get Object success, the s3GetObjectResult contains a 'body' property of type ByteStream"),
           Err(_) => tracing::info!("Failure with S3 Get Object request")
       }
   
       Ok(())
   }
   ```

------

1. 在 Lambda 主控台的**程式碼來源**窗格中，將程式碼貼到程式碼編輯器中，取代 Lambda 建立的程式碼。

1. 在 **DEPLOY** 區段中，選擇**部署**以更新函數的程式碼：  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/getting-started-tutorial/deploy-console.png)

## 建立 Amazon S3 觸發條件
<a name="with-s3-example-create-trigger"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps7.png)


**若要建立 Amazon S3 觸發條件**

1. 在**函數概觀**窗格中，選擇**新增觸發條件**。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/overview-trigger.png)

1. 選取 **S3**。

1. 在**儲存貯體**下，選取您在本教學課程中稍早建立的儲存貯體。

1. 在**事件類型**下，選取**所有物件建立事件**。

1. 在**遞迴調用**下，選取核取方塊，確認您了解不建議使用相同的 Amazon S3 儲存貯體進行輸入和輸出作業。

1. 選擇**新增**。

**注意**  
當您使用 Lambda 主控台為 Lambda 函數建立 Amazon S3 觸發條件時，Amazon S3 會在您指定的儲存貯體上設定[事件通知](https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html)。在設定此事件通知之前，Amazon S3 會執行一系列檢查，以確認該事件目的地存在，且具有所需的 IAM 政策。Amazon S3 也會對針對為該儲存貯體設定的任何其他事件通知執行這些測試。  
由於此檢查的存在，如果儲存貯體先前已為不再存在的資源設定事件目的地，或為沒有必要許可政策的資源設定事件目的地，則 Amazon S3 將無法建立新的事件通知。您將看到以下錯誤訊息，指出無法建立觸發條件：  

```
An error occurred when creating the trigger: Unable to validate the following destination configurations.
```
如果您先前已使用相同的儲存貯體為另一個 Lambda 函數設定觸發條件，且在之後刪除了相關函數或修改了其許可政策，則會顯示此錯誤。

## 使用虛擬事件來測試 Lambda 函數
<a name="with-s3-example-test-dummy-event"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps8.png)


**使用虛擬事件來測試 Lambda 函數**

1. 在函數的 Lambda 主控台頁面中，選擇**測試**索引標籤。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/test-tab.png)

1. **事件名稱**輸入 `MyTestEvent`。

1. 在**事件 JSON** 中，貼上以下測試事件。務必取代這些值：
   + 將 `us-east-1` 取代為您用來建立 Amazon S3 儲存貯體的區域。
   + 將 `amzn-s3-demo-bucket` 的兩個執行個體取代為您的 Amazon S3 儲存貯體名稱。
   + 將 `test%2FKey` 取代為您之前上傳到儲存貯體的測試物件名稱 (例如 `HappyFace.jpg`)。

   ```
   {
     "Records": [
       {
         "eventVersion": "2.0",
         "eventSource": "aws:s3",
         "awsRegion": "us-east-1",
         "eventTime": "1970-01-01T00:00:00.000Z",
         "eventName": "ObjectCreated:Put",
         "userIdentity": {
           "principalId": "EXAMPLE"
         },
         "requestParameters": {
           "sourceIPAddress": "127.0.0.1"
         },
         "responseElements": {
           "x-amz-request-id": "EXAMPLE123456789",
           "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH"
         },
         "s3": {
           "s3SchemaVersion": "1.0",
           "configurationId": "testConfigRule",
           "bucket": {
             "name": "amzn-s3-demo-bucket",
             "ownerIdentity": {
               "principalId": "EXAMPLE"
             },
             "arn": "arn:aws:s3:::amzn-s3-demo-bucket"
           },
           "object": {
             "key": "test%2Fkey",
             "size": 1024,
             "eTag": "0123456789abcdef0123456789abcdef",
             "sequencer": "0A1B2C3D4E5F678901"
           }
         }
       }
     ]
   }
   ```

1. 選擇**儲存**。

1. 選擇**測試**。

1. 如果函數成功運作，您會在**執行結果**索引標籤中看到類似以下內容的輸出。

   ```
   Response
   "image/jpeg"
   
   Function Logs
   START RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6 Version: $LATEST
   2021-02-18T21:40:59.280Z    12b3cae7-5f4e-415e-93e6-416b8f8b66e6    INFO    INPUT BUCKET AND KEY:  { Bucket: 'amzn-s3-demo-bucket', Key: 'HappyFace.jpg' }
   2021-02-18T21:41:00.215Z    12b3cae7-5f4e-415e-93e6-416b8f8b66e6    INFO    CONTENT TYPE: image/jpeg
   END RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6
   REPORT RequestId: 12b3cae7-5f4e-415e-93e6-416b8f8b66e6    Duration: 976.25 ms    Billed Duration: 977 ms    Memory Size: 128 MB    Max Memory Used: 90 MB    Init Duration: 430.47 ms        
   
   Request ID
   12b3cae7-5f4e-415e-93e6-416b8f8b66e6
   ```

### 使用 Amazon S3 觸發條件測試 Lambda 函數
<a name="with-s3-example-test-s3-trigger"></a>

![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps9.png)


若要使用已設定的觸發條件來測試函數，需使用主控台將物件上傳至 Amazon S3 儲存貯體。若要確認 Lambda 函數如預期執行，請使用 CloudWatch Logs 來檢視函數的輸出。

**將物件上傳至 Amazon S3 儲存貯體**

1. 開啟 Amazon S3 主控台的[儲存貯體](https://console.aws.amazon.com/s3/buckets)頁面，然後選擇您稍早建立的儲存貯體。

1. 選擇**上傳**。

1. 選擇**新增檔案**，然後使用檔案選擇器選擇您要上傳的物件。此物件可以是您自選的任何檔案。

1. 選擇**開啟**，然後選擇**上傳**。

**若要使用 CloudWatch Logs 驗證函數調用**

1. 開啟 [CloudWatch 主控台](https://console.aws.amazon.com/cloudwatch/home)。

1. 請確定您在 AWS 區域 建立 Lambda 函數的相同 中工作。您可使用螢幕頂端的下拉式清單來變更區域。  
![\[\]](http://docs.aws.amazon.com/zh_tw/lambda/latest/dg/images/console_region_select.png)

1. 選擇**日誌**，然後選擇**日誌群組**。

1. 為函數 (`/aws/lambda/s3-trigger-tutorial`) 選擇日誌群組名稱。

1. 在**日誌串流**下，選擇最新的日誌串流。

1. 如果系統已正確調用函數以回應 Amazon S3 觸發條件，您會看到類似以下內容的輸出。您看到的 `CONTENT TYPE` 取決於您上傳到儲存貯體的檔案類型。

   ```
   2022-05-09T23:17:28.702Z	0cae7f5a-b0af-4c73-8563-a3430333cc10	INFO	CONTENT TYPE: image/jpeg
   ```

## 清除您的資源
<a name="cleanup"></a>

除非您想要保留為此教學課程建立的資源，否則您現在便可刪除。透過刪除您不再使用 AWS 的資源，您可以避免不必要的 費用 AWS 帳戶。

**若要刪除 Lambda 函數**

1. 開啟 Lambda 主控台中的 [函數頁面](https://console.aws.amazon.com/lambda/home#/functions)。

1. 選擇您建立的函數。

1. 選擇 **Actions** (動作)、**Delete** (刪除)。

1. 在文字輸入欄位中輸入 **confirm**，然後選擇**刪除**。

**刪除執行角色**

1. 開啟 IAM 主控台中的 [角色頁面](https://console.aws.amazon.com/iam/home#/roles) 。

1. 選取您建立的執行角色。

1. 選擇**刪除**。

1. 在文字輸入欄位中輸入角色的名稱，然後選擇**刪除**。

**刪除 S3 儲存貯體**

1. 開啟 [Amazon S3 主控台](https://console.aws.amazon.com//s3/home#)。

1. 選擇您建立的儲存貯體。

1. 選擇 **刪除** 。

1. 在文字輸入欄位中輸入儲存貯體的名稱。

1. 選擇**刪除儲存貯體**。

## 後續步驟
<a name="next-steps"></a>

在 [教學課程：使用 Amazon S3 觸發條件建立縮圖影像](with-s3-tutorial.md) 中，Amazon S3 觸發條件會調用函數，為上傳至 S3 儲存貯體的每個影像檔建立縮圖影像。本教學課程需要中等程度的 AWS 和 Lambda 網域知識。它示範如何使用 AWS Command Line Interface (AWS CLI) 建立資源，以及如何為函數及其相依性建立 .zip 檔案封存部署套件。