본문 바로가기

⭐ AWS/SAM (ServerlessApplicationModel)

SAM Build & Deploy with Python

# SAM을 빌드 및 배포 해보자.

1. 아래의 명령어를 입력하여 sample app을 생성한다.

C:\Users\김승현\Desktop\SAM\SAM_Python>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 - Data processing
        3 - Hello World Example with Powertools for AWS Lambda
        4 - Multi-step workflow
        5 - Scheduled task
        6 - Standalone function
        7 - Serverless API
        8 - Infrastructure event management
        9 - Lambda Response Streaming
        10 - Serverless Connector Hello World Example
        11 - Multi-step workflow with Connectors
        12 - GraphQLApi Hello World Example
        13 - Full Stack
        14 - Lambda EFS example
        15 - Hello World Example With Powertools for AWS Lambda
        16 - DynamoDB Example
        17 - Machine Learning
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]: y

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

Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: y
Structured Logging in JSON format might incur an additional cost. View https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html#monitoring-cloudwatchlogs-pricing for more details

Project name [sam-app]: sam-app-example

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app-example
    Runtime: python3.9
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    Configuration file: sam-app-example\samconfig.toml

    Next steps can be found in the README file at sam-app-example\README.md


Commands you can use next
=========================
[*] Create pipeline: cd sam-app-example && sam pipeline init --bootstrap
[*] Validate SAM template: cd sam-app-example && sam validate
[*] Test Function in the Cloud: cd sam-app-example && sam sync --stack-name {stack-name} --watch

2. Python 기반으로 생성된 폴더 구조는 아래와 같다.

아래의 파일 목록중 가장 중요한 파일은 template.yaml 파일이다.

template.yaml에는 프로젝트에 대한 정보들 그리고 Resource하위에는 사용자가 접근할 endpoint 그리고 lambda 함수에 대해서 적혀있다.

- template.yaml 파일의 내용은 아래와 같다.

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.9
      Architectures:
      - x86_64
      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

3. 코드 실행 프로세스는 아래와 같다. (매우 심플)

CodeUri : 함수가 위치하는 디렉토리를 명시한다.

Handler : 파일명.함수명으로 작성한다. ex) app.py의 lambda_handler같은 경우는 아래와 같이 app. lambda_handler로 설정한다.

4. 빌드 및 배포하기

빌드 : sam build

최초 배포 : sam deploy --guided

- 최초 빌드를 수행하면 아래와 같이 몇가지 질문이 나오고 해당 내용을 아래와 같이 입력해준다.

(아래 부분에서 비어있는 부분은 enter를 입력.)

C:\Users\김승현\Desktop\SAM\SAM_Python\sam-app-example>sam deploy --guided

Configuring SAM deploy
======================

        Looking for config file [samconfig.toml] :  Found
        Reading default arguments  :  Success

        Setting default arguments for 'sam deploy'
        =========================================
        Stack Name [sam-app-example]:
        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 has no authentication. Is this okay? [y/N]: y
        Save arguments to configuration file [Y/n]:
        SAM configuration file [samconfig.toml]:
        SAM configuration environment [default]:

일단 aws configure를 통해 현재 AWS 리소스에 접근 가능한 Access Key ID와 Secret Access Key를 사전에 설정해 놓아야 한다. 해당 aws auth 정보를 기반으로 SAM 애플리케이션이 생성된다.

5. 빌드 완료 후 정보

- 빌드가 완료된 후 정보는 아래와 같다.

아래의 정보에서 빨간색 박스의 Endpoint 주소를 웹으로 접근하면 결과를 받아 볼 수 있다.

- 웹 접속 결과는 아래와 같다.

위의 코드와 같이 hello world를 리턴받은 모습을 볼 수 있다.

6. AWS Console에서 리소스를 확인해 보자.

lambda 함수와 Api Gateway가 자동으로  생성된것을 확인 할 수 있다.

7. 삭제

sam delete

- 아래와 같이 물어보고 y를 누르면 삭제가 진행 된다.

 

- 끝 -