sam build 사용하기 - AWS Serverless Application Model

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

sam build 사용하기

AWS Serverless Application Model Command Line Interface(AWS SAM CLI) sam build명령을 사용하여 로컬 테스트 또는 AWS 클라우드 배포와 같은 개발 워크플로의 후속 단계를 위해 서버리스 애플리케이션을 준비할 수 있습니다. 이 명령은 sam localsam deploy에서 요구하는 형식과 위치로 애플리케이션을 구성하는 .aws-sam 디렉터리를 만듭니다.

참고

sam build를 사용하려면 개발 시스템에 있는 서버리스 애플리케이션의 기본 구성 요소부터 시작해야 합니다. 여기에는 AWS SAM 템플릿, AWS Lambda 함수 코드, 모든 언어별 파일 및 종속성이 포함됩니다. 자세한 내용은 sam init 사용하기 섹션을 참조하세요.

sam build로 애플리케이션 빌드

sam build를 사용하기 전에 다음 사항을 고려하고 구성합니다.

  1. Lambda 함수 및 계층 - sam build 명령은 Lambda 함수 및 계층을 구축할 수 있습니다. Lambda 계층 사용에 대해 자세히 알아보려면 레이어 구축 섹션을 참조하세요.

  2. Lambda 런타임런타임은 간접적으로 호출될 때 실행 환경에서 함수를 실행하는 언어별 환경을 제공합니다. 네이티브 런타임과 사용자 지정 런타임을 구성할 수 있습니다.

    1. 네이티브 런타임 - 지원되는 Lambda 런타임에서 Lambda 함수를 작성하고 AWS 클라우드에서 네이티브 Lambda 런타임을 사용하도록 함수를 빌드합니다.

    2. 사용자 지정 런타임 - 모든 프로그래밍 언어를 사용하여 Lambda 함수를 작성하고, makefile 또는 esbuild와 같은 타사 빌더에 정의된 사용자 지정 프로세스를 사용하여 런타임을 빌드합니다. 자세한 내용은 사용자 지정 런타임 구축을 잠조하세요.

  3. Lambda 패키지 유형 - Lambda 함수는 다음과 같은 Lambda 배포 패키지 유형으로 패키징될 수 있습니다.

    1. .zip 파일 아카이브 – 애플리케이션 코드와 해당 종속 항목이 포함됩니다.

    2. 컨테이너 이미지 – 기본 운영 체제, 런타임, Lambda 익스텐션, 애플리케이션 코드 및 해당 종속 항목이 포함됩니다.

sam init를 사용하여 애플리케이션을 초기화할 때 이러한 애플리케이션 설정을 구성할 수 있습니다.

  • sam init를 사용하는 방법에 대한 자세한 내용은 sam init 사용하기 섹션을 참조하세요.

  • 애플리케이션에서 이러한 설정을 구성하는 방법에 대해 자세히 알아보려면 애플리케이션 구축 섹션을 참조하세요.

애플리케이션을 빌드하려면
  1. 프로젝트의 루트에 대한 cd. AWS SAM 템플릿과 같은 위치입니다.

    $ cd sam-app
  2. 다음을 실행합니다.

    sam-app $ sam build <arguments> <options>
    참고

    일반적으로 사용되는 옵션은 --use-container입니다. 자세한 내용은 제공된 컨테이너 내에 Lambda 함수 빌드을 잠조하세요.

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

    sam-app $ 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/.../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
  3. AWS SAM CLI는 .aws-sam 빌드 디렉터리를 생성합니다. 다음은 그 예제입니다.

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

애플리케이션 구성 방식에 따라 AWS SAM CLI은 다음을 수행합니다.

  1. .aws-sam/build 디렉터리에서 종속성을 다운로드, 설치 및 구성합니다.

  2. Lambda 코드를 준비합니다. 여기에는 코드 컴파일, 실행 가능한 바이너리 생성, 컨테이너 이미지 구축이 포함될 수 있습니다.

  3. 빌드 아티팩트를 .aws-sam 디렉터리에 복사합니다. 형식은 애플리케이션 패키지 유형에 따라 달라집니다.

    1. .zip 패키지 유형의 경우 로컬 테스트에 사용할 수 있도록 아티팩트가 아직 압축되지 않았습니다. AWS SAM CLI는 sam deploy를 사용할 때 애플리케이션을 압축합니다.

    2. 컨테이너 이미지 패키지 유형의 경우 컨테이너 이미지가 로컬에서 생성되고 .aws-sam/build.toml 파일에서 참조됩니다.

  4. AWS SAM 템플릿을 .aws-sam 디렉터리에 복사하고 필요한 경우 새 파일 경로로 수정합니다.

.aws-sam 디렉터리의 빌드 아티팩트를 구성하는 주요 구성 요소는 다음과 같습니다.

  • 빌드 디렉터리 - 서로 독립적으로 구성된 Lambda 함수 및 계층을 포함합니다. 그 결과 .aws-sam/build 디렉터리의 각 함수 또는 계층이 고유한 구조를 갖게 됩니다.

  • AWS SAM 템플릿 - 빌드 프로세스 중 변경 내용을 기반으로 업데이트된 값으로 수정되었습니다.

  • build.toml 파일 - AWS SAM CLI에서 사용하는 빌드 설정이 포함된 구성 파일입니다.

로컬 테스트 및 배포

sam local를 사용하여 로컬 테스트를 수행하거나 sam deploy를 사용하여 배포를 수행할 때 AWS SAM CLI는 다음을 수행합니다.

  1. 먼저 .aws-sam 디렉터리가 존재하는지, 해당 디렉터리에 AWS SAM 템플릿이 있는지 확인합니다. 이러한 조건이 충족되면 AWS SAM CLI는 이 디렉터리를 애플리케이션의 루트 디렉터리로 간주합니다.

  2. 이러한 조건이 충족되지 않는 경우 AWS SAM CLI는 AWS SAM 템플릿의 원래 위치를 애플리케이션의 루트 디렉터리로 간주합니다.

개발할 때 원본 애플리케이션 파일이 변경되면 로컬에서 테스트하기 전에 sam build를 실행하여 .aws-sam 디렉터리를 업데이트합니다.

모범 사례

  • .aws-sam/build 디렉터리 아래의 코드는 수정하지 않습니다. 대신 프로젝트 폴더의 원본 소스 코드를 업데이트하고 sam build를 실행하여 .aws-sam/build 디렉터리를 업데이트합니다.

  • 원본 파일을 수정할 때는 sam build를 실행하여 .aws-sam/build 디렉터리를 업데이트합니다.

  • sam local을 개발하고 테스트할 때와 같이 AWS SAM CLI가 .aws-sam 디렉터리 대신 프로젝트의 원래 루트 디렉터리를 참조하도록 할 수도 있습니다. .aws-sam 디렉터리나 .aws-sam 디렉터리의 AWS SAM 템플릿을 삭제하여 AWS SAM CLI가 원래 프로젝트 디렉터리를 루트 프로젝트 디렉터리로 인식하도록 합니다. 준비가 되면 sam build를 다시 실행하여 .aws-sam 디렉터리를 생성합니다.

  • sam build를 실행하면 매번 .aws-sam/build 디렉터리를 덮어쓰게 됩니다. .aws-sam 디렉터리는 그렇지 않습니다. 로그와 같은 파일을 저장하려면 파일을 덮어쓰지 않도록 .aws-sam에 저장하세요.

sam build 옵션

단일 리소스 빌드

해당 리소스만 빌드하려면 리소스의 논리적 ID를 제공합니다. 다음은 그 예제입니다.

$ sam build HelloWorldFunction

중첩된 애플리케이션 또는 스택의 리소스를 구축하려면 다음 형식 <stack-logical-id>/<resource-logical-id>을 사용하여 애플리케이션 또는 스택 논리 ID를 리소스 논리 ID와 함께 제공하세요.

$ sam build MyNestedStack/MyFunction

제공된 컨테이너 내에 Lambda 함수 빌드

--use-container 옵션은 컨테이너 이미지를 다운로드하고 이를 사용하여 Lambda 함수를 빌드합니다. 그러면 로컬 컨테이너가 .aws-sam/build.toml 파일에서 참조됩니다.

이 옵션은 Docker가 설치되어 있어야 합니다. 지침은 Docker 설치 섹션을 참조하세요.

다음은 그러한 명령의 예입니다.

$ sam build --use-container

--build-image 옵션과 함께 사용할 컨테이너 이미지를 지정할 수 있습니다. 다음은 그 예제입니다.

$ sam build --use-container --build-image amazon/aws-sam-cli-build-image-nodejs12.x

단일 함수에 사용할 컨테이너 이미지를 지정하려면 함수 논리적 ID를 제공합니다. 다음은 그 예제입니다.

$ sam build --use-container --build-image Function1=amazon/aws-sam-cli-build-image-python3.8

컨테이너로 전달할 환경 변수입니다.

빌드 컨테이너로 환경 변수를 전달하기 위해 --container-env-var를 사용합니다. 다음은 그 예제입니다.

$ sam build --use-container --container-env-var Function1.GITHUB_TOKEN=<token1> --container-env-var GLOBAL_ENV_VAR=<global-token>

파일에서 환경 변수를 전달하려면 --container-env-var-file 옵션을 사용합니다. 다음은 그 예제입니다.

$ sam build --use-container --container-env-var-file <env.json>

env.json 파일의 예:

{ "MyFunction1": { "GITHUB_TOKEN": "TOKEN1" }, "MyFunction2": { "GITHUB_TOKEN": "TOKEN2" } }

여러 함수를 포함하는 애플리케이션을 빠르게 빌드할 수 있습니다.

여러 함수가 있는 애플리케이션에서 sam build를 실행하는 경우 AWS SAM CLI는 각 함수를 한 번에 하나씩 빌드합니다. 빌드 프로세스의 속도를 높이려면 --parallel 옵션을 사용하세요. 이 옵션을 사용하면 모든 함수와 계층이 동시에 빌드됩니다.

다음은 그러한 명령의 예입니다.

$ sam build —-parallel

소스 폴더에서 프로젝트를 빌드하여 빌드 시간 단축

지원되는 런타임과 빌드 메서드의 경우 --build-in-source 옵션을 사용하여 소스 폴더에서 직접 프로젝트를 빌드할 수 있습니다. 기본적으로 AWS SAM CLI는 임시 디렉터리에 빌드하며, 여기에는 소스 코드와 프로젝트 파일을 복사하는 작업이 수반됩니다. --build-in-source를 사용하면 AWS SAM CLI가 소스 폴더에서 직접 빌드하므로 파일을 임시 디렉터리에 복사할 필요가 없어 빌드 프로세스 속도가 빨라집니다.

지원되는 런타임 및 빌드 메서드 목록은 --build-in-source를 참조하세요.

문제 해결

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

예제

네이티브 런타임과.zip 패키지 유형을 사용하는 애플리케이션 빌드

이 예에서는 사용 지침서: Hello World 애플리케이션 배포 섹션을 참조하세요.

네이티브 런타임과 이미지 패키지 유형을 사용하는 애플리케이션 구축

먼저 sam init를 실행하여 새 애플리케이션을 초기화합니다. 대화형 흐름 중에 Image 패키지 유형을 선택합니다. 다음은 그 예제입니다.

$ 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]: ENTER Which runtime would you like to use? ... 11 - java8 12 - nodejs18.x 13 - nodejs16.x 14 - nodejs14.x ... Runtime: 12 What package type would you like to use? 1 - Zip 2 - Image Package type: 2 Based on your selections, the only dependency manager available is npm. We will proceed copying the template using npm. 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 Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment) ----------------------- Generating application: ----------------------- Name: sam-app Base Image: amazon/nodejs18.x-base Architectures: x86_64 Dependency Manager: npm Output Directory: . Configuration file: sam-app/samconfig.toml Next steps can be found in the README file at sam-app/README.md ...

AWS SAM CLI는 애플리케이션을 초기화하고 다음 프로젝트 디렉터리를 만듭니다.

sam-app
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── Dockerfile
│   ├── app.mjs
│   ├── package.json
│   └── tests
│       └── unit
│           └── test-handler.mjs
├── samconfig.toml
└── template.yaml

다음으로 애플리케이션을 빌드하기 위해 sam build를 실행합니다.

sam-app $ sam build Building codeuri: /Users/.../build-demo/sam-app runtime: None metadata: {'DockerTag': 'nodejs18.x-v1', 'DockerContext': '/Users/.../build-demo/sam-app/hello-world', 'Dockerfile': 'Dockerfile'} architecture: arm64 functions: HelloWorldFunction Building image for HelloWorldFunction function Setting DockerBuildArgs: {} for HelloWorldFunction function Step 1/4 : FROM public.ecr.aws/lambda/nodejs:18 ---> f5b68038c080 Step 2/4 : COPY app.mjs package*.json ./ ---> Using cache ---> 834e565aae80 Step 3/4 : RUN npm install ---> Using cache ---> 31c2209dd7b5 Step 4/4 : CMD ["app.lambdaHandler"] ---> Using cache ---> 2ce2a438e89d Successfully built 2ce2a438e89d Successfully tagged helloworldfunction:nodejs18.x-v1 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

컴파일된 프로그래밍 언어를 포함하는 애플리케이션 빌드

이 예제에서는 Go 런타임을 사용하여 Lambda 함수를 포함하는 애플리케이션을 빌드합니다.

먼저 sam init를 사용하여 새 애플리케이션을 초기화하고 Go를 사용하도록 애플리케이션을 구성합니다.

$ 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 ... Template: 1 Use the most popular runtime and package type? (Python and zip) [y/N]: ENTER Which runtime would you like to use? ... 4 - dotnetcore3.1 5 - go1.x 6 - go (provided.al2) ... Runtime: 5 What package type would you like to use? 1 - Zip 2 - Image Package type: 1 Based on your selections, the only dependency manager available is mod. We will proceed copying the template using mod. 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 Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment) ----------------------- Generating application: ----------------------- Name: sam-app Runtime: go1.x Architectures: x86_64 Dependency Manager: mod Application Template: hello-world Output Directory: . Configuration file: sam-app/samconfig.toml Next steps can be found in the README file at sam-app-go/README.md ...

AWS SAM CLI는 애플리케이션을 초기화합니다. 다음은 애플리케이션 디렉터리 구조의 예제입니다.

sam-app
├── Makefile
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── go.mod
│   ├── go.sum
│   ├── main.go
│   └── main_test.go
├── samconfig.toml
└── template.yaml

이 애플리케이션의 요구 사항은 README.md 파일을 참조합니다.

...
## Requirements
* AWS CLI already configured with Administrator permission
* [Docker installed](https://www.docker.com/community-edition)
* [Golang](https://golang.org)
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
...

다음으로 함수를 테스트하기 위해 sam local invoke를 실행합니다. 이 명령은 Go가 로컬 컴퓨터에 설치되지 않았으므로 오류가 발생합니다.

sam-app $ sam local invoke Invoking hello-world (go1.x) Local image was not found. Removing rapid images for repo public.ecr.aws/sam/emulation-go1.x Building image................................................................................................................................................................................................................................................. Using local image: public.ecr.aws/lambda/go:1-rapid-x86_64. Mounting /Users/.../Playground/build/sam-app/hello-world as /var/task:ro,delegated inside runtime container START RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31 Version: $LATEST fork/exec /var/task/hello-world: no such file or directory: PathError null END RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31 REPORT RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31 Init Duration: 0.88 ms Duration: 175.75 ms Billed Duration: 176 ms Memory Size: 128 MB Max Memory Used: 128 MB {"errorMessage":"fork/exec /var/task/hello-world: no such file or directory","errorType":"PathError"}%

다음으로 애플리케이션을 빌드하기 위해 sam build를 실행합니다. 로컬 컴퓨터에 Go가 설치되지 않아 오류가 발생했습니다.

sam-app $ sam build Starting Build use cache Cache is invalid, running build and copying resources for following functions (HelloWorldFunction) Building codeuri: /Users/.../Playground/build/sam-app/hello-world runtime: go1.x metadata: {} architecture: x86_64 functions: HelloWorldFunction Build Failed Error: GoModulesBuilder:Resolver - Path resolution for runtime: go1.x of binary: go was not successful

함수를 제대로 빌드하도록 로컬 시스템을 구성할 수도 있지만, 대신 --use-container 옵션에 sam build를 사용합니다. 는 컨테이너 이미지를 AWS SAM CLI 다운로드하고 GoModulesBuilder 네이티브를 사용하여 함수를 빌드한 다음 결과 .aws-sam/build/HelloWorldFunction 바이너리를 디렉터리에 복사합니다.

sam-app $ sam build --use-container Starting Build use cache Starting Build inside a container Cache is invalid, running build and copying resources for following functions (HelloWorldFunction) Building codeuri: /Users/.../build/sam-app/hello-world runtime: go1.x metadata: {} architecture: x86_64 functions: HelloWorldFunction Fetching public.ecr.aws/sam/build-go1.x:latest-x86_64 Docker container image..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... Mounting /Users/.../build/sam-app/hello-world as /tmp/samcli/source:ro,delegated inside runtime container Running GoModulesBuilder:Build 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 파일의 예입니다.

.aws-sam
├── build
│   ├── HelloWorldFunction
│   │   └── hello-world
│   └── template.yaml
├── build.toml
├── cache
│   └── c860d011-4147-4010-addb-2eaa289f4d95
│       └── hello-world
└── deps

다음으로 sam local invoke를 실행합니다. 함수가 성공적으로 호출되었습니다.

sam-app $ sam local invoke Invoking hello-world (go1.x) Local image is up-to-date Using local image: public.ecr.aws/lambda/go:1-rapid-x86_64. Mounting /Users/.../Playground/build/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479 Version: $LATEST END RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479 REPORT RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479 Init Duration: 1.20 ms Duration: 1782.46 ms Billed Duration: 1783 ms Memory Size: 128 MB Max Memory Used: 128 MB {"statusCode":200,"headers":null,"multiValueHeaders":null,"body":"Hello, 72.21.198.67\n"}%

자세히 알아보기

sam build 명령 사용에 대한 자세한 내용은 다음을 참조하세요.