원본 저장 -> 저장 이벤트 발생 -> 리사이즈 된 이미지 저장 -> 저장 이벤트 발생 -> ...
테스트용 이미지업로드
테스트를 위해 원본 버킷에 이미지를 1개 미리 업로드 해둔다.
권한 정책 생성
s3와 cloudwatch에 접근하기 위한 권한 정책을 생성한다
s3 읽기: 저장 이벤트 발생 시 불러오기
s3 쓰기: 리사이즈된 이미지 저장
cloudWatch 쓰기: 함수 실행 후 로그 저장
실행 역할 생성
위에서 만든 권한 정책을 사용하는 역할을 생성
Lambda 함수 생성
// dependenciesimport { S3Client, GetObjectCommand, PutObjectCommand,} from'@aws-sdk/client-s3'import { Readable } from'stream'import sharp from'sharp'import util from'util'// create S3 clientconsts3=newS3Client({ region:'ap-northeast-2' })// define the handler functionexportconsthandler=async (event, context) => {// Read options from the event parameter and get the source bucketconsole.log('Reading options from event:\n',util.inspect(event, { depth:5 }) )constsrcBucket=event.Records[0].s3.bucket.name// Object key may have spaces or unicode non-ASCII charactersconstsrcKey=decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g,' ') )constdstBucket= srcBucket +'-resized'constdstKey='resized-'+ srcKey// Infer the image type from the file suffixconsttypeMatch=srcKey.match(/\.([^.]*)$/)if (!typeMatch) {console.log('Could not determine the image type.')return }// Check that the image type is supportedconstimageType= typeMatch[1].toLowerCase()if (imageType !='jpg'&& imageType !='png') {console.log(`Unsupported image type: ${imageType}`)return }// Get the image from the source bucket. GetObjectCommand returns a stream.try {constparams= { Bucket: srcBucket, Key: srcKey, }var response =awaits3.send(newGetObjectCommand(params))var stream =response.Body// Convert stream to buffer to pass to sharp resize function.if (stream instanceofReadable) {var content_buffer =Buffer.concat(awaitstream.toArray()) } else {thrownewError('Unknown object stream type') } } catch (error) {console.log(error)return }// set thumbnail width. Resize will set the height automatically to maintain aspect ratio.constwidth=200// Use the sharp module to resize the image and save in a buffer.try {var output_buffer =awaitsharp(content_buffer).resize(width).toBuffer() } catch (error) {console.log(error)return }// Upload the thumbnail image to the destination buckettry {constdestparams= { Bucket: dstBucket, Key: dstKey, Body: output_buffer, ContentType:'image', }constputResult=awaits3.send(newPutObjectCommand(destparams)) } catch (error) {console.log(error)return }console.log('Successfully resized '+ srcBucket +'/'+ srcKey +' and uploaded to '+ dstBucket +'/'+ dstKey )}
npminstall--arch=x64--platform=linuxsharp@0.32.6
루트 폴더를 .zip로 압축 -> 함수로 업로드
위에서 만든 역할을 가지는 lambda 함수 생성
zip 파일을 업로드
S3 트리거 추가
s3에서 생성 이벤트가 발생하면 lambda 함수가 실행되도록 s3의 All object create events 트리거를 추가
테스트 이벤트 생성 및 테스트
테스트 이벤트를 생성하여 처음에 업로드한 테스트용 이미지에 대해서 리사이즈된 이미지를 생성하는지 테스트