Amazon S3 트리거에서 Lambda 함수 호출하기

Amazon S3 트리거에서 Lambda 함수 호출하기 (Invoke a Lambda function from an Amazon S3 trigger)

S3 버킷에 객체를 업로드하면 이벤트가 발생하고, Lambda 함수가 그 이벤트를 받아 처리할 수 있어요. 이 예제는 이벤트 파라미터에서 S3 버킷 이름과 객체 키(key)를 꺼내 Amazon S3 API로 객체의 콘텐츠 타입(content type)을 조회·로그로 남기는 Lambda 함수를 구현하는 방법을 보여줘요.

출처: AWS Lambda 개발자 안내서

본문

다음 코드 예제는 S3 버킷에 객체를 업로드하면 트리거되는 이벤트를 받는 Lambda 함수를 구현하는 방법을 보여줘요. 이 함수는 이벤트 파라미터에서 S3 버킷 이름과 객체 키를 가져와 Amazon S3 API를 호출하고 객체의 콘텐츠 타입을 조회해 로그로 남겨요.

.NET (SDK for .NET)

S3 이벤트를 .NET에서 Lambda로 소비하는 예제예요.

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)

S3 이벤트를 Go에서 Lambda로 소비하는 예제예요.

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 object: %s", err)
			continue
		}
		log.Printf("Content type of %s/%s is %s", bucket, key, *headOutput.ContentType)
	}
	return nil
}

func main() {
	lambda.Start(handler)
}

다른 언어(Java, JavaScript, Python 등)의 예제와 전체 코드·실행 방법은 serverless-snippets 에서 확인할 수 있어요.

참고
S3 버킷에서 Lambda 함수를 트리거하려면 함수에 S3 이벤트를 보내도록 버킷 알림(bucket notification)을 구성해야 해요. 자세한 내용은 S3 트리거 구성 을 참고하세요.

더 알아보기 (Learn more)