1. SAM 설치
1.1 SAM CLI 설치파일 다운로드
AWS SAM CLI 64-bit 를 눌러 다운받습니다.
https://github.com/aws/aws-sam-cli/releases/latest/download/AWS_SAM_CLI_64_PY3.msi
1.2 설치파일 실행
AWS_SAM_CLI_64_PY3.msi를 실행하여 설치합니다.
1.3 설치 확인
Terminal을 열어 설치를 확인합니다.
sam --version
설치를 성공하면 아래와 비슷한 결과가 나옵니다.
SAM CLI, version 1.23.0
1.4 Docker 설치
여기를 눌러 Docker 설치 페이지로 이동합니다.
Docker Desktop for Windows를 눌러 Docker를 설치합니다.
1.5 AWS Toolkit(VScode Extension)
아래 순서대로 진행합니다.
- VScode 왼쪽 메뉴 중 다섯번째 탭(Extensions) 선택
- 검색 창에 aws 입력
- AWS Toolkit 선택 후 Install
AWS configure을 실행하여 접속 정보를 입력합니다.
2. SAM – Hello World!
아래의 순서를 따라 Sample Application을 생성합니다.
- AWS Toolkit 선택
- 메뉴 선택 (···)
- Create Lambda SAM Application 선택
python 3.8을 선택하여 파이썬으로 Sample Application을 생성합니다.
AWS SAM Hello World를 선택합니다.
프로젝트를 생성할 폴더를 선택합니다. 현재 Workspace를 선택합니다.
어플리케이션의 이름을 입력합니다. 기본값으로 입력하고 넘어갑니다.
얼마지나지않아, Workspace에 새로운 폴더와 파일들이 생겼습니다. 벌써 다 한 기분이에요!
3. Event
Lambda를 호출하는 Event를 로컬에서 생성합니다. 생성한 내용을 복사하여 events 폴더 아래 event.json 파일에 붙여넣어 사용합니다.
3.1 Cloudwatch Schedule
sam local generate-event cloudwatch scheduled-event
{
"id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
"detail-type": "Scheduled Event",
"source": "aws.events",
"account": "123456789012",
"time": "1970-01-01T00:00:00Z",
"region": "us-east-1",
"resources": [
"arn:aws:events:us-east-1:123456789012:rule/ExampleRule"
],
"detail": {}
}
3.2 APIGateway aws-proxy
sam local generate-event apigateway aws-proxy
{
"body": "eyJ0ZXN0IjoiYm9keSJ9",
"resource": "/{proxy+}",
"path": "/path/to/resource",
"httpMethod": "POST",
"isBase64Encoded": true,
"queryStringParameters": {
"foo": "bar"
},
"multiValueQueryStringParameters": {
"foo": [
"bar"
]
},
"pathParameters": {
"proxy": "/path/to/resource"
},
"stageVariables": {
"baz": "qux"
},
"headers": {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Accept-Language": "en-US,en;q=0.8",
"Cache-Control": "max-age=0",
...
}
}
4. 코드 변경
기존 Sample은 API Gateway로 Lambda를 호출합니다. 우리는 API Gateway 대신 Cloudwatch Schedule Event로 Lambda를 호출해봅니다.
4.1 Event
event.json 파일을 수정합니다. 3.1 Cloudwatch Schedule에서 생성한 내용으로 변경합니다.
// lambda-python3.8/events/event.json
{
"id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
"detail-type": "Scheduled Event",
"source": "aws.events",
"account": "123456789012",
"time": "1970-01-01T00:00:00Z",
"region": "us-east-1",
"resources": ["arn:aws:events:us-east-1:123456789012:rule/ExampleRule"],
"detail": {}
}
4.2 App
app.py 파일을 수정합니다. 주석으로 되어있는 내용을 지우고 실행되는 코드만 남깁니다.
import json
def lambda_handler(event, context):
return {
"statusCode": 200,
"body": json.dumps({"message": "hello world"}),
}
4.3 Test
tests 폴더는 삭제합니다.
4.4 Template
template.yaml 파일을 수정합니다. Resources 항목 아래의 Events를 변경합니다.
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.lambda_handler
Runtime: python3.8
Events:
CheckScheduledEvent:
Type: Schedule
Properties:
Schedule: rate(1 minute)
Outputs 내용 중 API gateway 내용은 삭제합니다.
Outputs:
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
5. Test
5.1 Build
Docker container로 코드를 build합니다.
sam build --use-container
or
위의 코드를 실행했는데 에러가 발생한다면 아래의 코드로 실행하세요. Image Repository를 Amazon ECR에서 DockerHub로 변경한 코드입니다. 여기를 눌러 추가 컨테이너 이미지를 확인할 수 있습니다.
sam build --use-container --build-image amazon/aws-sam-cli-build-image-python3.8
빌드에 성공하였다면, 아래처럼 Output을 출력합니다.
Starting Build inside a container
...
Fetching amazon/aws-sam-cli-build-image-python3.8 Docker container image...............................
...
Build Succeeded
Built Artifacts : .aws-sambuild
Built Template : .aws-sambuildtemplate.yaml
Commands you can use next
=========================
[*] Invoke Function: sam local invoke
[*] Deploy: sam deploy --guided
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource
5.2 Test
Event로 Lambda를 호출하였을 때 의도대로 동작하는지 테스트합니다.
sam local invoke
특별한 건 없으니, app.py에 정의한 return대로 나오는 것을 확인할 수 있습니다.
Invoking app.lambda_handler (python3.8)
Image was not found.
Building image..............................................................
Skip pulling image and use local one: amazon/aws-sam-cli-emulation-image-python3.8:rapid-1.23.0.
...
START RequestId: 0b770a09-33ec-4349-9714-bc0d93b6f55f Version: $LATEST
END RequestId: 0b770a09-33ec-4349-9714-bc0d93b6f55f
REPORT RequestId: 0b770a09-33ec-4349-9714-bc0d93b6f55f Init Duration: 0.20 ms Duration: 119.95 ms Billed Duration: 200 ms Memory Size: 128 MB Max Memory Used: 128 MB
{"statusCode": 200, "body": "{"message": "hello world"}"}
6. 배포
아래 명령어를 입력하여 배포를 시작합니다.
sam deploy --guided
설정에 필요한 값을 입력하면 자동으로 Cloudformation Stack을 생성하여 Lambda를 생성합니다.
Configuring SAM deploy
======================
Looking for config file [samconfig.toml] : Not found
Setting default arguments for 'sam deploy'
=========================================
Stack Name [sam-app]: laminar
AWS Region [ap-southeast-1]:
#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
Save arguments to configuration file [Y/n]: y
SAM configuration file [samconfig.toml]:
SAM configuration environment [default]:
Looking for resources needed for deployment: Not found.
Creating the required resources...
Successfully created!
Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-3k8v1edfkc8r
A different default S3 bucket can be set in samconfig.toml
Saved arguments to config file
Running 'sam deploy' for future deployments will use the parameters saved above.
The above parameters can be changed by modifying samconfig.toml
Learn more about samconfig.toml syntax at
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
Uploading to laminar/4026c532d246ee38cd02526cefa4b0ca 599959 / 599959 (100.00%)
Deploying with following values
===============================
Stack name : laminar
Region : ap-southeast-1
Confirm changeset : True
Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-3k8v1edfkc8r
Capabilities : ["CAPABILITY_IAM"]
Parameter overrides : {}
Signing Profiles : {}
Initiating deployment
=====================
Uploading to laminar/403e1d4b78e92f8b88a182cbbace44aa.template 937 / 937 (100.00%)
Waiting for changeset to be created..
CloudFormation stack changeset
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Operation LogicalResourceId ResourceType Replacement
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+ Add HelloWorldFunctionCheckScheduledEventPermission AWS::Lambda::Permission N/A
+ Add HelloWorldFunctionCheckScheduledEvent AWS::Events::Rule N/A
+ Add HelloWorldFunctionRole AWS::IAM::Role N/A
+ Add HelloWorldFunction AWS::Lambda::Function N/A
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Changeset created successfully. arn:aws:cloudformation:ap-southeast-1:<Your-AWS-Account-Number>:changeSet/samcli-deploy1620266678/50099513-3dad-4d7f-9394-06ba407654ff
Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y
2021-05-06 11:04:54 - Waiting for stack create/update to complete
CloudFormation events from changeset
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus ResourceType LogicalResourceId ResourceStatusReason
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole Resource creation Initiated
CREATE_IN_PROGRESS AWS::IAM::Role HelloWorldFunctionRole -
CREATE_COMPLETE AWS::IAM::Role HelloWorldFunctionRole -
CREATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction Resource creation Initiated
CREATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction -
CREATE_COMPLETE AWS::Lambda::Function HelloWorldFunction -
CREATE_IN_PROGRESS AWS::Events::Rule HelloWorldFunctionCheckScheduledEvent -
CREATE_IN_PROGRESS AWS::Events::Rule HelloWorldFunctionCheckScheduledEvent Resource creation Initiated
CREATE_COMPLETE AWS::Events::Rule HelloWorldFunctionCheckScheduledEvent -
CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionCheckScheduledEventPermission Resource creation Initiated
CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionCheckScheduledEventPermission -
CREATE_COMPLETE AWS::Lambda::Permission HelloWorldFunctionCheckScheduledEventPermission -
CREATE_COMPLETE AWS::CloudFormation::Stack laminar -
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Outputs
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Key HelloWorldFunctionIamRole
Description Implicit IAM Role created for Hello World function
Value arn:aws:iam::<Your-AWS-Account-Number>:role/laminar-HelloWorldFunctionRole-PDFE5J2Z023K
Key HelloWorldFunction
Description Hello World Lambda Function ARN
Value arn:aws:lambda:ap-southeast-1:<Your-AWS-Account-Number>:function:laminar-HelloWorldFunction-J7T81X5HW8UU
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Successfully created/updated stack - laminar in ap-southeast-1
필요한 라이브러리까지 포함하여 생성한 것을 Console에서 확인할 수 있습니다.
7. 삭제
AWS SAM CLI는 stack 삭제를 지원하지 않고, AWS CLI를 사용하거나 VScode AWS Toolkit 확장 기능을 활용하여 삭제할 수 있습니다.
7.1 AWS CLI
aws cloudformation delete-stack --stack-name laminar
7.2 VScode Extensions
다음 글 보기
이전 글 보기