[AWS] SAM 간단한 예제(RESTful API endpoint using Amazon API Gateway)

SAM으로 간단한 예제

1. template.yaml 설정

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
AWSTemplateFormatVersion: '2010-09-09'   #SAM 템플릿
Transform: 'AWS::Serverless-2016-10-31'
Description: A simple backend with a RESTful API endpoint using Amazon API Gateway.
Resources:
hello:
Type: 'AWS::Serverless::Function'
Properties:
Handler: handler.hello #실행 함수
Runtime: nodejs8.10 #node.js 로 실행
CodeUri: . #파일 path
Description: A simple backend with a RESTful API endpoint using Amazon API Gateway.
MemorySize: 512 #function 할당 메모리
Timeout: 10 #호출 타임아웃
Events:
Api1:
Type: Api #api gateway
Properties:
Path: /hello #API호출경로
Method: ANY #모든메소드


2. handler.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
'use strict';

// apigateway 에서 호출시 진입점(hello)
exports.hello = (event, context, callback) => {
//console.log('Received event:', JSON.stringify(event, null, 2));

switch (event.httpMethod) {
case 'DELETE':
sendResponse(200, 'DELETE happened', callback);
break;
case 'GET':
sendResponse(200, 'GET happened', callback);
break;
case 'POST':
sendResponse(200, 'POST happened', callback);
break;
case 'PUT':
sendResponse(200, 'PUT happened', callback);
break;
default:
sendResponse(200, `Unsupported method "${event.httpMethod}"`, callback);
}
};

function sendResponse(statusCode, message, callback){
const response = {
statusCode: statusCode,
body: JSON.stringify(message)
};
callback(null,response);
}


3. S3 bucket 생성
aws 설치 및 config 설정 생략…

1
2
aws s3 mb s3://sam-test-bucket3
make_bucket: sam-test-bucket3


4. Packing Artifacts

1
2
3
4
aws cloudformation package --template-file .\template.yml --s3-bucket sam-test-bucket3 --output-template.yaml
Uploading to 7e7043603cb391e49a966292b19ddcf0 42386 / 42386.0 (100.00%)
Successfully packaged artifacts and wrote output template to file packaged-template.yaml.
Execute the following command to deploy the packaged template

output-template.yaml 에 codeUri가 변경됨 S3의 위치로


5. 배포(Deploy)

1
2
3
4
5
aws cloudformation deploy --template-file .\packaged-template.yaml --stack-name sam-test-basic3 --capabilities CAPABILITY_IAM

Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - sam-test-basic3


6. 생성된 cloudFormation STACK
-


7. 생성된 STACK RESOURCE
-


8. 생성된 Template
-


9. 생성된 API GATEWAY
-


10. API 호출정보 및 호출
-

호출


11. 삭제

1
aws --region us-east-2 cloudformation delete-stack --stack-name sam-test-basic3