aws sam, lambda 정리

  • nodejs 람다 기준

sam

  • sam cli로 로컬에서 람다를 작성하고 배포할 수 있다

실행환경

  • /var/task 에서 람다 함수가 실행된다
  • /opt/nodejs 에 레이어가 적재된다
  • /tmp 디렉터리는 유일한 쓰기 디렉터리이다
  • /tmp 디렉터리의 용량은 512MB이다
  • /tmp 디렉터리는 일회성이다

로컬에서 테스트

  • sam local start-api로 로컬에서 람다를 테스트해볼 수 있다
  • --skip-pull-image 옵션을 주어 실행 시간을 단축시킬 수 있다
  • 로컬에서 실행할 때 도커가 필요하다
  • 참고로 람다는 아마존 리눅스 2 환경에서 돌아간다

빌드

  • sam build 명령으로 설치되는 패키지에는 devDependencies가 포함되지 않는다

레이어

  • 레이어는 종속성을 따로 관리할 수 있게 해 준다
  • 노드 모듈은 웬만하면 레이어로 빼는 게 맞는 것 같다
  • 람다 노드 모듈 폴더를 포함하여 배포되면 용량이 커져서 브라우저에서 코드 조회를 할 수 없다
  • 공통적으로 자주 사용되는 패키지들을 묶어서 재사용할 수 있다
  • 레이어로 사용할
  • devDependencies가 포함되건 말건 상관없다면 심볼릭 링크를 사용하는 것도 나쁘지 않은 것 같다 참고

레이어 (내가 만든 모듈)

  • 내가 제작한 모듈도 레이어로 뺄 수 있다
  • sam project 루트 디렉터리를 기준으로 /opt/nodejs 에 내 모듈을 작성한다 (ex. /opt/nodejs/myModule.js)
  • sam project 루트 디렉터리에서 jsconfig.json를 다음과 같이 한다 (없으면 생성)
jsconfig.json
1
2
3
4
5
6
7
8
9
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"*": ["./opt/nodejs/*"]
}
},
"exclude": ["node_modules", "build"]
}
  • 이를 임포트 해서 사용하는 파일에서는
app.js
1
const myModule = require('myModule');
  • 이런 식으로 불러와 사용할 수 있다
  • 자동 완성도 잘 작동한다

레이어 yaml 설정

tmplate.yaml
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
32
33
34
35
36
37
38
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: functions/hello-world/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Layers:
- !Ref MyModuleLayer
- !Ref HelloWorldFunctionLayer
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
# ...
HelloWorldFunctionLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: HelloWorldFunctionLayer
Description: Dependencies for SAM
ContentUri: layer/HelloWorldFunction
CompatibleRuntimes:
- nodejs12.x
LicenseInfo: 'MIT'
RetentionPolicy: Retain

MyModuleLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: my-layer
Description: Dependencies for SAM
ContentUri: opt
CompatibleRuntimes:
- nodejs12.x
LicenseInfo: 'MIT'
RetentionPolicy: Retain
  • 이런 식으로 리소스에 레이어를 작성한다

참고

sam template.yaml 익히는 빠른 방법

  • 브라우저에서 aws console 통해 람다 수정해보고
  • 작업 > 내보내기 > aws sam 파일 다운로드 하기
  • 여기서 aws sam 파일template.yaml이다

익히는 법

  • 처음에 할때는 gui만큼 쉬운게 없다
  • sam을 시작하면 yaml을 어떻게 건드려야할지 감이 안올 것이다
  • 그럴때는 역으로 브라우저에서 내가 설정할 권한들을 설정하고 저장한다
  • 그리고 작업 > 내보내기 > aws sam 파일 다운로드를 통해 어떻게 yaml이 수정되었는지 확인해보면 된다

sam에서 노드 모듈을 레이어로 빼기

  • 람다는 가벼운게 최고다
  • 노드 모듈은 따로 빼버리기!

Lambda Layer

  • nodejs로 치면 node_modules이다
  • 람다 함수에서 노드 모듈같은 종속성을 람다 함수 밖에으로 뺄 수 있음
  • 왜 쓰냐?
      1. 공통적으로 쓰이는 패키지들을 묶어서 관리할 수 있음
      1. 람다함수가 커지면 브라우저로 aws console에서 코드 조회를 못함

따라하기

외부 모듈을 사용해보기

  • sam template.yaml에서 layer설정할 수 있다
  • 지난번에 만든 hello world에서 이어서 진행해 보겠다
hello-world/app.js
1
2
3
// const axios = require('axios')
// const url = 'http://checkip.amazonaws.com/';
let response;
hello-world/app.js
1
2
3
const axios = require('axios');
const url = 'http://checkip.amazonaws.com/';
let response;
  • 맨 윗 2줄 주석 해제한다
hello-world/app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
exports.lambdaHandler = async (event, context) => {
try {
// const ret = await axios(url);
response = {
statusCode: 200,
body: JSON.stringify({
message: 'hello world',
// location: ret.data.trim(),
}),
};
} catch (err) {
console.log(err);
return err;
}

return response;
};
hello-world/app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
exports.lambdaHandler = async (event, context) => {
try {
const ret = await axios(url);
response = {
statusCode: 200,
body: JSON.stringify({
message: 'hello world',
location: ret.data.trim(),
}),
};
} catch (err) {
console.log(err);
return err;
}

return response;
};
  • 여기도 2곳 주석을 해제한다

package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
"name": "hello_world",
"version": "1.0.0",
"description": "hello world sample for NodeJS",
"main": "app.js",
"repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs",
"author": "SAM CLI",
"license": "MIT",
"dependencies": {
"axios": "^0.18.0"
},
"scripts": {
"test": "mocha tests/unit/"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^6.1.4"
}
}
  • 필요없는 devDependencies 를 없앤다
  • test 할때 필요한 패키지인데, 우리는 안쓸거다
package.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "hello_world",
"version": "1.0.0",
"description": "hello world sample for NodeJS",
"main": "app.js",
"repository": "https://github.com/awslabs/aws-sam-cli/tree/develop/samcli/local/init/templates/cookiecutter-aws-sam-hello-nodejs",
"author": "SAM CLI",
"license": "MIT",
"dependencies": {
"axios": "^0.18.0"
},
"scripts": {
"test": "mocha tests/unit/"
}
}
  • 없애면 이런 모양이 된다

cmd
1
2
cd hello-world
npm i
  • app.js가 있는 hello-world 디렉터리로 와서 종속성을 설치한다
1
2
3
4
5
6
7
8
9
10
11
12
13
.
├── .aws-sam/
├── events
│ └── event.json
├── hello-world
│ ├── node_modules/
│ ├── tests/
│ ├── .npmignore
│ ├── app.js
│ └── package.json
├── .gitignore
├── README.md
└── template.yaml
  • node_modules 폴더가 생기면서 현재 디렉터리 구조는 이렇게 된다
  • hello-world/tests 폴더를 삭제한다. 우리는 안쓴다
  • events 폴더를 삭제한다. 우리는 안쓴다
  • .aws-sam 폴더를 삭제한다. 이 폴더가 있으면 local start-api 했을때 .aws-sam를 우선 참조하기때문에 소스 코드에 변경사항이 발생해도 반영되지 않는다
1
2
3
4
5
6
7
8
9
.
├── hello-world
│ ├── node_modules/
│ ├── .npmignore
│ ├── app.js
│ └── package.json
├── .gitignore
├── README.md
└── template.yaml
  • 현재까지 디렉터리 구조는 이렇게 된다

cmd
1
2
cd ..
sam local start-api --skip-pull-image
cmd log
1
2
3
4
5
6
7
C:\tmp\hello-world\hello-world>cd ..

C:\tmp\hello-world>sam local start-api --skip-pull-image
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM
CLI if you update your AWS SAM template
2020-09-21 14:49:47 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
  • 이렇게 location에 자신의 공인 IP가 뜨면 성공이다

  • 주석 해제한 소스 코드는

  • axios라는 모듈로 http://checkip.amazonaws.com/ 에서 공인 ip를 얻어와 response 객체에 location이라는 이름으로 담아서 반환한 것이다

  • http://checkip.amazonaws.com/ 에 접속해 보면 알 수 있듯이 자신의 공인 ip를 알려주는 api다

  • 여기까지 axios라는 모듈을 이용해봤다

  • 이제 sam build & sam deploy 를 통해 aws에 올려보자

cmd
1
sam build & sam deploy
  • 배포가 완료되면 엔드 포인트를 통해서 aws에 올린 람다를 실행해보자
  • 그러면 이상한 아이피가 나온다
  • 이게 aws 컴퓨터중에서 현재 람다가 실행된 컴퓨터의 공인 ip 주소이다
  • 여기까지 잘 작동되는 것이 확인 되었다

외부 모듈을 layer로 빼기

  • 이제 브라우저를 열고 aws console > lambda > HelloWorldFunction 으로 가서 함수가 어떻게 생겻는지 확인한다
  • 함수 안에 노드 모듈이 포함되어 있는 것을 확인할 수 있다
  • 이제 이 글의 핵심인 node_modules 폴더를 layer로 빼볼것이다
  • 레이어를 만드는 방법이 여러가지가 있지만 나는 내 방식을 설명해 보겠다
  • 나는 cmd명령을 사용할 것이다

  • template.yaml에서 빨간 네모 부분을 추가한다
template.yaml
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
hello-world

Sample SAM Template for hello-world

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
Function:
Timeout: 3

Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
Layers:
- !Ref DependencyLayer
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
DependencyLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: HelloWorldFunction-layer
Description: Dependencies for HelloWorldFunction
ContentUri: opt/
CompatibleRuntimes:
- nodejs12.x
RetentionPolicy: Retain

Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: 'API Gateway endpoint URL for Prod stage for Hello World function'
Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/'
HelloWorldFunction:
Description: 'Hello World Lambda Function ARN'
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: 'Implicit IAM Role created for Hello World function'
Value: !GetAtt HelloWorldFunctionRole.Arn
  • 최종코드는 이러하다
  • 눈여겨 봐야할 것은
  • Resources아래에 DependencyLayer라는 이름으로 layer정의하고
  • ContentUri: opt/ 를 지정한다. 이 opt 디렉터리에 우리가 layer로 따로뺄 패키지가 들어가게 될것이다
  • 이제 배치파일을 2개 만들거다
layer.bat
1
2
3
4
5
6
7
echo layer process

set functionDir=HelloWorldFunction

echo y|rmdir /s opt\nodejs
mkdir opt\nodejs
move .aws-sam\build\%functionDir%\node_modules opt\nodejs
  • layer.bat을 sam project 최상위에 만들고 내용은 위와같이 한다
  • set functionDir=HelloWorldFunction 에서는 template.yaml에서 지정한 함수명을 적어주면 된다. template.yaml을 안거드렸으면 HelloWorldFunction이니까 그대로 사용하면 된다
template.yaml
1
2
3
Resources:
HelloWorldFunction: // <- 이름과 매칭되도록
Type: AWS::Serverless::Function
deploy.bat
1
2
3
echo deploy

sam build & layer.bat & sam deploy
  • 또 deploy.bat을 sam project 최상위에 만들고 내용은 위와같이 한다
  • build하고 방금 만든 layer.bat으로 배포될 빌드 디렉터리에서 node_modules을 opt 디렉터리로 옮기고
  • deploy한다

  • 결과는 이렇게 된다
  • 1.2. 디렉터리 구조를 봐보면 node_modules 폴더가 없다
  • 3.4. yaml에서 지정한 layer 등록되어 있는 것을 확인할 수 있다
  • 당연하게도 이 함수는 잘 동작한다
  • 여기까지 batch파일을 활용해서 노드모듈을 레이어로 빼는 방법을 알아보았다
  • 여기까지 프로젝트 파일

로컬에서 sam 테스트하기

  • 이제 테스트할 때 build, deploy 기다리기… 할 필요가 없다!

전제조건


sam local start-api

cmd
1
sam local start-api --skip-pull-image
cmd log
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
C:\tmp\hello-world>sam local start-api --skip-pull-image
Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM
CLI if you update your AWS SAM template
2020-09-21 13:40:36 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
2020-09-21 13:40:41 127.0.0.1 - - [21/Sep/2020 13:40:41] "GET / HTTP/1.1" 403 -
2020-09-21 13:40:41 127.0.0.1 - - [21/Sep/2020 13:40:41] "GET /favicon.ico HTTP/1.1" 403 -
Invoking app.lambdaHandler (nodejs12.x)
Requested to skip pulling images ...

Mounting C:\tmp\hello-world\.aws-sam\build\HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: 00b5b190-1c8d-184f-5ab5-c0e0764041d3 Version: $LATEST
END RequestId: 00b5b190-1c8d-184f-5ab5-c0e0764041d3
REPORT RequestId: 00b5b190-1c8d-184f-5ab5-c0e0764041d3 Init Duration: 438.88 ms
Duration: 4.53 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 44 MB
No Content-Type given. Defaulting to 'application/json'.
2020-09-21 13:40:48 127.0.0.1 - - [21/Sep/2020 13:40:48] "GET /hello HTTP/1.1" 200 -
2020-09-21 13:40:48 127.0.0.1 - - [21/Sep/2020 13:40:48] "GET /favicon.ico HTTP/1.1" 403 -
  • 나는 이렇게 명령을 쓴다
  • 나는 보통 매 실행마다 3-4초 정도 걸린다
  • build, deploy 하면서 테스트할때보다 획기적으로 빠르게 로컬에서 테스트 해볼 수 있다
  • --skip-pull-image옵션을 주는 이유는 매 실행마다 이미지를 받아오는 과정이 있는게 그걸 스킵하면 2초정도 빨라진다
  • 변경 사항은 자동으로 반영된다
  • 단점 ; 근데 변경사항이 없어도 매 실행 3초이상 걸린다
  • template.yaml 파일을 수정하면 수동으로 재시작 해줘야한다

samconfig.toml 에서 sam deploy 자동 y 설정하기

cmd log
1
2
3
Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y
  • deploy를 자주하다보면 이 y 누르는게 힘들다…

samconfig.toml 설정하기

samconfig.toml
1
2
3
4
5
6
7
8
9
10
version = 0.1
[default]
[default.deploy]
[default.deploy.parameters]
stack_name = "test-sam-app"
s3_bucket = "00000000000000000000000000000000000000000000000000000000000"
s3_prefix = "test-sam-app"
region = "ap-northeast-2"
confirm_changeset = false
capabilities = "CAPABILITY_IAM"
  • 처음 배포할때 -g옵션에서 설정했던것이 samconfig.toml에 저장되어있다
1
confirm_changeset = false
  • 여기서 confirm_changeset을 flase로 바꿔주면 중간에 확인 과정을 생략할 수 있다
  • 편안..!

sam 시작하기

  • sam을 이용해서 hello world 프로젝트 만들어 보기
  • nodejs로 만든다

전제조건

SAM(Serverless Application Model)

  • 겁나 어려워 보이는데 그냥 람다 생성기라고 생각하면 된다
  • 로컬에서 편하게 vscode로 람다함수짜고 yml 파일 수정해서..!
  • 로컬 테스트 환경도 제공한다!

따라하기

cmd
1
2
3
4
5
6
7
sam init

C:\tmp>sam init
Which template source would you like to use?
1 - AWS Quick Start Templates
2 - Custom Template Location
Choice:
  • 1번, 1번해서
  • AWS Quick Start Templates, nodejs 를 골라준다
cmd
1
Project name [sam-app]: hello-world
  • 프로젝트명 설정하면, 샘플 프로젝트를 가져온다
cmd
1
2
3
4
5
6
7
8
9
10
AWS quick start application templates:
1 - Hello World Example
2 - Step Functions Sample App (Stock Trader)
3 - Quick Start: From Scratch
4 - Quick Start: Scheduled Events
5 - Quick Start: S3
6 - Quick Start: SNS
7 - Quick Start: SQS
8 - Quick Start: Web Backend
Template selection: 1
  • 1번 선택하여 헬로월드 템플릿을 받아온다
cmd
1
cd hello-world
  • 이제 생성된 프로젝트로 들어간다
1
2
3
4
5
6
7
8
9
10
11
.
├── events
│ └── event.json
├── hello-world
│ ├── tests/
│ ├── .npmignore
│ ├── app.js
│ └── package.json
├── .gitignore
├── README.md
└── template.yaml
  • 디렉터리 구조는 이러하다
  • 여기서 중요한 파일은 hello-world/app.jstemplate.yaml이다

  • 2개 파일 소스 대충 어떻게 생겼는지 봐보고 빌드해본다
cmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
sam build

C:\tmp\hello-world>sam build
Building function 'HelloWorldFunction'
Running NodejsNpmBuilder:NpmPack
Running NodejsNpmBuilder:CopyNpmrc
Running NodejsNpmBuilder:CopySource
Running NodejsNpmBuilder:NpmInstall
Running NodejsNpmBuilder:CleanUpNpmrc

Build Succeeded

Built Artifacts : .aws-sam\build
Built Template : .aws-sam\build\template.yaml

Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided
  • .aws-sam 이라는 폴더가 생성된다
1
2
3
4
5
6
7
.aws-sam
└── build
├── HelloWorldFunction
│ ├── node_modules/
│ ├── app.js
│ └── package.json
└── template.yaml
  • 이제 배포해보자
cmd
1
sam deploy -g
  • 배포하자. -g옵션은 --guided 와 동일하다
  • 이 옵션은 최초에 배포할때만 사용된다
cmd log
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Configuring SAM deploy
======================

Looking for samconfig.toml : Not found

Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]: test-sam-app
AWS Region [us-east-1]: ap-northeast-2
#Shows you resources changes to be deployed and require a 'Y' to initiate deploy
Confirm changes before deploy [y/N]: y
#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]: y
HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
Save arguments to samconfig.toml [Y/n]: y
  • 먼저 Stack Name을 지정해준다. 공란으로 하면 sam-app으로 적용된다
  • 다음은 리전 설정이다. 나는 서울 ap-northeast-2로 지정했다
  • 다음은 전부다 y 해준다
cmd log
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CloudFormation stack changeset
----------------
Operation LogicalResourceId ResourceType
----------------
+ Add HelloWorldFunctionHelloWorldPermissionProd AWS::Lambda::Permission
+ Add HelloWorldFunctionRole AWS::IAM::Role
+ Add HelloWorldFunction AWS::Lambda::Function
+ Add ServerlessRestApiDeployment47fc2d5f9d AWS::ApiGateway::Deployment
+ Add ServerlessRestApiProdStage AWS::ApiGateway::Stage
+ Add ServerlessRestApi AWS::ApiGateway::RestApi
----------------

Changeset created successfully. arn:aws:cloudformation:ap-northeast-2:111111111111:changeSet/samcli-deploy1600652952/89cf8cb3-a626-44ef-bd26-815dacedaa8e


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y
  • 또 어쩌구 저쩌구 나오면서 마지막 확인을 받는데 y 해준다
cmd log
1
Successfully created/updated stack - test-sam-app in ap-northeast-2
  • 그러면 시간이 쫌 걸리면서 aws에 올라가게 된다

  • samconfig.toml 파일이 생성된 것을 확인할 수 있다

  • 이제 브라우저를 열어서 aws lambda 로 들어간다

  • 위와 같이 [스택네임]-HelloWorldFunction이름의 함수 하나가 생성되었다
  • 눌러서 들어간다
  • 이런 화면이 나온다
  • api 게이트웨이를 클릭한다. 그러면 아래 화면이 api 게이트웨이로 바뀐다. 거기서 다시 세부 정보를 클릭해서 api 엔드포인트를 확인한다
  • 엔드포인트를 눌러 접속한다
  • {"message":"hello world"}이 보이면 성공이다
  • 이렇게 다짜고짜 sam으로 람다를 만들어 보았다

해설

  • sam Hello World Example template를 이용해서 람다를 만들었다
  • 이 람다는 어떤 주소로 접속하면 hello world를 반환하는 람다이다
  • 현재 프로젝트 구조를 잘 살펴보면 sam을 익히면 된다
  • 먼저 이 {"message":"hello world"}는 어디서 왔을까?
hello-world/app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
exports.lambdaHandler = async (event, context) => {
try {
// const ret = await axios(url);
response = {
statusCode: 200,
body: JSON.stringify({
message: 'hello world',
// location: ret.data.trim()
}),
};
} catch (err) {
console.log(err);
return err;
}

return response;
};
  • lambdaHandler라는 함수가 있는데 response객체를 반환한다
  • 근데 우리는 {“message”:”hello world”} 만 보이니까 body에 있는 내용을 조작하면 우리가 원하는 내용을 보낼 수 있겠구나 생각할 수 있다
  • 그러면 이 함수를 실행시키는 트리거, s22xid3g26.execute-api.ap-northeast-2.amazonaws.com/Prod/hello
  • api 게이트웨이의 엔드포인트는 어디서 설정되었을까?
template.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello-world/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
  • template.yaml을 보면 Events 아래 Type: Api가 보인다
  • hello라는 Path로 get 요청이 왔을때 라고 이해할 수 있다

  • 이제 이를 토대로 람다를 업그레이드 해보자

심볼릭 링크 만들기

  • 동기화 하고 싶은 폴더가 있을때 정말 좋다

심볼릭 링크 만드는 법

  • 절대 위치 사용 ; mklink /d [링크위치] [실제위치]
  • 상대 위치 사용 ; mklink /d [링크위치] [링크위치를 기준으로 상대위치]
    • ex ) mklink /d .\.aws-sam\build\CommentFunction ..\..\dist
  • 링크이름 ; 새로만들어질 폴더 ; 현재 존재하지 않는 폴더여야 함
  • 실제위치 ; 원본 폴더 ; 이미 만들어져 있는 폴더

심볼릭 링크 삭제

rmdir [링크]

심볼릭 링크

  • 폴더 내용물이 공유된다. (사본이 아님)
  • 링크 폴더도 실제 폴더 처럼 작동한다
  • 바로가기 아이콘을 하고 있다
  • 원본 폴더에 별명을 지어준 느낌이다
  • 포인터 같은 느낌이다

  • 권한이 없다고 하면 관리자 권한으로 명령을 실행한다

상대경로를 사용해 만든경우

  • 당연한 말이지만 원본 폴더나 링크 폴더의 위치가 바뀌면 안된다
  • 디렉터리 구조가 변하지 않고 두 폴더를 이동한다면 잘 작동한다

절대경로를 사용해 만든경우

  • 링크 폴더를 아무렇게나 이동시켜도 잘 작동한다
  • 당연한 말이지만 원본 폴더를 옮기면 작동하지 않는다

내가 활용한 곳

aws lambda layer

  • lambda 에서는 함수의 크기를 줄이기 위해 layer라는 것을 사용한다
  • sam project에서 lambda를 작성하고 node_modules 같은 무거운 얘들은 layer로 빼야한다
  • 그런데 이 과정이 매우 귀찮다
    • package.json 에서 종속성들이 빌드되지 않게 주석
    • sam yaml에서 지정한 종속성 경로에 node_modules 사본 또는 옮기기
    • 수정작업할때, 코딩할때 자동완성 및 문서를 보기 위해서는 node_modules 폴더가 함수 안에 필요함
  • sam yaml에서 지정한 종속성 경로는 함수안이 되면 안됨. 즉, 직접 다이렉트로 node_modules를 지정할 수 없음. sam project 루트로 빼던가 해야함
  • 여기서 심볼릭 링크를 활용해서 두 폴더간 동기화를 진행!