사용 지침서: Hello World 애플리케이션 배포 - AWS Serverless Application Model

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

사용 지침서: Hello World 애플리케이션 배포

이 사용 지침서에서는 AWS Serverless Application Model 명령줄 인터페이스(AWS SAMCLI)를 사용하여 다음을 완료합니다.

  • 샘플 Hello World 애플리케이션을 초기화, 빌드 및 배포합니다.

  • 로컬에서 변경하고 AWS CloudFormation에 동기화합니다.

  • AWS 클라우드에서 애플리케이션을 테스트합니다.

  • 개발 호스트에서 로컬 테스트를 수행할 수도 있습니다.

  • AWS 클라우드에서 샘플 애플리케이션을 삭제합니다.

샘플 Hello World 애플리케이션은 기본적인 API 백엔드를 구현합니다. 다음 리소스로 구성됩니다.

  • Amazon API Gateway – 함수를 호출하는 데 사용할 API 엔드포인트입니다.

  • AWS Lambda – HTTP API GET 요청을 처리하고 hello world 메시지를 반환하는 함수입니다.

  • AWS Identity and Access Management(IAM) 역할 – 서비스가 안전하게 상호 작용할 수 있는 권한을 제공합니다.

다음 다이어그램은 이 애플리케이션의 구성 요소를 보여줍니다.


			귀하가 API 게이트웨이 엔드포인트에 GET 요청을 보낼 때 호출되는 Lambda 함수의 다이어그램.

사전 조건

다음 단계들을 귀하가 완료했는지 확인하십시오.

1단계: Hello World 샘플 애플리케이션 초기화

이 단계에서는 AWS SAM CLI를 사용하여 귀하의 로컬 기기에 샘플 Hello World 애플리케이션 프로젝트를 생성합니다.

샘플 Hello World 애플리케이션을 초기화하려면
  1. 명령줄 프롬프트에 선택한 시작 디렉터리에서 다음 명령을 실행합니다.

    $ sam init
  2. AWS SAM CLI가 새 애플리케이션을 초기화하는 과정을 안내합니다. 다음을 구성합니다.

    1. AWS퀵 스타트 템플릿을 선택하여 시작 템플릿을 선택합니다.

    2. Hello World 예제 템플릿을 선택하고 다운로드하십시오.

    3. Python런타임 및 zip 패키지 유형을 사용합니다.

    4. 이 사용 지침서에서는 AWS X-Ray 추적을 옵트아웃합니다. 자세한 내용은 AWS X-Ray 개발자 가이드에서 AWS X-Ray란 무엇입니까?를 참조하세요.

    5. 이 자습서에서는 Amazon CloudWatch 애플리케이션 인사이트를 통한 모니터링을 옵트아웃하십시오. 자세한 내용은 Amazon CloudWatch 사용 설명서의 Amazon CloudWatch 애플리케이션 인사이트를 참조하십시오.

    6. 애플리케이션 이름을 sam-app으로 지정합니다.

    AWS SAMCLI대화형 흐름을 사용하려면:

    • 대괄호([ ])는 기본값을 나타냅니다. 기본값을 선택하려면 답을 비워둡니다.

    • y를 입력하고 아니요n를 입력합니다.

    다음은 sam init 대화형 흐름에 대한 예제입니다.

    $ sam init ... 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 EFS example 12 - DynamoDB Example 13 - 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]: ENTER 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]: ENTER Project name [sam-app]: ENTER
  3. AWS SAM CLI는 시작 템플릿을 다운로드하고 귀하의 로컬 기기에 애플리케이션 프로젝트 디렉터리 구조를 만듭니다. 다음은 AWS SAM CLI 출력의 예시입니다.

    Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
    
        -----------------------
        Generating application:
        -----------------------
        Name: sam-app
        Runtime: python3.9
        Architectures: x86_64
        Dependency Manager: pip
        Application Template: hello-world
        Output Directory: .
        Configuration file: sam-app/samconfig.toml
    
        Next steps can be found in the README file at sam-app/README.md
    
    
    Commands you can use next
    =========================
    [*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
    [*] Validate SAM template: cd sam-app && sam validate
    [*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch
  4. 명령줄에서 새로 만든 sam-app 디렉터리로 이동합니다. 다음은 AWS SAM CLI에서 만든 내용의 예입니다.

    $ cd sam-app $ tree ├── README.md ├── __init__.py ├── events │ └── event.json ├── hello_world │ ├── __init__.py │ ├── app.py │ └── requirements.txt ├── samconfig.toml ├── template.yaml └── tests ├── __init__.py ├── integration │ ├── __init__.py │ └── test_api_gateway.py ├── requirements.txt └── unit ├── __init__.py └── test_handler.py 6 directories, 14 files

    강조해야 할 몇 가지 중요한 파일:

    • hello_world/app.py – 귀하의 Lambda 함수 코드가 포함되어 있습니다.

    • hello_world/requirements.txt – Lambda 함수에 필요한 모든 Python 종속물을 포함합니다.

    • samconfig.toml – AWS SAM CLI에 의해 사용되는 기본 파라미터를 저장하는 애플리케이션의 구성 파일.

    • template.yaml – 귀하의 애플리케이션 인프라 코드가 들어 있는 AWS SAM 템플릿입니다.

이제 로컬 컴퓨터에 완전히 작성된 서버리스 애플리케이션이 생겼습니다!

2단계: 귀하의 애플리케이션 빌드

이 단계에서는 AWS SAM CLI를 사용하여 애플리케이션을 빌드하고 배포를 준비합니다. 빌드하면, AWS SAM CLI가 .aws-sam 디렉토리를 만들고 여기에 함수 종속성, 프로젝트 코드 및 프로젝트 파일을 구성합니다.

귀하의 애플리케이션을 빌드하려면
  • 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam build
    참고

    로컬 기기에 Python이 설치되어 있지 않은 경우, sam build --use-container 명령어를 대신 사용합니다. AWS SAMCLI는 함수의 런타임과 종속물을 포함하는 Docker 컨테이너를 생성합니다. 이 명령은 로컬 기기에 Docker을 필요로 합니다. Docker의 설치는 Docker 설치을 참조하십시오

    다음은 AWS SAM CLI 출력의 예시입니다.

    $ sam build Starting Build use cache Manifest file is changed (new hash: 3298f1304...d4d421) or dependency folder (.aws-sam/deps/4d3dfad6-a267-47a6-a6cd-e07d6fae318c) is missing for (HelloWorldFunction), downloading dependencies and copying/building source Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction Running PythonPipBuilder:CleanUp Running PythonPipBuilder:ResolveDependencies Running PythonPipBuilder:CopySource Running PythonPipBuilder:CopySource Build Succeeded Built Artifacts : .aws-sam/build Built Template : .aws-sam/build/template.yaml Commands you can use next ========================= [*] Validate SAM template: sam validate [*] Invoke Function: sam local invoke [*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch [*] Deploy: sam deploy --guided

    다음은 AWS SAM CLI가 생성한 .aws-sam 디렉토리의 축약된 예입니다.

    .aws-sam
    ├── build
    │   ├── HelloWorldFunction
    │   │   ├── __init__.py
    │   │   ├── app.py
    │   │   └── requirements.txt
    │   └── template.yaml
    └── build.toml

강조해야 할 몇 가지 중요한 파일:

  • build/HelloWorldFunction – Lambda 함수 코드 및 종속 항목이 포함되어 있습니다. AWS SAM CLI는 애플리케이션의 각 함수에 대한 디렉토리를 생성합니다.

  • build/template.yaml – 배포 시 AWS CloudFormation이 참조하는 AWS SAM 템플릿 사본이 들어 있습니다.

  • build.toml – 애플리케이션을 빌드하고 배포할 때 AWS SAM CLI이 참조하는 기본 파라미터 값을 저장하는 구성 파일입니다.

이제 AWS 클라우드에 귀하의 애플리케이션을 배포할 준비가 되었습니다.

3단계: AWS 클라우드에 대한 애플리케이션 배포

참고

이 단계에는 AWS 보안 인증 구성이 필요합니다. 자세한 내용은 AWS SAM 필수 조건에서 5단계: AWS CLI을 사용하여 AWS 보안 인증을 구성합니다.을 잠조하세요

이 단계에서는 AWS SAM CLI를 사용하여 애플리케이션을 AWS 클라우드에 배포합니다. AWS SAM CLI는 다음과 같은 작업을 수행합니다.

  • 배포를 위한 애플리케이션 설정을 구성하는 과정을 안내합니다.

  • Amazon Simple Storage Service(S3)에 귀하의 애플리케이션 파일을 업로드합니다.

  • AWS SAM템플릿을 AWS CloudFormation 템플릿으로 변환하십시오. 그런 다음 템플릿을 AWS CloudFormation 서비스에 업로드하여 AWS 리소스를 프로비저닝합니다.

애플리케이션을 배포하려면
  1. 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam deploy --guided
  2. AWS SAMCLI 대화형 흐름에 따라 애플리케이션 설정을 구성하십시오. 다음을 구성합니다.

    1. AWS CloudFormation스택 이름 - 스택이란 하나의 단위로 관리할 수 있는 AWS 리소스의 모음입니다. 자세히 알아보려면 AWS CloudFormation 사용자 가이드의 스택 작업을 잠조하세요.

    2. AWS CloudFormation스택을 배포할 AWS 리전 자세한 내용은 AWS CloudFormation 사용자 가이드AWS CloudFormation엔드포인트를 잠조하세요.

    3. 이 사용 지침서에서는 배포 전 변경 사항 확인을 옵트아웃합니다.

    4. IAM 역할 생성 허용 - 이를 통해 AWS SAM가 API Gateway 리소스와 Lambda 함수 리소스가 상호 작용하는 데 필요한 IAM 역할을 생성할 수 있습니다.

    5. 이 사용 지침서에서는 롤백 비활성화를 옵트아웃합니다.

    6. 승인 HelloWorldFunction 없이 허용 정의 - API Gateway 엔드포인트가 승인 없이 공개적으로 액세스할 수 있도록 구성되어 있기 때문에 이 메시지가 표시됩니다. 이것이 Hello World 애플리케이션을 위한 의도된 구성이므로 AWS SAM CLI가 계속 진행되도록 합니다. 권한 부여 전송에 대한 자세한 내용은을 잠조하세요API Gateway API에 대한 액세스 제어

    7. 구성 파일에 인수 저장 - 그러면 배포 우선 설정에 따라 애플리케이션의 samconfig.toml 파일이 업데이트됩니다.

    8. 기본 구성 파일 이름을 선택합니다.

    9. 기본 구성 환경을 선택합니다.

    다음은 sam deploy --guided 대화형 플로우의 출력의 예제입니다.

    $ sam-app 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]: ENTER AWS Region [us-west-2]: ENTER #Shows you resources changes to be deployed and require a 'Y' to initiate deploy Confirm changes before deploy [Y/n]: 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]: ENTER #Preserves the state of previously provisioned resources when an operation fails Disable rollback [y/N]: ENTER HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y Save arguments to configuration file [Y/n]: ENTER SAM configuration file [samconfig.toml]: ENTER SAM configuration environment [default]: ENTER
  3. AWS SAM CLI는 다음을 수행하여 애플리케이션을 배포합니다.

    • AWS SAM CLI는 Amazon S3 버킷을 생성하고 귀하의 .aws-sam 디렉터리를 업로드합니다.

    • AWS SAM CLI는 귀하의 AWS SAM템플릿을 AWS CloudFormation로 변환하여 AWS CloudFormation 서비스에 업로드합니다.

    • AWS CloudFormation은 귀하의 리소스를 프로비저닝합니다.

    배포 중에는 AWS SAM CLI는 귀하의 진행 상황을 표시합니다. 다음은 출력의 예제입니다.

    Looking for resources needed for deployment:
    
        Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1a4x26zbcdkqr
        A different default S3 bucket can be set in samconfig.toml
    
        Parameter "stack_name=sam-app" in [default.deploy.parameters] is defined as a global parameter [default.global.parameters].
        This parameter will be only saved under [default.global.parameters] in /Users/.../Demo/sam-tutorial1/sam-app/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
    
    File with same data already exists at sam-app/da3c598813f1c2151579b73ad788cac8, skipping upload
    
        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : us-west-2
        Confirm changeset            : False
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}
    
    Initiating deployment
    =====================
    
    File with same data already exists at sam-app/2bebf67c79f6a743cc5312f6dfc1efee.template, skipping upload
    
    
    Waiting for changeset to be created..
    
    CloudFormation stack changeset
    ---------------------------------------------------------------------------------------------------------------------------------------------
    Operation                           LogicalResourceId                   ResourceType                        Replacement
    ---------------------------------------------------------------------------------------------------------------------------------------------
    * Modify                            HelloWorldFunction                  AWS::Lambda::Function               False
    * Modify                            ServerlessRestApi                   AWS::ApiGateway::RestApi            False
    - Delete                            AwsSamAutoDependencyLayerNestedSt   AWS::CloudFormation::Stack          N/A
                                        ack
    ---------------------------------------------------------------------------------------------------------------------------------------------
    
    
    Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1678917603/22e05525-08f9-4c52-a2c4-f7f1fd055072
    
    
    2023-03-15 12:00:16 - Waiting for stack create/update to complete
    
    CloudFormation events from stack operations (refresh every 0.5 seconds)
    ---------------------------------------------------------------------------------------------------------------------------------------------
    ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
    ---------------------------------------------------------------------------------------------------------------------------------------------
    UPDATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  -
    UPDATE_COMPLETE                     AWS::Lambda::Function               HelloWorldFunction                  -
    UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          sam-app                             -
    SS
    DELETE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                            ack
    DELETE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                            ack
    UPDATE_COMPLETE                     AWS::CloudFormation::Stack          sam-app                             -
    ---------------------------------------------------------------------------------------------------------------------------------------------
    
    CloudFormation outputs from deployed stack
    ----------------------------------------------------------------------------------------------------------------------------------------------
    Outputs
    ----------------------------------------------------------------------------------------------------------------------------------------------
    Key                 HelloWorldFunctionIamRole
    Description         Implicit IAM Role created for Hello World function
    Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-15GLOUR9LMT1W
    
    Key                 HelloWorldApi
    Description         API Gateway endpoint URL for Prod stage for Hello World function
    Value               https://<restapiid>.execute-api.us-west-2.amazonaws.com/Prod/hello/
    
    Key                 HelloWorldFunction
    Description         Hello World Lambda Function ARN
    Value               arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-yQDNe17r9maD
    ----------------------------------------------------------------------------------------------------------------------------------------------
    
    
    Successfully created/updated stack - sam-app in us-west-2

이제 귀하의 애플리케이션이 배포되어 AWS 클라우드에서 실행 중입니다!

4단계: 애플리케이션의 실행

이 단계에서는 API 엔드포인트에 GET 요청을 보내고 Lambda 함수 출력을 확인합니다.

API 엔드포인트 값을 가져오려면
  1. 이전 단계에서 AWS SAM CLI에 의해 표시된 정보에서 Outputs 섹션을 찾습니다. 이 섹션에서 HelloWorldApi 리소스를 찾아 HTTP 엔드포인트 값을 찾으십시오. 다음은 출력의 예제입니다.

    ----------------------------------------------------------------------------------------------------------------------------------------------
    Outputs
    ----------------------------------------------------------------------------------------------------------------------------------------------
    ...
    Key                 HelloWorldApi
    Description         API Gateway endpoint URL for Prod stage for Hello World function
    Value               https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
    ...
    ----------------------------------------------------------------------------------------------------------------------------------------------
  2. 다른 방식으로는 sam list endpoints --output json 명령을 사용하여 이 정보를 가져올 수 있습니다. 다음은 출력의 예제입니다.

    $ sam list endpoints --output json 2023-03-15 12:39:19 Loading policies from IAM... 2023-03-15 12:39:25 Finished loading policies from IAM. [ { "LogicalResourceId": "HelloWorldFunction", "PhysicalResourceId": "sam-app-HelloWorldFunction-yQDNe17r9maD", "CloudEndpoint": "-", "Methods": "-" }, { "LogicalResourceId": "ServerlessRestApi", "PhysicalResourceId": "ets1gv8lxi", "CloudEndpoint": [ "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod", "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Stage" ], "Methods": [ "/hello['get']" ] } ]
함수를 호출하려면
  • 브라우저 또는 명령줄을 사용하여 API 엔드포인트에 GET 요청을 보냅니다. 다음은 curl 명령을 사용한 예입니다.

    $ curl https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/ {"message": "hello world"}

5단계: AWS 클라우드에서 함수와 상호작용하십시오.

이 단계에서는 AWS SAM CLI를 사용하여 AWS 클라우드에서 귀하의 Lambda 함수를 호출합니다.

Lambda 함수를 클라우드에서 호출하려면
  1. 이전 단계의 함수의 LogicalResourceId을 기록해 두십시오. 그것은 HelloWorldFunction이어야 합니다.

  2. 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam remote invoke HelloWorldFunction --stack-name sam-app
  3. AWS SAM CLI는 클라우드에서 귀하의 함수를 호출하고 응답을 반환합니다. 다음은 출력의 예제입니다.

    $ sam remote invoke HelloWorldFunction --stack-name sam-app Invoking Lambda Function HelloWorldFunction START RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Version: $LATEST END RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 REPORT RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Duration: 6.62 ms Billed Duration: 7 ms Memory Size: 128 MB Max Memory Used: 67 MB Init Duration: 164.06 ms {"statusCode":200,"body":"{\"message\":\"hello world\"}"}%

6단계: 애플리케이션을 수정하고 AWS 클라우드에 동기화합니다.

이 단계에서는 AWS SAM CLI sam sync --watch 명령을 사용하여 로컬 변경 내용을 AWS 클라우드에 동기화합니다.

sam sync를 사용하려면
  1. 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam sync --watch
  2. AWS SAM CLI는 프롬프트를 통해 귀하가 개발 스택을 동기화하고 있는지 확인을 구합니다. 이 sam sync --watch 명령은 로컬 변경 내용을 실시간으로 AWS 클라우드에 자동 배포하므로 개발 환경에서만 사용하는 것이 좋습니다.

    AWS SAM CLI는 로컬 변경 모니터링을 시작하기 전에 초기 배포를 수행합니다. 다음은 출력의 예제입니다.

    $ sam sync --watch The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code without performing a CloudFormation deployment. This will cause drift in your CloudFormation stack. **The sync command should only be used against a development stack**. Confirm that you are synchronizing a development stack. Enter Y to proceed with the command, or enter N to cancel: [Y/n]: y Queued infra sync. Waiting for in progress code syncs to complete... Starting infra sync. Manifest is not changed for (HelloWorldFunction), running incremental build Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction Running PythonPipBuilder:CopySource Build Succeeded Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpq3x9vh63. Execute the following command to deploy the packaged template sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpq3x9vh63 --stack-name <YOUR STACK NAME> Deploying with following values =============================== Stack name : sam-app Region : us-west-2 Disable rollback : False Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-1a4x26zbcdkqr Capabilities : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"] Parameter overrides : {} Signing Profiles : null Initiating deployment ===================== 2023-03-15 13:10:05 - Waiting for stack create/update to complete CloudFormation events from stack operations (refresh every 0.5 seconds) --------------------------------------------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason --------------------------------------------------------------------------------------------------------------------------------------------- UPDATE_IN_PROGRESS AWS::CloudFormation::Stack sam-app Transformation succeeded CREATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedSt - ack CREATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedSt Resource creation Initiated ack CREATE_COMPLETE AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedSt - ack UPDATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction - UPDATE_COMPLETE AWS::Lambda::Function HelloWorldFunction - UPDATE_COMPLETE_CLEANUP_IN_PROGRE AWS::CloudFormation::Stack sam-app - SS UPDATE_COMPLETE AWS::CloudFormation::Stack sam-app - --------------------------------------------------------------------------------------------------------------------------------------------- CloudFormation outputs from deployed stack ---------------------------------------------------------------------------------------------------------------------------------------------- Outputs ---------------------------------------------------------------------------------------------------------------------------------------------- Key HelloWorldFunctionIamRole Description Implicit IAM Role created for Hello World function Value arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-15GLOUR9LMT1W Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-yQDNe17r9maD ---------------------------------------------------------------------------------------------------------------------------------------------- Stack update succeeded. Sync infra completed. Infra sync completed. CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi.

다음으로 귀하는 Lambda 함수 코드를 수정합니다. AWS SAM CLI는 이 변경 사항을 자동으로 감지하고 애플리케이션을 AWS 클라우드에 동기화합니다.

애플리케이션을 수정하고 동기화하려면
  1. 귀하가 선택한 IDE에서 sam-app/hello_world/app.py 파일을 엽니다.

  2. message을 변경하고 파일을 저장합니다. 다음은 그 예제입니다.

    import json ... def lambda_handler(event, context): ... return { "statusCode": 200, "body": json.dumps({ "message": "hello everyone!", ... }), }
  3. AWS SAM CLI는 귀하의 변경 사항을 감지하고 애플리케이션을 AWS 클라우드에 동기화합니다. 다음은 출력의 예제입니다.

    Syncing Lambda Function HelloWorldFunction...
    Manifest is not changed for (HelloWorldFunction), running incremental build
    Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
    Running PythonPipBuilder:CopySource
    Finished syncing Lambda Function HelloWorldFunction.
  4. 변경 사항을 확인하려면 API 엔드포인트에 GET 요청을 다시 보내십시오.

    $ curl https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/ {"message": "hello everyone!"}

7단계: (선택 사항) 로컬에서 애플리케이션 테스트

참고

이 단계는 Docker을 귀하의 로컬 기기에서 요구하므로 선택 사항입니다.

중요

AWS SAM CLI를 로컬 테스트에 사용하려면 귀하는 Docker을 설치하고 구성해야 합니다. 자세한 내용은 Docker 설치을 참조하십시오

이 단계에서는 AWS SAM CLI sam local 명령을 사용하여 애플리케이션을 로컬에서 테스트합니다. 이를 위해 AWS SAM CLI는 Docker를 사용하여 로컬 환경을 만듭니다. 이 로컬 환경은 Lambda 함수의 클라우드 기반 실행 환경을 에뮬레이션합니다.

귀하는 다음을 수행합니다.

  1. Lambda 함수를 위한 로컬 환경을 생성하고 이를 호출합니다.

  2. 로컬에서 HTTP API 엔드포인트를 호스팅하고 Lambda 함수를 호출하는 데 사용합니다.

Lambda 함수를 로컬에서 호출하려면
  1. 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam local invoke
  2. AWS SAM CLI는 로컬 Docker 컨테이너를 생성하고 귀하의 함수를 호출합니다. 다음은 출력의 예제입니다.

    $ sam local invoke Invoking app.lambda_handler (python3.9) Local image was not found. Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9 Building image..................... Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64. Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 Version: $LATEST END RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 REPORT RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 Init Duration: 1.01 ms Duration: 633.45 ms Billed Duration: 634 ms Memory Size: 128 MB Max Memory Used: 128 MB {"statusCode": 200, "body": "{\"message\": \"hello world\"}"}
API를 로컬에서 호스팅하려면
  1. 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam local start-api
  2. AWS SAMCLI는 Lambda 함수를 위한 로컬 Docker 컨테이너를 생성하고 API 엔드포인트를 시뮬레이션하기 위한 로컬 HTTP 서버를 생성합니다. 다음은 출력의 예제입니다.

    $ sam local start-api Initializing the lambda functions containers. Local image is up-to-date Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64. Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container Containers Initialization is done. 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. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template 2023-03-15 14:25:21 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:3000 2023-03-15 14:25:21 Press CTRL+C to quit
  3. 귀하의 브라우저 또는 명령줄을 사용하여 로컬 API 엔드포인트에 GET 요청을 보냅니다. 다음은 curl 명령을 사용한 예입니다.

    $ curl http://127.0.0.1:3000/hello {"message": "hello world"}

8단계: AWS 클라우드에서 애플리케이션 삭제

이 단계에서는 AWS SAM CLI sam delete 명령을 사용하여 AWS 클라우드에서 애플리케이션을 삭제합니다.

AWS 클라우드에서 귀하의 애플리케이션을 삭제하려면
  1. 명령줄에서 sam-app 프로젝트 디렉터리로부터 다음을 실행합니다.

    $ sam delete
  2. AWS SAM CLI는 확인을 요청할 것입니다. 그러면 애플리케이션의 Amazon S3 버킷과 AWS CloudFormation 스택이 삭제됩니다. 다음은 출력의 예제입니다.

    $ sam delete Are you sure you want to delete the stack sam-app in the region us-west-2 ? [y/N]: y Are you sure you want to delete the folder sam-app in S3 which contains the artifacts? [y/N]: y - Deleting S3 object with key c6ce8fa8b5a97dd022ecd006536eb5a4 - Deleting S3 object with key 5d513a459d062d644f3b7dd0c8b56a2a.template - Deleting S3 object with key sam-app/2bebf67c79f6a743cc5312f6dfc1efee.template - Deleting S3 object with key sam-app/6b208d0e42ad15d1cee77d967834784b.template - Deleting S3 object with key sam-app/da3c598813f1c2151579b73ad788cac8 - Deleting S3 object with key sam-app/f798cdd93cee188a71d120f14a035b11 - Deleting Cloudformation stack sam-app Deleted successfully

문제 해결

AWS SAM CLI 문제를 해결하려면 AWS SAMCLI 문제 해결 섹션을 참조하세요.

자세히 알아보기

AWS SAM에 대해 계속 알아보고자 한다면 다음 리소스를 잠조하세요.

  • 전체 AWS SAM 워크숍 – AWS SAM가 제공하는 여러 주요 기능을 설명하기 위해 마련된 워크숍입니다.

  • SAM과의 세션 – 당사의 AWS 서버리스 개발자 지원 팀이 제작한 AWS SAM의 사용에 관한 동영상 시리즈입니다.

  • 서버리스 랜드 – AWS 서버리스에 대한 최신 정보, 블로그, 동영상, 코드 및 학습 리소스를 한데 모아 놓은 사이트입니다.