
저장된 원본 이미지를 썸네일용 이미지로 변환하여 새로운 버킷에 저장하기
총 두개의 버킷을 생성한다.하나의 버킷은 원본 이미지를 저장할 버킷이고 다른 하나는 원본 이미지가 썸네일 이미지로 변경되어 넣어질 버킷이다.
필자는 버킷명을 원본이미지용:
bk-picture, 썸네일용:bk-thumbnail으로 지었다.


{
 "Version": "2012-10-17",
 "Statement": [
     {
         "Sid": "PublicReadGetObject",
         "Effect": "Allow",
         "Principal": "*",
         "Action": "s3:GetObject",
         "Resource": "arn:aws:s3:::bk-pictrue/*"
     }
 ]
}두개의 S3 모두 위와 같이 설정하여 만들어준다.
람다함수 역할 : 원본 이미지 버킷에 이미지가 추가되었을 때 이미지 사이즈를 변경하고 썸네일용 버킷에 넣음
선수조건:
1. AWS CLI 자격 증명 이 완료되어야 함.
2. SAM 이 설치되어야 한다.
sam init 을 통해 초기 세팅을 해준다.$ sam init
...
  - Which template source would you like to use?
  	=> `1` - AWS Quick Start Templates
  - Choose an AWS Quick Start application template
  	=> `1` - Hello World Example
  - Which runtime would you like to use?
  	=> `15` - nodejs14.x
  - What package type would you like to use?
  	=> `1` - Zip
  - Select your starter template
  	=> `1` - Hello World Example
  - Would you like to enable X-Ray tracing on the function(s) in your application?
  	=> `N` (추적 관련된 내용이나 현재 필요치 않음)
	- Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html
		=> `N`
  - Project name [sam-app]:
  	=> `thumbnail-app-test`
결과:
sam init                   
	You can preselect a particular runtime or package type when using the `sam init` experience.
Call `sam init --help` to learn more.
	Which template source would you like to use?
     1 - AWS Quick Start Templates
     2 - Custom Template Location
Choice: 1
	Choose an AWS Quick Start application template
     1 - Hello World Example
     2 - Multi-step workflow
     3 - Serverless API
     4 - Scheduled task
     5 - Standalone function
     6 - Data processing
     7 - Hello World Example With Powertools
     8 - Infrastructure event management
     9 - Serverless Connector Hello World Example
     10 - Multi-step workflow with Connectors
     11 - Lambda Response Streaming
     12 - Lambda EFS example
     13 - DynamoDB Example
     14 - Machine Learning
Template: 1
	Use the most popular runtime and package type? (Python and zip) [y/N]: N
	Which runtime would you like to use?
     1 - aot.dotnet7 (provided.al2)
     2 - dotnet6
     3 - dotnet5.0
     4 - dotnetcore3.1
     5 - go1.x
     6 - go (provided.al2)
     7 - graalvm.java11 (provided.al2)
     8 - graalvm.java17 (provided.al2)
     9 - java17
     10 - java11
     11 - java8.al2
     12 - java8
     13 - nodejs18.x
     14 - nodejs16.x
     15 - nodejs14.x
     16 - nodejs12.x
     17 - python3.9
     18 - python3.8
     19 - python3.7
     20 - python3.10
     21 - ruby2.7
     22 - rust (provided.al2)
	Runtime: 15
	What package type would you like to use?
     1 - Zip
     2 - Image
	Package type: 1
	Based on your selections, the only dependency manager available is npm.
	We will proceed copying the template using npm.
	Select your starter template
     1 - Hello World Example
     2 - Hello World Example TypeScript
	Template: 1
	Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: N
	Would you like to enable monitoring using CloudWatch Application Insights?
	For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: N
	Project name [sam-app]: thumbnail-app-test
 -----------------------
 Generating application:
 -----------------------
 Name: thumbnail-app-test
 Runtime: nodejs14.x
 Architectures: x86_64
 Dependency Manager: npm
 Application Template: hello-world
 Output Directory: .
 Configuration file: thumbnail-app-test/samconfig.toml
 
 Next steps can be found in the README file at thumbnail-app-test/README.md
     
	Commands you can use next
	=========================
	[*] Create pipeline: cd thumbnail-app-test && sam pipeline init --bootstrap
	[*] Validate SAM template: cd thumbnail-app-test && sam validate
	[*] Test Function in the Cloud: cd thumbnail-app-test && sam sync --stack-name {stack-name} --watch
 ```
sam init 으로 만들어진 폴더thumbnail-app-test 내에서 hellow-world 내 app.js 에 아래의 소스를 붙여넣는다.
const aws = require('aws-sdk');
const s3 = new aws.S3({ apiVersion: '2006-03-01' });
const sharp = require('sharp');
exports.lambdaHandler = async (event, context) => {
console.log(event);
console.log(context);
const bucket = event.Records[0].s3.bucket.name;      // 원본 버킷 이름
const key = event.Records[0].s3.object.key;          // 원본 버킷 키
console.log("bucket: ", bucket);
console.log("key: ", key);
const dstBucket = process.env.s3resized     // 썸네일 버킷 이름
console.log(`test  111`);
// 원본 버킷으로부터 파일 읽기
const s3Object = await s3.getObject({
       Bucket: bucket,
       Key: key
}).promise()
console.log(`test  222`);
// 이미지 리사이즈, sharp 라이브러리가 필요합니다.
const data = await sharp(s3Object.Body)
       .resize(200)
       .jpeg({ mozjpeg: true })
       .toBuffer()
console.log(`test  333`);
// 대상 버킷으로 파일 쓰기
const result = await s3.putObject({
       Bucket: dstBucket,
       Key: key,                                       // 원본 버킷 키와 동일
       ContentType: 'image/jpeg',                      // 컨텐츠 타입
       Body: data,
       ACL: 'public-read'
}).promise()
console.log(`test  444`);
return result;
}
위의 소스 역할: 원본 이미지 버킷에 추가된 이미지를 가져와 이미지 사이즈를 변경하고 썸네일용 버킷에 넣음
sharp 라이브러리 설치
hellow-world 폴더 내에서 npm install sharp 실행
빌드 및 배포
cd ..sam buildsam deploy --guided
$ sam deploy --guided
   Stack Name [thumbnail-app-test]: 
   AWS Region [ap-northeast-2]: 
   #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
   Confirm changes before deploy [Y/n]: 
   #SAM needs permission to be able to create roles to connect to the resources in your template
   Allow SAM CLI IAM role creation [Y/n]: 
   #Preserves the state of previously provisioned resources when an operation fails
   Disable rollback [y/N]: 
   HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
   Save arguments to configuration file [Y/n]: 
   SAM configuration file [samconfig.toml]: 
   SAM configuration environment [default]: 
   Deploy this changeset? [y/N]: y결과:




bk-thumbnail 란에 썸네일용 버킷명을 적는다. 
정책 생성 버튼 클릭JSON 탭을 선택한 후 다음 정책을 붙여 넣음.{
  "Version": "2012-10-17",
  "Statement": [
      {
          "Effect": "Allow",
          "Action": [
              "logs:PutLogEvents",
              "logs:CreateLogGroup",
              "logs:CreateLogStream"
          ],
          "Resource": "arn:aws:logs:*:*:*"
      },
      {
          "Sid": "AllAccess",
          "Action": "s3:*",
          "Effect": "Allow",
          "Resource": [
              "*"
          ]
      }
  ]
}LambdaS3Policy 로 하고 정책 생성접근 및 저장 에 대한 권한을 갖고 있음.역할 만들기 버튼 클릭
LambdaS3Policy 정책을 추가lambda-s3-role 로 하여 역할 생성lambda-s3-role 로 변경 
jpeg 파일을 업로드 한다.

Cloud Watch 로그 확인
타임아웃으로 인해 실패된 것을 확인 
타임아웃을 기존 3초에서 10초로 변경 


Runtime exited with error: signal: killed Runtime.ExitErrorMemory 가 부족할 때 죽는다고 함 (스택오버플로우)Memory 변경128MB -> 500MB로 넉넉히 변경함 

추후 필자가 알아둬아야할 정보: ACL 이 뭔지 추후 확인이 필요함
참고자료:
1. cks8483님 블로그
2. AWS 자습서: Amazon S3 트리거를 사용하여 썸네일 이미지 생성
3. AWS 자습서: Hello World 애플리케이션 배포
4. AWS: Lambda 실행 역할
5. 자습서: Amazon S3 트리거를 사용하여 Lambda 함수 호출
6. 상협님 블로그