

# 자습서: 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/ko_kr/lambda/latest/dg/images/services-s3-example/s3_tut_config.png)


이 자습서에서는 다음을 수행하는 방법을 설명합니다.

1. Amazon S3 버킷을 생성합니다.

1. Amazon S3 버킷에 있는 객체의 유형을 반환하는 Lambda 함수를 생성합니다.

1. 객체가 버킷에 업로드될 때 함수를 간접 호출하는 Lambda 트리거를 구성합니다.

1. 먼저 더미 이벤트로 함수를 테스트한 다음 트리거를 사용하여 함수를 테스트합니다.

이 단계를 완료하면 Amazon S3 버킷에서 객체가 추가되거나 삭제될 때마다 실행되도록 Lambda 함수를 구성하는 방법을 알게 됩니다. AWS Management Console만 사용하여 이 자습서를 완료할 수 있습니다.

## Amazon S3 버킷 생성
<a name="with-s3-example-create-bucket"></a>

![\[\]](http://docs.aws.amazon.com/ko_kr/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/ko_kr/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/ko_kr/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/ko_kr/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. **다음: 검토(Next: Review)**를 선택합니다.

1. **정책 검토**의 **이름**에 **s3-trigger-tutorial**를 입력합니다.

1. **정책 생성**을 선택합니다.

## 실행 역할 만들기
<a name="with-s3-example-create-role"></a>

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


[실행 역할](lambda-intro-execution-role.md)은 AWS 서비스 및 리소스에 액세스할 수 있는 권한을 Lambda 함수에 부여하는 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`)을 선택한 후, **다음(Next)**을 선택합니다.

1. **Role details**(역할 세부 정보)에서 **Role name**(역할 이름)에 **lambda-s3-trigger-role**을 입력한 다음 **Create role**(역할 생성)을 선택합니다.

## Lambda 함수 생성
<a name="with-s3-example-create-function"></a>

![\[\]](http://docs.aws.amazon.com/ko_kr/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. Amazon S3 버킷을 생성한 동일한 AWS 리전에서 작업 중인지 확인합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다.  
![\[\]](http://docs.aws.amazon.com/ko_kr/lambda/latest/dg/images/console_region_select.png)

1. **함수 생성**을 선택합니다.

1. **새로 작성**을 선택합니다.

1. **기본 정보**에서 다음과 같이 합니다.

   1. **함수 이름**에 `s3-trigger-tutorial`을 입력합니다.

   1. **런타임**에서 **Python 3.14**를 선택합니다.

   1. **아키텍처**에서는 **x86\$164**를 선택합니다.

1. **기본 실행 역할 변경** 탭에서 다음을 수행합니다.

   1. 탭을 확장한 다음 **기존 역할 사용**을 선택합니다.

   1. 이전에 생성한 `lambda-s3-trigger-role`을 선택합니다.

1. **함수 생성**을 선택합니다.

## 함수 코드 배포
<a name="with-s3-example-deploy-code"></a>

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


이 자습서에서는 Python 3.14 런타임을 사용하지만 다른 런타임의 예제 코드 파일도 제공했습니다. 다음 상자에서 탭을 선택하여 관심 있는 런타임에 대한 코드를 볼 수 있습니다.

Lambda 함수는 Amazon S3에서 수신한 `event` 파라미터에서 업로드된 객체의 키 이름과 버킷 이름을 검색합니다. 그런 다음 함수는 AWS SDK for Python (Boto3)의 [get\$1object](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/get_object.html) 메서드를 사용하여 업로드된 객체의 콘텐츠 유형(MIME 유형)을 비롯한 객체의 메타데이터를 검색합니다.

**함수 코드 배포**

1. 다음 상자에서 **Python** 탭을 선택하고 코드를 복사합니다.

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

**SDK for .NET**  
 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 ]

**SDK for JavaScript (v3)**  
 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 ]

**SDK for PHP**  
 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 ]

**SDK for Python(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 ]

**SDK for Rust**  
 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 콘솔의 **코드 소스** 창에서 Code Editor에 코드를 붙여넣고 Lambda가 생성한 코드를 바꿉니다.

1. **배포** 섹션에서 **배포**를 선택하여 함수의 코드를 업데이트하세요.  
![\[\]](http://docs.aws.amazon.com/ko_kr/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/ko_kr/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps7.png)


**Amazon S3 트리거 생성 방법**

1. **함수 개요** 창에서 **트리거 추가**를 선택합니다.  
![\[\]](http://docs.aws.amazon.com/ko_kr/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/ko_kr/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps8.png)


**더미 이벤트로 Lambda 함수 테스트**

1. 함수의 Lambda 콘솔 페이지에서 **테스트** 탭을 선택합니다.  
![\[\]](http://docs.aws.amazon.com/ko_kr/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/ko_kr/lambda/latest/dg/images/services-s3-example/s3trigger_tut_steps9.png)


구성된 트리거로 함수를 테스트하려면 콘솔을 사용하여 Amazon S3 버킷에 객체를 업로드합니다. Lambda 함수가 예상대로 실행되었는지 확인하려면 CloudWatch 로그를 사용하여 함수의 출력을 확인합니다.

**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. Lambda 함수를 생성한 동일한 AWS 리전에서 작업 중인지 확인합니다. 화면 상단의 드롭다운 목록을 사용하여 리전을 변경할 수 있습니다.  
![\[\]](http://docs.aws.amazon.com/ko_kr/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. **작업**, **삭제**를 선택합니다.

1. 텍스트 입력 필드에 **confirm**를 입력하고 **Delete**(삭제)를 선택합니다.

**집행 역할 삭제**

1. IAM 콘솔에서 [역할 페이지](https://console.aws.amazon.com/iam/home#/roles)를 엽니다.

1. 생성한 실행 역할을 선택합니다.

1. **삭제**를 선택합니다.

1. 텍스트 입력 필드에 역할의 이름을 입력하고 **Delete**(삭제)를 선택합니다.

**S3 버킷을 삭제하려면**

1. [Amazon S3 콘솔](https://console.aws.amazon.com//s3/home#)을 엽니다.

1. 생성한 버킷을 선택합니다.

1. **삭제**를 선택합니다.

1. 텍스트 입력 필드에 버킷 이름을 입력합니다.

1. **버킷 삭제(Delete bucket)**를 선택합니다.

## 다음 단계
<a name="next-steps"></a>

[자습서: Amazon S3 트리거를 사용하여 썸네일 이미지 생성](with-s3-tutorial.md)에서는 Amazon S3 트리거가 함수를 간접적으로 간접 호출하여 버킷에 업로드된 각 이미지 파일에 대해 썸네일 이미지를 생성합니다. 이 자습서를 진행하려면 중급 수준의 AWS 및 Lambda 분야 지식이 필요합니다. AWS Command Line Interface(AWS CLI)를 사용하여 리소스를 생성하는 방법과 함수 및 해당 종속성에 대한 .zip 파일 아카이브 배포 패키지를 생성하는 방법을 설명합니다.