

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

# 를 사용하여 애플리케이션 빌드 AWS SAM
<a name="serverless-building"></a>

 AWS SAM 템플릿에 코드형 인프라(IaC)를 추가하면 **sam build** 명령을 사용하여 애플리케이션 빌드를 시작할 준비가 됩니다. 이 명령은 애플리케이션 프로젝트 디렉터리의 파일(즉, AWS SAM 템플릿 파일, 애플리케이션 코드, 적용 가능한 언어별 파일 및 종속성)에서 빌드 아티팩트를 생성합니다. 이러한 빌드 아티팩트는 로컬 테스트 및 AWS 클라우드에 배포와 같은 애플리케이션 개발의 이후 단계를 위해 서버리스 애플리케이션을 준비합니다. 테스트와 배포 모두 빌드 아티팩트를 입력으로 사용합니다.

**sam build**를 사용하여 전체 서버리스 애플리케이션을 빌드할 수 있습니다. 또한 특정 함수, 계층 또는 사용자 지정 런타임이 있는 빌드와 같은 사용자 지정 빌드를 생성할 수 있습니다. **sam build**를 사용하는 방법과 이유에 대해 자세히 알아보려면 이 섹션의 주제를 참조하세요. `sam build` 명령 사용에 대한 소개는 [를 사용한 빌드 소개 AWS SAM](using-sam-cli-build.md) 단원을 참조하세요.

**Topics**
+ [를 사용한 빌드 소개 AWS SAM](using-sam-cli-build.md)
+ [를 사용한 기본 빌드 AWS SAM](serverless-sam-cli-using-build.md)
+ [를 사용하여 빌드 사용자 지정 AWS SAM](building-lambda-functions.md)

# 를 사용한 빌드 소개 AWS SAM
<a name="using-sam-cli-build"></a>

 AWS Serverless Application Model 명령줄 인터페이스(AWS SAM CLI) `sam build` 명령을 사용하여 로컬 테스트 또는에 배포와 같은 개발 워크플로의 후속 단계를 위해 서버리스 애플리케이션을 준비합니다 AWS 클라우드. 이 명령은 `sam local`과 `sam deploy`에서 요구하는 형식과 위치로 애플리케이션을 구성하는 `.aws-sam` 디렉터리를 만듭니다.
+ 에 대한 소개는 단원을 AWS SAM CLI참조하십시오[란 무엇입니까 AWS SAM CLI?](what-is-sam-overview.md#what-is-sam-cli).
+ `sam build` 명령 옵션 목록은 [sam build](sam-cli-command-reference-sam-build.md) 섹션을 참조하세요.
+ 일반적인 개발 워크플로 중 `sam build`를 사용하는 예는 [2단계: 귀하의 애플리케이션 빌드](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-build) 섹션을 참조하세요.

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

**Topics**
+ [sam build로 애플리케이션 빌드](#using-sam-cli-build-apps)
+ [로컬 테스트 및 배포](#using-sam-cli-build-test-deploy)
+ [모범 사례](#using-sam-cli-build-best)
+ [sam build 옵션](#using-sam-cli-build-options)
+ [문제 해결](#using-sam-cli-build-troubleshooting)
+ [예제](#using-sam-cli-build-examples)
+ [자세히 알아보기](#using-sam-cli-build-learn)

## sam build로 애플리케이션 빌드
<a name="using-sam-cli-build-apps"></a>

`sam build`를 사용하기 전에 다음을 구성하는 것이 좋습니다.

1. **Lambda 함수 및 계층** - `sam build` 명령은 Lambda 함수 및 계층을 구축할 수 있습니다. Lambda 계층 사용에 대해 자세히 알아보려면 [에서 Lambda 계층 빌드 AWS SAM](building-layers.md) 섹션을 참조하세요.

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

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

   1. **사용자 지정 런타임** - 모든 프로그래밍 언어를 사용하여 Lambda 함수를 작성하고, makefile 또는 esbuild와 같은 타사 빌더에 정의된 사용자 지정 프로세스를 사용하여 런타임을 빌드합니다. 자세한 내용은 [에서 사용자 지정 런타임을 사용하여 Lambda 함수 빌드 AWS SAM](building-custom-runtimes.md)를 참조하세요.

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

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

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

`sam init`를 사용하여 애플리케이션을 초기화할 때 이러한 애플리케이션 설정을 구성할 수 있습니다.
+ `sam init`를 사용하는 방법에 대한 자세한 내용은 [에서 애플리케이션 생성 AWS SAM](using-sam-cli-init.md) 섹션을 참조하세요.
+ 애플리케이션에서 이러한 설정을 구성하는 방법에 대해 자세히 알아보려면 [를 사용한 기본 빌드 AWS SAM](serverless-sam-cli-using-build.md) 섹션을 참조하세요.

**애플리케이션을 빌드하려면**

1. 프로젝트의 루트에 대한 `cd`. 템플릿과 동일한 위치입니다 AWS SAM .

   ```
   $ cd sam-app
   ```

1. 다음을 실행합니다.

   ```
   sam-app $ sam build <arguments> <options>
   ```
**참고**  
일반적으로 사용되는 옵션은 `--use-container`입니다. 자세한 내용은 [제공된 컨테이너 내에 Lambda 함수 빌드](#using-sam-cli-build-options-container)를 참조하세요.

   다음은 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.12 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
   ```

1.  AWS SAMCLI는 `.aws-sam` 빌드 디렉터리를 생성합니다. 다음은 예제입니다.

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

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

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

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

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

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

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

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

`.aws-sam` 디렉터리의 빌드 아티팩트를 구성하는 주요 구성 요소는 다음과 같습니다.
+ **빌드 디렉터리** - 서로 독립적으로 구성된 Lambda 함수 및 계층을 포함합니다. 그 결과 `.aws-sam/build` 디렉터리의 각 함수 또는 계층이 고유한 구조를 갖게 됩니다.
+ ** AWS SAM 템플릿 **- 빌드 프로세스 중 변경 사항에 따라 업데이트된 값으로 수정되었습니다.
+ **build.toml 파일 **-에서 사용하는 빌드 설정이 포함된 구성 파일입니다 AWS SAM CLI.

## 로컬 테스트 및 배포
<a name="using-sam-cli-build-test-deploy"></a>

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

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

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

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

## 모범 사례
<a name="using-sam-cli-build-best"></a>
+ `.aws-sam/build` 디렉터리 아래의 코드는 수정하지 않습니다. 대신 프로젝트 폴더의 원본 소스 코드를 업데이트하고 `sam build`를 실행하여 `.aws-sam/build` 디렉터리를 업데이트합니다.
+ 원본 파일을 수정할 때는 `sam build`를 실행하여 `.aws-sam/build` 디렉터리를 업데이트합니다.
+ `sam local`을 개발하고 테스트할 때와 같이 AWS SAMCLI가 `.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 옵션
<a name="using-sam-cli-build-options"></a>

### 단일 리소스 빌드
<a name="using-sam-cli-build-options-resource"></a>

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

```
$ sam build HelloWorldFunction
```

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

```
$ sam build MyNestedStack/MyFunction
```

### 제공된 컨테이너 내에 Lambda 함수 빌드
<a name="using-sam-cli-build-options-container"></a>

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

이 옵션은 Docker가 설치되어 있어야 합니다. 지침은 [Docker 설치](install-docker.md) 섹션을 참조하세요.

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

```
$ sam build --use-container
```

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

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

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

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

### 컨테이너로 전달할 환경 변수입니다.
<a name="using-sam-cli-build-options-env"></a>

빌드 컨테이너로 환경 변수를 전달하기 위해 `--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"
  }
}
```

### 여러 함수를 포함하는 애플리케이션을 빠르게 빌드할 수 있습니다.
<a name="using-sam-cli-build-options-speed"></a>

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

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

```
$ sam build —-parallel
```

### 소스 폴더에서 프로젝트를 빌드하여 빌드 시간 단축
<a name="using-sam-cli-build-options-source"></a>

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

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

## 문제 해결
<a name="using-sam-cli-build-troubleshooting"></a>

문제를 해결하려면 섹션을 AWS SAM CLI참조하세요[AWS SAMCLI 문제 해결](sam-cli-troubleshooting.md).

## 예제
<a name="using-sam-cli-build-examples"></a>

### 네이티브 런타임과.zip 패키지 유형을 사용하는 애플리케이션 빌드
<a name="using-sam-cli-build-examples-tutorial1"></a>

이 예에서는 [자습서:를 사용하여 Hello World 애플리케이션 배포 AWS SAM](serverless-getting-started-hello-world.md) 섹션을 참조하세요.

### 네이티브 런타임과 이미지 패키지 유형을 사용하는 애플리케이션 구축
<a name="using-sam-cli-build-examples-image"></a>

먼저 `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?
        ...
        10 - java8
        11 - nodejs20.x
        12 - nodejs18.x
        13 - nodejs16.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
```

### 컴파일된 프로그래밍 언어를 포함하는 애플리케이션 빌드
<a name="using-sam-cli-build-examples-compiled"></a>

이 예제에서는 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"}%
```

## 자세히 알아보기
<a name="using-sam-cli-build-learn"></a>

`sam build` 명령 사용에 대한 자세한 내용은 다음을 참조하세요.
+ **[학습 AWS SAM: sam build](https://www.youtube.com/watch?v=fDhYKp4op_g)** –의 서버리스 랜드 "학습 AWS SAM" 시리즈YouTube.
+ **[학습 AWS SAM \$1 sam build \$1 E3 ](https://www.youtube.com/watch?v=vsAvRyLnB7Y)** –의 서버리스 랜드 "학습 AWS SAM" 시리즈YouTube.
+ **[AWS SAM build: 배포를 위한 아티팩트를 제공하는 방법(SAM S2E8을 사용한 세션)](https://www.youtube.com/watch?v=bNbBd6XoDHg)** -에 AWS SAM 시리즈가 있는 세션YouTube.
+ **[AWS SAM 사용자 지정 빌드: Makefiles를 사용하여 SAM(S2E9)의 빌드를 사용자 지정하는 방법](https://www.youtube.com/watch?v=wpccutnSbAk)** -의 AWS SAM 시리즈가 있는 세션YouTube.

# 를 사용한 기본 빌드 AWS SAM
<a name="serverless-sam-cli-using-build"></a>

서버리스 애플리케이션을 구축하려면 `sam build` 명령을 사용합니다. 또한 이 명령은 애플리케이션 종속성의 구축 아티팩트를 수집하여 로컬 테스트, 패키징, 배포와 같은 다음 단계를 위해 적절한 형식과 위치에 배치합니다.

`requirements.txt`(Python) 또는 `package.json`(Node.js) 같은 매니페스트 파일에서 또는 함수 리소스의 `Layers` 속성을 사용하여 애플리케이션의 종속성을 지정합니다. `Layers` 속성에는 Lambda 함수가 의존하는 [AWS Lambda 계층](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) 리소스 목록이 포함되어 있습니다.

애플리케이션 구축 아티팩트의 형식은 각 함수의 `PackageType` 속성에 따라 달라집니다. 이 속성의 옵션은 다음과 같습니다.
+ **`Zip`** – 애플리케이션 코드와 그 종속 항목을 포함하는 .zip 파일 아카이브입니다. 코드를 .zip 파일 아카이브로 패키징하는 경우 함수의 Lambda 런타임을 지정해야 합니다.
+ **`Image`** - 애플리케이션 코드 및 그 종속 항목에 추가하여 기본 운영 체제, 런타임, 익스텐션 등을 포함하는 컨테이너 이미지입니다.

Lambda 패키지 유형에 대한 자세한 내용은 [개발자 가이드](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html)의 *AWS Lambda Lambda 배포 패키지*를 참조하세요.

**Topics**
+ [.zip 파일 아카이브 만들기](#build-zip-archive)
+ [컨테이너 이미지 구축](#build-container-image)
+ [컨테이너 환경 변수 파일](#serverless-sam-cli-using-container-environment-file)
+ [소스 폴더에서 프로젝트를 빌드하여 빌드 시간 단축](#serverless-sam-cli-using-build-in-source)
+ [예제](#building-applications-examples)
+ [외부에서 함수 빌드 AWS SAM](#building-applications-skip)

## .zip 파일 아카이브 만들기
<a name="build-zip-archive"></a>

서버리스 애플리케이션을 .zip 파일 아카이브로 구축하려면 서버리스 함수에 대해 `PackageType: Zip`을 선언합니다.

AWS SAM 는 지정한 [아키텍처](sam-resource-function.md#sam-function-architectures)에 대한 애플리케이션을 빌드합니다. 아키텍처를 지정하지 않으면 `x86_64` 기본적으로를 AWS SAM 사용합니다.

Lambda 함수가 기본적으로 컴파일된 프로그램이 있는 패키지에 의존하는 경우 `--use-container` 플래그를 사용하십시오. 이 플래그는 Lambda 환경처럼 작동하는 컨테이너에서 함수를 로컬로 컴파일하므로 AWS 클라우드에 배포할 때 올바른 형식입니다.

`--use-container` 옵션을 사용하면는 기본적으로 [Amazon ECR Public](https://docs.aws.amazon.com/AmazonECR/latest/public/what-is-ecr.html)에서 컨테이너 이미지를 AWS SAM 가져옵니다. 다른 리포지토리 또는 특정 버전의 AWS SAM CLI에 대해 컨테이너 이미지를 가져오려면 `--build-image` 옵션을 사용하고 대체 컨테이너 이미지의 URI를 제공할 수 있습니다. 다음은 특정 AWS SAM CLI 버전의 컨테이너 이미지를 사용하여 애플리케이션을 빌드하기 위한 두 가지 예제 명령입니다.

```
# Build a Node.js 20 application using a container image for a specific version of AWS SAM CLI (1.136.0)
sam build --use-container --build-image public.ecr.aws/sam/build-nodejs22.x:1.136.0

# Build a function resource using the Python 3.13 container image from a specific version of AWS SAM CLI (1.136.0)(
sam build --use-container --build-image Function1=public.ecr.aws/sam/build-python3.13:1.136.0
```

.zip 파일 아카이브 애플리케이션을 구축하는 추가 예제는 이 주제 뒷부분의 예제 섹션을 참조하세요.

## 컨테이너 이미지 구축
<a name="build-container-image"></a>

서버리스 애플리케이션을 컨테이너 이미지로 구축하려면 서버리스 함수에 대해 `PackageType: Image`을 선언하십시오. 또한 다음 항목들을 사용하여 `Metadata` 리소스 속성을 선언해야 합니다.

`Dockerfile`  
Lambda 함수와 연결되는 Dockerfile의 이름입니다.

`DockerContext`  
Dockerfile의 위치입니다.

`DockerTag`  
(선택 사항) 구축된 이미지에 적용할 태그.

`DockerBuildArgs`  
구축에 대한 구축 인수입니다.  
 AWS SAMCLI는 `DockerBuildArgs` 인수에 포함된 정보를 삭제하거나 난독화하지 않습니다. 이 섹션을 사용하여 암호나 보안 암호와 같은 민감한 정보를 저장하지 않는 것이 좋습니다.

다음은 예제 `Metadata` 리소스 속성 섹션입니다.

```
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: v1
```

`Image` 패키지 유형으로 구성된 샘플 애플리케이션을 다운로드하려면 [자습서:를 사용하여 Hello World 애플리케이션 배포 AWS SAM](serverless-getting-started-hello-world.md) 섹션을 참조하세요. 설치할 패키지 유형을 묻는 메시지가 나타나면 `Image`을 선택합니다.

**참고**  
Dockerfile에서 다중 아키텍처 기본 이미지를 지정하는 경우는 호스트 시스템의 아키텍처에 맞게 컨테이너 이미지를 AWS SAM 빌드합니다. 다른 아키텍처용으로 구축하려면 특정 대상 아키텍처를 사용하는 기본 이미지를 지정하십시오.

## 컨테이너 환경 변수 파일
<a name="serverless-sam-cli-using-container-environment-file"></a>

구축 컨테이너의 환경 변수가 포함된 JSON 파일을 제공하려면 `--container-env-var-file` 인수를 `sam build` 명령과 함께 사용하십시오. 모든 서버리스 리소스에 적용되는 단일 환경 변수를 제공하거나 각 리소스에 대해 서로 다른 환경 변수를 제공할 수 있습니다.

### 형식
<a name="serverless-sam-cli-using-container-environment-file-format"></a>

구축 컨테이너에 환경 변수를 전달하는 형식은 리소스에 제공하는 환경 변수의 개수에 따라 달라집니다.

모든 리소스에 단일 환경 변수를 제공하려면 다음과 같이 `Parameters` 객체를 지정하십시오.

```
{
  "Parameters": {
    "GITHUB_TOKEN": "TOKEN_GLOBAL"
  }
}
```

각 리소스에 서로 다른 환경 변수를 제공하려면 다음과 같이 각 리소스의 객체를 지정하십시오.

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

환경 변수를 파일로(예를 들면 `env.json`이라는 이름으로) 저장합니다. 다음 명령은 이 파일을 사용하여 환경 변수를 구축 컨테이너에 전달합니다.

```
sam build --use-container --container-env-var-file env.json
```

### 우선 순위
<a name="serverless-sam-cli-using-container-environment-file-precedence"></a>
+ 특정 리소스에 귀하가 제공하는 환경 변수는 모든 리소스의 단일 환경 변수보다 우선합니다.
+ 명령 행에 제공하는 환경 변수는 한 파일 내 환경 변수보다 우선합니다.

## 소스 폴더에서 프로젝트를 빌드하여 빌드 시간 단축
<a name="serverless-sam-cli-using-build-in-source"></a>

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

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

## 예제
<a name="building-applications-examples"></a>

### 예제 1: .zip 파일 아카이브
<a name="examples-zip-archives"></a>

다음 `sam build` 명령은.zip 파일 아카이브를 구축합니다.

```
# Build all functions and layers, and their dependencies
sam build

# Run the build process inside a Docker container that functions like a Lambda environment
sam build --use-container

# Build a Node.js 20 application using a container image for a specific version of AWS SAM CLI (1.136.0)
sam build --use-container --build-image public.ecr.aws/sam/build-nodejs22.x:1.136.0

# Build a function resource using the Python 3.13 container image from a specific version of AWS SAM CLI (1.136.0)(
sam build --use-container --build-image Function1=public.ecr.aws/sam/build-python3.13:1.136.0

# Build and run your functions locally
sam build && sam local invoke

# For more options
sam build --help
```

### 예제 2: 컨테이너 이미지
<a name="examples-container-image-1"></a>

다음 AWS SAM 템플릿은 컨테이너 이미지로 빌드됩니다.

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: ["app.lambda_handler"]
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: v1
```

다음은 Dockfile 파일의 예입니다.

```
FROM public.ecr.aws/lambda/python:3.12

COPY app.py requirements.txt ./

RUN python3.12 -m pip install -r requirements.txt

# Overwrite the command by providing a different command directly in the template.
CMD ["app.lambda_handler"]
```

### 예제 3: npm ci
<a name="examples-npm-ci"></a>

Node.js 애플리케이션의 경우 종속물을 설치하기 위하여 `npm ci`대신 `npm install`를 사용할 수 있습니다. `npm ci`을 사용하려면 Lambda 함수의 `UseNpmCi: True` 리소스 속성 내 `BuildProperties` 이하에 `Metadata`를 지정하십시오. `npm ci`을 사용하려면 애플리케이션에 귀하의 Lambda 함수용 `package-lock.json`에 존재하는 `npm-shrinkwrap.json` 또는 `CodeUri` 파일이 있어야 합니다.

다음 예제는 `npm ci`의 실행 시 종속 항목을 설치하기 위해 `sam build`를 사용합니다.

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.handler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
    Metadata:
      BuildProperties:
        UseNpmCi: True
```

### Python 상위 패키지
<a name="building-applications-python-parent-packages"></a>

Python 애플리케이션의 경우, 빌드 프로세스 중에 패키지 구조를 보존하여 절대 임포트를 활성화할 수 있습니다. 패키지 구조를 보존하려면, Lambda 함수의 `Metadata` 리소스 속성에서 `BuildProperties` 아래에 `ParentPackageMode`을(를) 지정하세요.

다음 예시는 `sam build`을(를) 실행할 때 `app` 패키지 구조를 보존합니다.

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.main.handler
      Runtime: python3.12
      Architectures:
        - x86_64
    Metadata:
      BuildProperties:
        ParentPackageMode: explicit
        ParentPackages: app
```

이 구성을 사용하면, 코드가 `from .utils import logger`와(과) 같은 상대 임포트 대신 `from app.utils import logger`와(과) 같은 절대 임포트를 사용할 수 있습니다.

## 외부에서 함수 빌드 AWS SAM
<a name="building-applications-skip"></a>

기본적으로를 실행하면가 모든 함수 리소스를 **sam build** AWS SAM 빌드합니다. 그 밖에도 다음과 같은 옵션이 있습니다.
+ **외부의 모든 함수 리소스 빌드 AWS SAM** - 모든 함수 리소스를 수동으로 또는 다른 도구를 통해 빌드하는 경우 **sam build**는 필요하지 않습니다. **sam build**을 건너뛰고 로컬 테스트 수행 또는 애플리케이션 배포와 같은 프로세스의 다음 단계로 이동할 수 있습니다.
+ **외부에서 일부 함수 리소스 빌드 AWS SAM** - 외부에서 다른 함수 리소스를 빌드하는 동안 일부 함수 리소스를 빌드 AWS SAM 하려면 AWS SAM 템플릿에서 이를 지정할 AWS SAM수 있습니다.

### 외부에서 일부 함수 리소스 빌드 AWS SAM
<a name="building-applications-skip-some"></a>

를 사용할 때 함수를 AWS SAM 건너뛰려면 AWS SAM 템플릿에서 다음을 **sam build**구성합니다.

1. 함수에 `SkipBuild: True` 메타데이터 속성을 추가합니다.

1. 구축된 함수 리소스의 경로를 지정합니다.

다음은 `TestFunction`을 건너뛰도록 구성한 예제입니다. 구축된 리소스는 `built-resources/TestFunction.zip`에 있습니다.

```
TestFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: built-resources/TestFunction.zip
    Handler: TimeHandler::handleRequest
    Runtime: java11
  Metadata:
    SkipBuild: True
```

이제를 실행하면 **sam build** AWS SAM 가 다음을 수행합니다.

1. AWS SAM 는 로 구성된 함수를 건너뜁니다`SkipBuild: True`.

1. AWS SAM 는 다른 모든 함수 리소스를 빌드하고 `.aws-sam` 빌드 디렉터리에 캐시합니다.

1. 건너뛰는 함수의 경우 `.aws-sam` 구축 디렉터리 내 이들의 템플릿이 구축된 함수 리소스의 지정된 경로를 참조하도록 자동으로 업데이트됩니다.

   다음은 `TestFunction` 구축 디렉터리에 있는 `.aws-sam`를 위한 캐시된 템플릿의 예입니다.

   ```
   TestFunction:
     Type: AWS::Serverless::Function
     Properties:
       CodeUri: ../../built-resources/TestFunction.zip
       Handler: TimeHandler::handleRequest
       Runtime: java11
     Metadata:
       SkipBuild: True
   ```

# 를 사용하여 빌드 사용자 지정 AWS SAM
<a name="building-lambda-functions"></a>

특정 Lambda 함수 또는 Lambda 계층을 포함하도록 빌드를 사용자 지정할 수 있습니다. 함수는 Lambda에서 코드를 실행하기 위해 간접 호출할 수 있는 리소스입니다. Lambda 계층을 사용하면 Lambda 함수에서 코드를 추출한 다음 여러 Lambda 함수에서 재사용할 수 있습니다. 공유 종속성 또는 리소스를 관리하는 복잡성 없이 개별 서버리스 함수를 개발하고 배포하는 데 집중하려는 경우 특정 Lambda 함수에 맞게 빌드를 사용자 지정할 수 있습니다. 또한 Lambda 계층을 빌드하도록 선택하여 배포 패키지의 크기를 줄이고, 핵심 함수 로직을 종속성과 분리하며, 여러 함수에서 종속성을 공유할 수 있습니다.

이 섹션의 주제에서는 Lambda 함수를 빌드할 수 있는 몇 가지 다양한 방법을 살펴봅니다 AWS SAM. 여기에는 고객 런타임을 사용하여 Lambda 함수를 빌드하고 Lambda 계층을 빌드하는 것이 포함됩니다. 사용자 지정 런타임을 사용하면 AWS Lambda 개발자 안내서의 Lambda 런타임에 나열되지 않은 언어를 설치하고 사용할 수 있습니다. 이렇게 하면 서버리스 함수 및 애플리케이션을 실행할 수 있는 특수한 실행 환경을 생성할 수 있습니다. 전체 애플리케이션을 빌드하는 대신 Lambda 계층만 빌드함으로써 몇 가지 이점을 얻을 수 있습니다. 예를 들어 배포 패키지의 크기를 줄이고, 핵심 함수 로직을 종속성과 분리하며, 여러 함수에서 종속성을 공유할 수 있습니다.

자세한 내용은AWS Lambda 개발자 안내서**의 [Lambda 개념](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html)을 참조하세요.

**Topics**
+ [에서 esbuild를 사용하여 Node.js Lambda 함수 빌드 AWS SAM](serverless-sam-cli-using-build-typescript.md)
+ [에서 네이티브 AOT 컴파일을 사용하여 .NET Lambda 함수 빌드 AWS SAM](build-dotnet7.md)
+ [Cargo Lambda에서를 사용하여 Rust Lambda 함수 빌드 AWS SAM](building-rust.md)
+ [uv에서를 사용하여 Python Lambda 함수 빌드 AWS SAM](building-python-uv.md)
+ [에서 사용자 지정 런타임을 사용하여 Lambda 함수 빌드 AWS SAM](building-custom-runtimes.md)
+ [에서 Lambda 계층 빌드 AWS SAM](building-layers.md)

# 에서 esbuild를 사용하여 Node.js Lambda 함수 빌드 AWS SAM
<a name="serverless-sam-cli-using-build-typescript"></a>

Node.js AWS Lambda 함수를 AWS SAM CLI 빌드하고 패키징하려면 esbuild JavaScript 번들러와 함께를 사용할 수 있습니다. esbuild 번들러는 TypeScript로 작성하는 Lambda 함수를 지원합니다.

esbuild를 사용하여 Node.js Lambda 함수를 빌드하려면 `AWS:Serverless::Function` 리소스에 `Metadata` 객체를 추가하고 `BuildMethod`에 `esbuild`를 지정합니다. **sam build** 명령을 실행하면가 esbuild를 AWS SAM 사용하여 Lambda 함수 코드를 번들링합니다.

## 메타데이터 속성
<a name="serverless-sam-cli-using-build-typescript-metadata"></a>

`Metadata` 객체는 다음 속성을 지원합니다.

### BuildMethod
<a name="serverless-sam-cli-using-build-typescript-metadata-buildmethod"></a>

애플리케이션의 URL 접두사를 지정합니다. 지원되는 유일한 값은 `esbuild`입니다.

### BuildProperties
<a name="serverless-sam-cli-using-build-typescript-metadata-buildproperties"></a>

Lambda 함수 코드의 빌드 속성을 지정합니다.

`BuildProperties` 객체는 다음 속성을 지원합니다. 다른 모든 속성은 선택 사항입니다. 기본적으로는 진입점에 Lambda 함수 핸들러를 AWS SAM 사용합니다.

**EntryPoint**  
애플리케이션의 진입점을 지정합니다.

**외부**  
빌드에서 제외할 패키지 목록을 지정합니다. 자세한 내용은 *esbuild 웹사이트*의 [외부](https://esbuild.github.io/api/#external) 섹션을 참조하세요.

**형식**  
애플리케이션에서 생성된 JavaScript 파일의 출력 형식을 지정합니다. 자세한 내용은 *esbuild 웹 사이트*의 [형식](https://esbuild.github.io/api/#format)을 참조하세요.

**로더**  
지정된 파일 유형의 데이터를 로드하기 위한 구성 목록을 지정합니다.

**MainFields**  
패키지를 확인할 때 가져오려고 시도할 `package.json` 필드를 지정합니다. 기본값은 `main,module`입니다.

**Minify**  
번들링된 출력 코드를 축소할지 여부를 지정합니다. 기본값은 `true`입니다.

**OutExtension**  
esbuild가 생성하는 파일의 파일 확장자를 사용자 지정합니다. 자세한 내용은 *esbuild 웹사이트*의 [확장](https://esbuild.github.io/api/#out-extension)을 참조하세요.

**Sourcemap**  
번들러가 소스 맵 파일을 생성할지 여부를 지정합니다. 기본값은 `false`입니다.  
`true`로 설정되면 `NODE_OPTIONS: --enable-source-maps`는 Lambda 함수의 환경 변수에 추가되고, 소스 맵이 생성되어 함수에 포함됩니다.  
또는 `NODE_OPTIONS: --enable-source-maps`가 함수의 환경 변수에 포함된 경우 `Sourcemap`가 자동으로 `true`로 설정됩니다.  
충돌하는 경우 `Sourcemap: false`는 `NODE_OPTIONS: --enable-source-maps`보다 우선합니다.  
기본적으로 Lambda는 저장된 모든 환경 변수를 AWS Key Management Service (AWS KMS)로 암호화합니다. 소스 맵을 사용할 때 배포가 성공하려면 함수의 실행 역할에 `kms:Encrypt` 작업을 수행할 수 있는 권한이 있어야 합니다.

**SourcesContent**  
소스 맵 파일에 소스 코드를 포함할지 여부를 지정합니다. `Sourcemap`이 `'true'`로 설정되면 이 속성을 구성합니다.  
+ 모든 소스 코드를 포함하도록 `SourcesContent: 'true'`를 지정합니다.
+ 모든 소스 코드를 제외하도록 `SourcesContent: 'false'`를 지정합니다. 이렇게 하면 소스 맵 파일 크기가 작아지므로 시작 시간을 줄여 프로덕션에 유용합니다. 하지만 소스 코드는 디버거에서 사용할 수 없습니다.
기본값은 `SourcesContent: true`입니다.  
자세한 내용은 *esbuild 웹 사이트*의 [소스 콘텐츠](https://esbuild.github.io/api/#sources-content)를 참조하세요.

**대상**  
대상 ECMAScript 버전을 지정합니다. 기본값은 `es2020`입니다.

## TypeScript Lambda 함수
<a name="serverless-sam-cli-using-build-typescript-example"></a>

다음 예제 AWS SAM 템플릿 코드 조각은 esbuild를 사용하여의 TypeScript 코드에서 Node.js Lambda 함수를 생성합니다`hello-world/app.ts`.

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.handler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api 
          Properties:
            Path: /hello
            Method: get
      Environment:
        Variables:
          NODE_OPTIONS: --enable-source-maps
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Format: esm
        Minify: false
        OutExtension:
          - .js=.mjs
        Target: "es2020"
        Sourcemap: true
        EntryPoints: 
          - app.ts
        External:
          - "<package-to-exclude>"
```

# 에서 네이티브 AOT 컴파일을 사용하여 .NET Lambda 함수 빌드 AWS SAM
<a name="build-dotnet7"></a>

네이티브 AOT(Ahead-of-Time AWS SAM) 컴파일을 활용하여 AWS Lambda 콜드 스타트 시간을 개선하는 AWS Serverless Application Model ()로 .NET 8 AWS Lambda 함수를 빌드하고 패키징합니다.

**Topics**
+ [.NET 8 네이티브 AOT 개요](#build-dotnet7-overview)
+ [.NET 8 Lambda 함수와 AWS SAM 함께 사용](#build-dotnet7-sam)
+ [사전 조건 설치](#build-dotnet7-prerequisites)
+ [AWS SAM 템플릿에서 .NET 8 Lambda 함수 정의](#build-dotnet7-sam-define)
+ [AWS SAMCLI를 사용한 애플리케이션 구축](#build-dotnet7-sam-build)
+ [자세히 알아보기](#build-dotnet7-learn-more)

## .NET 8 네이티브 AOT 개요
<a name="build-dotnet7-overview"></a>

전통적으로 .NET Lambda 함수의 콜드 스타트 시간은 사용자 경험, 시스템 지연 시간, 서버리스 애플리케이션 사용 비용에 영향을 미칩니다. .NET 네이티브 AOT 컴파일을 사용하면 Lambda 함수의 콜드 스타트 시간을 개선할 수 있습니다. .NET 8용 네이티브 AOT에 대한 자세한 내용은 Dotnet GitHub 리포지토리**의 [네이티브 AOT 사용](https://github.com/dotnet/runtime/tree/main/src/coreclr/nativeaot#readme)을 참조하세요.

## .NET 8 Lambda 함수와 AWS SAM 함께 사용
<a name="build-dotnet7-sam"></a>

다음을 수행하여 .NET 8 Lambda 함수에서 AWS Serverless Application Model (AWS SAM)을 구성합니다.
+ 귀하의 개발 기기에 사전 조건을 설치합니다.
+  AWS SAM 템플릿에서 .NET 8 Lambda 함수를 정의합니다.
+ 를 사용하여 애플리케이션을 빌드합니다 AWS SAM CLI.

## 사전 조건 설치
<a name="build-dotnet7-prerequisites"></a>

다음은 필수적 사전 조건입니다.
+ 는 AWS SAM CLI
+ .NET Core CLI
+ Amazon.Lambda.Tools .NET Core Global Tool
+ Docker

**AWS SAM CLI 설치**

1. 이미 AWS SAMCLI가 설치되어 있는지 확인하려면 다음을 실행합니다.

   ```
   sam --version
   ```

1. 를 설치하려면 단원을 AWS SAM CLI참조하십시오[AWS SAM CLI 설치](install-sam-cli.md).

1. 설치된 버전의를 업그레이드하려면 단원을 AWS SAM CLI참조하십시오[AWS SAMCLI업그레이드](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade).

**.NET Core CLI 설치**

1. .NET Core CLI를 다운로드하고 설치하려면 Microsoft 웹 사이트에서[ .NET 다운로드](https://dotnet.microsoft.com/download)를 참조하세요.

1. .NET Core CLI에 대한 자세한 내용은 *AWS Lambda 개발자 가이드*의 [.NET Core CLI](https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html)를 참조하세요.

**Amazon.Lambda.Tools .NET Core Global Tool 설치**

1. 다음 명령을 실행합니다.

   ```
   dotnet tool install -g Amazon.Lambda.Tools
   ```

1. 이 도구가 이미 설치되어 있으면 다음 명령을 사용하여 최신 버전인지 확인할 수 있습니다.

   ```
   dotnet tool update -g Amazon.Lambda.Tools
   ```

1. Amazon.Lambda.Tools .NET Core Global에 대한 자세한 내용은 GitHub의 [AWS Extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli) 리포지토리를 참조하세요.

**Docker 설치**
+ 네이티브 AOT로 구축하려면 Docker이 설치되어야 합니다. 설치 지침은 [AWS SAMCLI와 함께 사용할 Docker 설치](install-docker.md)을 확인하십시오.

## AWS SAM 템플릿에서 .NET 8 Lambda 함수 정의
<a name="build-dotnet7-sam-define"></a>

 AWS SAM 템플릿에서 .NET8 Lambda 함수를 정의하려면 다음을 수행합니다.

1. 선택한 시작 디렉터리에서 다음 명령을 실행합니다.

   ```
   sam init
   ```

1. `AWS Quick Start Templates`을 선택하여 시작 템플릿을 선택합니다.

1. `Hello World Example` 템플릿을 선택합니다.

1. `n`을 입력하여 가장 많이 사용하는 런타임 및 패키지 유형을 사용하지 않도록 선택합니다.

1. 런타임에서 `dotnet8`을 선택합니다.

1. 패키지 유형에서 `Zip`을 선택합니다.

1. 스타터 템플릿에서 `Hello World Example using native AOT`를 선택합니다.

**Docker 설치**
+ 네이티브 AOT로 구축하려면 Docker이 설치되어야 합니다. 설치 지침은 [AWS SAMCLI와 함께 사용할 Docker 설치](install-docker.md)을 확인하십시오.

```
Resources:
HelloWorldFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: ./src/HelloWorldAot/
    Handler: bootstrap
    Runtime: dotnet8
    Architectures:
      - x86_64
    Events:
      HelloWorldAot:
        Type: Api 
        Properties:
          Path: /hello
          Method: get
```

**참고**  
의 `Event` 속성`AWS::Serverless::Function`이 로 설정`Api`되었지만 `RestApiId` 속성이 지정되지 않은 경우는 `AWS::ApiGateway::RestApi` CloudFormation 리소스를 AWS SAM 생성합니다.

## AWS SAMCLI를 사용한 애플리케이션 구축
<a name="build-dotnet7-sam-build"></a>

 프로젝트의 루트 디렉터리에서 `sam build` 명령을 실행하여 애플리케이션 구축을 시작합니다. .NET 8 프로젝트 파일에 `PublishAot` 속성을 정의한 경우 AWS SAMCLI가 네이티브 AOT 컴파일을 사용하여 빌드합니다. `PublishAot`속성에 대한 자세한 내용은 Microsoft의 [.NET 설명서](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/)에서 *네이티브 AOT 배포*를 참조하세요.

함수를 구축하려면 AWS SAMCLI가 Amazon.Lambda.Tools .NET Core Global Tool을 사용하는 .NET Core CLI를 간접 호출합니다.

**참고**  
구축 시 `.sln` 파일이 프로젝트의 동일 또는 상위 디렉터리에 있는 경우 `.sln` 파일이 들어있는 디렉터리가 컨테이너에 마운트됩니다. `.sln` 파일을 찾을 수 없는 경우 프로젝트 폴더만 마운트됩니다. 따라서 다중 프로젝트 응용 프로그램을 구축하는 경우 `.sln` 파일이 속성에 있는지 확인하십시오.

## 자세히 알아보기
<a name="build-dotnet7-learn-more"></a>

.NET 8 Lambda 함수 빌드에 대한 자세한 내용은 [AWS Lambda용 .NET 8 런타임 소개](https://aws.amazon.com/blogs/compute/introducing-the-net-8-runtime-for-aws-lambda/)를 참조하세요.

**sam build** 명령에 대한 참조는 [sam build](sam-cli-command-reference-sam-build.md)를 확인하세요.

# Cargo Lambda에서를 사용하여 Rust Lambda 함수 빌드 AWS SAM
<a name="building-rust"></a>


|  | 
| --- |
| 이 기능은에 대한 평가판 릴리스 AWS SAM 이며 변경될 수 있습니다. | 

Rust AWS Lambda 함수와 함께 AWS Serverless Application Model 명령줄 인터페이스(AWS SAM CLI)를 사용합니다.

**Topics**
+ [사전 조건](#building-rust-prerequisites)
+ [Rust Lambda 함수와 함께 AWS SAM 사용하도록 구성](#building-rust-configure)
+ [예제](#building-rust-examples)

## 사전 조건
<a name="building-rust-prerequisites"></a>

**Rust 언어**  
Rust를 설치하려면 *Rust 언어 웹 사이트*의 [Rust 설치](https://www.rust-lang.org/tools/install) 섹션을 참조하세요.

**Cargo Lambda**  
 AWS SAMCLI에는 Cargo의 하위 명령인 [https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html](https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html)의 설치가 필요합니다. 설치에 대한 지침은 *Cargo Lambda 설명서*의 [설치](https://www.cargo-lambda.info/guide/installation.html) 섹션을 참조하세요.

**Docker**  
Rust Lambda 함수를 빌드하고 테스트하려면 Docker가 필요합니다. 설치 지침은 [Docker 설치](install-docker.md)을 확인하세요.

** AWS SAMCLI 베타 기능에 대한 옵트인**  
이 기능은 미리 보기 버전이므로 다음 방법 중 하나를 사용하여 옵트인해야 합니다.  

1. `SAM_CLI_BETA_RUST_CARGO_LAMBDA=1` 환경 변수를 사용합니다.

1. 다음을 `samconfig.toml` 파일에 추가합니다.

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 지원되는 AWS SAMCLI 명령을 사용할 때는 이 `--beta-features` 옵션을 사용합니다. 예제:

   ```
   $ sam build --beta-features
   ```

1.  AWS SAMCLI에 옵트인하라는 메시지가 표시되면 `y` 옵션을 선택합니다. 다음은 예제입니다.

   ```
   $ sam build
   Starting Build use cache
   Build method "rust-cargolambda" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## Rust Lambda 함수와 함께 AWS SAM 사용하도록 구성
<a name="building-rust-configure"></a>

### 1단계: AWS SAM 템플릿 구성
<a name="building-rust-configure-template"></a>

다음을 사용하여 AWS SAM 템플릿을 구성합니다.
+ **바이너리** - 선택 사항. 템플릿에 여러 Rust Lambda 함수가 포함된 경우를 지정합니다.
+ **BuildMethod** – `rust-cargolambda`.
+ **CodeUri** – `Cargo.toml` 파일에 대한 경로
+ **핸들러** – `bootstrap`.
+ **런타임** – `provided.al2`.

사용자 지정 런타임에 대한 자세한 내용은 *AWS Lambda 개발자 안내서*의 [사용자 지정 AWS Lambda 런타임](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html)을 참조하세요.

다음은 구성된 AWS SAM 템플릿의 예입니다.

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties: function_a
    Properties:
      CodeUri: ./rust_app
      Handler: bootstrap
      Runtime: provided.al2
...
```

### 2단계: Rust Lambda 함수와 함께 AWS SAMCLI 사용
<a name="building-rust-configure-cli"></a>

 AWS SAM 템플릿과 함께 명령을 AWS SAM CLI 사용합니다. 자세한 내용은 [AWS SAM CLI](using-sam-cli.md) 단원을 참조하십시오.

## 예제
<a name="building-rust-examples"></a>

### Hello World 예제
<a name="building-rust-examples-hello"></a>

**이 예제에서는 Rust를 런타임으로 사용하여 샘플 Hello World 애플리케이션을 빌드합니다.**

먼저 `sam init`를 사용하여 새 서버리스 애플리케이션을 초기화합니다. 대화형 흐름 중에 **Hello World 애플리케이션**을 선택하고 **Rust** 런타임을 선택합니다.

```
$ 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?
        1 - dotnet8
        2 - dotnet6
        3 - go (provided.al2)
        ...
        18 - python3.11
        19 - python3.10
        20 - ruby3.3
        21 - ruby3.2
        22 - rust (provided.al2)
        23 - rust (provided.al2023)
Runtime: 22

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is cargo.
We will proceed copying the template using cargo.

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]: hello-rust

    -----------------------
    Generating application:
    -----------------------
    Name: hello-rust
    Runtime: rust (provided.al2)
    Architectures: x86_64
    Dependency Manager: cargo
    Application Template: hello-world
    Output Directory: .
    Configuration file: hello-rust/samconfig.toml
    
    Next steps can be found in the README file at hello-rust/README.md
        

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

Hello World 애플리케이션의 구조는 다음과 같습니다.

```
hello-rust
├── README.md
├── events
│   └── event.json
├── rust_app
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── samconfig.toml
└── template.yaml
```

 AWS SAM 템플릿에서 Rust 함수는 다음과 같이 정의됩니다.

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function 
    Metadata:
      BuildMethod: rust-cargolambda 
    Properties:
      CodeUri: ./rust_app 
      Handler: bootstrap   
      Runtime: provided.al2
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
            Path: /hello
            Method: get
```

다음으로 애플리케이션을 빌드하고 배포를 준비하기 위해 `sam build`를 실행합니다. AWS SAMCLI는 `.aws-sam` 디렉터리를 생성하고 여기에 빌드 아티팩트를 구성합니다. 함수는 Cargo Lambda를 사용하여 빌드되고 `.aws-sam/build/HelloWorldFunction/bootstrap`에 실행 가능한 바이너리로 저장됩니다.

**참고**  
MacOS 에서 **sam local invoke** 명령을 실행하려는 경우 간접적으로 호출하기 전에 다른 함수를 빌드해야 합니다. 이렇게 하려면 다음 명령을 사용합니다.  
**SAM\$1BUILD\$1MODE=debug sam build**
이 명령은 로컬 테스트를 수행하는 경우에만 필요합니다. 배포를 위해 빌드할 때는 권장되지 않습니다.

```
hello-rust$ sam build
Starting Build use cache
Build method "rust-cargolambda" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-rust/rust_app runtime: provided.al2 metadata: {'BuildMethod': 'rust-cargolambda'} architecture: x86_64 functions: HelloWorldFunction
Running RustCargoLambdaBuilder:CargoLambdaBuild
Running RustCargoLambdaBuilder:RustCopyAndRename

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
```

다음으로 `sam deploy --guided`를 사용하여 애플리케이션을 배포합니다.

```
hello-rust$ 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 [hello-rust]: 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]: ENTER
        #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

        Looking for resources needed for deployment:

        ...

        Uploading to hello-rust/56ba6585d80577dd82a7eaaee5945c0b  817973 / 817973  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : hello-rust
        Region                       : us-west-2
        Confirm changeset            : True
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================

        Uploading to hello-rust/a4fc54cb6ab75dd0129e4cdb564b5e89.template  1239 / 1239  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------
Operation                  LogicalResourceId          ResourceType               Replacement              
---------------------------------------------------------------------------------------------------------
+ Add                      HelloWorldFunctionHelloW   AWS::Lambda::Permission    N/A                      
                           orldPermissionProd                                                             
...                    
---------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1681427201/f0ef1563-5ab6-4b07-9361-864ca3de6ad6


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2023-04-13 13:07:17 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
---------------------------------------------------------------------------------------------------------
ResourceStatus             ResourceType               LogicalResourceId          ResourceStatusReason     
---------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS         AWS::IAM::Role             HelloWorldFunctionRole     -                        
CREATE_IN_PROGRESS         AWS::IAM::Role             HelloWorldFunctionRole     Resource creation        
...
---------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------
Outputs                                                                                                 
---------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                           
Description         Implicit IAM Role created for Hello World function                                  
Value               arn:aws:iam::012345678910:role/hello-rust-HelloWorldFunctionRole-10II2P13AUDUY      

Key                 HelloWorldApi                                                                       
Description         API Gateway endpoint URL for Prod stage for Hello World function                    
Value               https://ggdxec9le9.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:hello-rust-HelloWorldFunction-       
yk4HzGzYeZBj                                                                                            
---------------------------------------------------------------------------------------------------------


Successfully created/updated stack - hello-rust in us-west-2
```

테스트를 위해 API 엔드포인트를 사용하여 Lambda 함수를 호출할 수 있습니다.

```
$ curl https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/
Hello World!%
```

함수를 로컬에서 테스트하려면 먼저 함수의 `Architectures` 속성이 로컬 시스템과 일치하는지 확인합니다.

```
...
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
    Metadata:
      BuildMethod: rust-cargolambda # More info about Cargo Lambda: https://github.com/cargo-lambda/cargo-lambda
    Properties:
      CodeUri: ./rust_app   # Points to dir of Cargo.toml
      Handler: bootstrap    # Do not change, as this is the default executable name produced by Cargo Lambda
      Runtime: provided.al2
      Architectures:
        - arm64
...
```

이 예제에서는 아키텍처를 `x86_64`에서 `arm64`로 수정했으므로 빌드 아티팩트를 업데이트하기 위해 `sam build`를 실행합니다. 그런 다음 `sam local invoke`를 실행하여 함수를 로컬에서 호출합니다.

```
hello-rust$ sam local invoke
Invoking bootstrap (provided.al2)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-provided.al2
Building image.....................................................................................................................................
Using local image: public.ecr.aws/lambda/provided:al2-rapid-arm64.

Mounting /Users/.../hello-rust/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 Version: $LATEST
{"statusCode":200,"body":"Hello World!"}END RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6
REPORT RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6  Init Duration: 0.68 ms  Duration: 130.63 ms     Billed Duration: 131 ms     Memory Size: 128 MB     Max Memory Used: 128 MB
```

### 단일 Lambda 함수 프로젝트
<a name="building-rust-examples-single"></a>

**다음은 Rust Lambda 함수 하나를 포함하는 서버리스 애플리케이션의 예입니다.**

프로젝트 디렉터리 구조:

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── template.yaml
```

AWS SAM 템플릿:

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
    Properties:
      CodeUri: ./             
      Handler: bootstrap
      Runtime: provided.al2
...
```

### 다중 Lambda 함수 프로젝트
<a name="building-rust-examples-multiple"></a>

**다음은 여러 Rust Lambda 함수를 포함하는 서버리스 애플리케이션의 예입니다.**

프로젝트 디렉터리 구조:

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── function_a.rs
│   └── function_b.rs
└── template.yaml
```

AWS SAM 템플릿:

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_a 
    Properties:
      CodeUri: ./           
      Handler: bootstrap     
      Runtime: provided.al2
  FunctionB:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_b
    Properties:
      CodeUri: ./
      Handler: bootstrap
      Runtime: provided.al2
```

`Cargo.toml` 파일:

```
[package]
name = "test-handler"
version = "0.1.0"
edition = "2021"

[dependencies]
lambda_runtime = "0.6.0"
serde = "1.0.136"
tokio = { version = "1", features = ["macros"] }
tracing = { version = "0.1", features = ["log"] }
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }

[[bin]]
name = "function_a"
path = "src/function_a.rs"

[[bin]]
name = "function_b"
path = "src/function_b.rs"
```

# uv에서를 사용하여 Python Lambda 함수 빌드 AWS SAM
<a name="building-python-uv"></a>


|  | 
| --- |
| 이 기능은에 대한 평가판 릴리스 AWS SAM 이며 변경될 수 있습니다. | 

빠른 Python 패키지 설치 관리자 및 해석기uv인와 함께 AWS Serverless Application Model 명령줄 인터페이스(AWS SAM CLI)를 사용하여 Python AWS Lambda 함수를 빌드합니다.

**Topics**
+ [사전 조건](#building-python-uv-prerequisites)
+ [Python Lambda 함수 및와 함께 AWS SAM 사용하도록 구성 uv](#building-python-uv-configure)
+ [예제](#building-python-uv-examples)

## 사전 조건
<a name="building-python-uv-prerequisites"></a>

**Python**  
Python을 설치하려면 [Python 웹 사이트의 Python 다운로드](https://www.python.org/downloads/)를 참조하세요. ** 

**uv**  
에는 AWS SAM CLI 매우 빠른 Python 패키지 설치 관리자 및 해석기[https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)인를 설치해야 합니다. 설치에 대한 지침은 *uv 설명서*의 [설치](https://docs.astral.sh/uv/getting-started/installation/) 섹션을 참조하세요.

** AWS SAMCLI 베타 기능에 대한 옵트인**  
이 기능은 미리 보기 버전이므로 다음 방법 중 하나를 사용하여 옵트인해야 합니다.  

1. `SAM_CLI_BETA_PYTHON_UV=1` 환경 변수를 사용합니다.

1. 다음을 `samconfig.toml` 파일에 추가합니다.

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 지원되는 AWS SAMCLI 명령을 사용할 때는 이 `--beta-features` 옵션을 사용합니다. 예제:

   ```
   $ sam build --beta-features
   ```

1.  AWS SAMCLI에 옵트인하라는 메시지가 표시되면 `y` 옵션을 선택합니다. 다음은 예제입니다.

   ```
   $ sam build
   Starting Build use cache
   Build method "python-uv" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## Python Lambda 함수 및와 함께 AWS SAM 사용하도록 구성 uv
<a name="building-python-uv-configure"></a>

### 1단계: AWS SAM 템플릿 구성
<a name="building-python-uv-configure-template"></a>

다음을 사용하여 AWS SAM 템플릿을 구성합니다.
+ **BuildMethod** – `python-uv`.
+ **CodeUri** - `pyproject.toml` 또는가 포함된 함수 코드 디렉터리의 경로입니다`requirements.txt`.
+ **핸들러** - 함수 핸들러(예: `app.lambda_handler`).
+ **런타임** - Python 런타임 버전(예: `python3.12`).

다음은 구성된 AWS SAM 템플릿의 예입니다.

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./my_function
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: python-uv
...
```

## 예제
<a name="building-python-uv-examples"></a>

### Hello World 예제
<a name="building-python-uv-examples-hello"></a>

**이 예제에서는 Python을 패키지 관리자uv로 사용하여 샘플 Hello World 애플리케이션을 빌드합니다.**

uv는 `pyproject.toml` 또는 `requirements.txt`를 사용하여 종속성을 읽을 수 있습니다. 둘 다 주어지면 `sam build`는 종속성에 `requirements.txt` 대해에서 읽습니다.

Hello World 애플리케이션의 구조는 다음과 같습니다.

```
hello-python-uv
├── README.md
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── pyproject.toml
├── samconfig.toml
└── template.yaml
```

`pyproject.toml` 파일:

```
[project]
name = "my-function"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "requests>=2.31.0",
    "boto3>=1.28.0",
]
```

 AWS SAM 템플릿에서 Python 함수는 다음과 같이 정의됩니다.

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
      Architectures:
        - x86_64
    Metadata:
      BuildMethod: python-uv
```

다음으로 애플리케이션을 빌드하고 배포를 준비하기 위해 `sam build`를 실행합니다. AWS SAMCLI는 `.aws-sam` 디렉터리를 생성하고 여기에 빌드 아티팩트를 구성합니다. 함수 종속성은를 사용하여 설치uv되며에 저장됩니다`.aws-sam/build/HelloWorldFunction/`.

```
hello-python-uv$ sam build
Starting Build use cache
Build method "python-uv" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-python-uv/hello_world runtime: python3.12 metadata: {'BuildMethod': 'python-uv'} architecture: x86_64 functions: HelloWorldFunction
Running PythonUvBuilder:UvBuild
Running PythonUvBuilder: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
```

**참고**  
`python-uv` 빌드 메서드는 `Metadata` 섹션의 함수별로 구성됩니다. 템플릿의 각 함수는 다른 빌드 방법을 사용할 수 있으므로 uv기반 함수를 동일한 AWS SAM 템플릿의 `pip`기반 함수와 혼합할 수 있습니다. 빌드 메서드를 지정하지 않으면 `pip`가 기본적으로 사용됩니다.

# 에서 사용자 지정 런타임을 사용하여 Lambda 함수 빌드 AWS SAM
<a name="building-custom-runtimes"></a>

`sam build` 명령을 사용하여 귀하의 Lambda 함수에 필요한 사용자 지정 런타임을 구축할 수 있습니다. Lamda 함수를 선언하여 사용자 지정 런타임을 사용하기 위해 해당 Lambda 함수에 대해 `Runtime: provided`을 지정하십시오.

사용자 지정 런타임을 구축하려면 `Metadata` 항목이 있는 `BuildMethod: makefile` 리소스 속성을 선언하십시오. 런타임용 빌드 명령이 포함된 양식의 빌드 대상을 `build-function-logical-id` 선언하는 사용자 지정 makefile을 제공하십시오. 귀하의 makefile은 필요한 경우 사용자 지정 런타임을 컴파일하고 워크플로의 후속 단계에 필요한 적절한 위치에 빌드 아티팩트를 복사합니다. makefile의 위치는 함수 리소스의 `CodeUri` 속성으로 지정되며 `Makefile`라는 이름을 지정해야 합니다.

## 예제
<a name="building-custom-runtimes-examples"></a>

### 예제 1: Rust로 작성된 함수의 사용자 지정 런타임
<a name="building-custom-runtimes-examples-rust"></a>

**참고**  
Cargo Lambda을 사용해 Lambda 함수를 구축하는 것이 좋습니다. 자세한 내용은 [Cargo Lambda에서를 사용하여 Rust Lambda 함수 빌드 AWS SAM](building-rust.md)를 참조하세요.

다음 AWS SAM 템플릿은 Rust로 작성된 Lambda 함수에 대해 사용자 지정 런타임을 사용하는 함수를 선언하고에 `build-HelloRustFunction` 빌드 대상에 대한 명령을 실행`sam build`하도록 지시합니다.

```
Resources:
  HelloRustFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: HelloRust
      Handler: bootstrap.is.real.handler
      Runtime: provided
      MemorySize: 512
      CodeUri: .
    Metadata:
      BuildMethod: makefile
```

다음 makefile에는 빌드 대상과 실행될 명령이 포함되어 있습니다. 참고로 `CodeUri` 속성은 `.`로 설정되어 있으므로 makefile은 프로젝트 루트 디렉터리(즉, 애플리케이션의 AWS SAM 템플릿 파일과 동일한 디렉터리)에 있어야 합니다. 파일 이름은 `Makefile`이어야 합니다.

```
build-HelloRustFunction:
	cargo build --release --target x86_64-unknown-linux-musl
	cp ./target/x86_64-unknown-linux-musl/release/bootstrap $(ARTIFACTS_DIR)
```

`cargo build` 이전 명령어를 실행`makefile`하기 위한 개발 환경 설정의 자세한 내용은 블로그 게시물용 [Rust Runtime AWS Lambda](https://aws.amazon.com/blogs/opensource/rust-runtime-for-aws-lambda/)을 잠조하세요.

### 예제 2: Python3.12용 Makefile 빌더(번들 빌더 사용의 대안)
<a name="building-custom-runtimes-examples-python"></a>

번들 빌더에 포함되지 않은 라이브러리 또는 모듈을 사용하고 싶을 수도 있습니다. 이 예제에서는 makefile 빌더가 있는 Python3.12 런타임에 대한 AWS SAM 템플릿을 보여줍니다.

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: makefile
```

다음 makefile에는 빌드 대상과 실행될 명령이 포함되어 있습니다. 참고로 `CodeUri` 속성은 `hello_world`로 설정되었으므로 makefile은 `hello_world` 하위 디렉토리의 루트에 있어야 하고 파일 이름은 `Makefile`이어야 합니다.

```
build-HelloWorldFunction:
	cp *.py $(ARTIFACTS_DIR)
	cp requirements.txt $(ARTIFACTS_DIR)
	python -m pip install -r requirements.txt -t $(ARTIFACTS_DIR)
	rm -rf $(ARTIFACTS_DIR)/bin
```

# 에서 Lambda 계층 빌드 AWS SAM
<a name="building-layers"></a>



 AWS SAM 를 사용하여 사용자 지정 Lambda 계층을 빌드할 수 있습니다. Lambda 계층을 사용하면 Lambda 함수에서 코드를 추출한 다음 여러 Lambda 함수에서 재사용할 수 있습니다. 전체 애플리케이션을 빌드하는 대신 Lambda 계층만 빌드함으로써 몇 가지 이점을 얻을 수 있습니다. 예를 들어 배포 패키지의 크기를 줄이고, 핵심 함수 로직을 종속성과 분리하며, 여러 함수에서 종속성을 공유할 수 있습니다. 레이어에 대한 자세한 내용을 알아보려면 [AWS 개발자 가이드](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html) 내 *AWS Lambda Lambda 레이어*를 확인하십시오.

## 에서 Lambda 계층을 빌드하는 방법 AWS SAM
<a name="w2aac18c23c19c34b7"></a>

**참고**  
Lambda 계층을 빌드하려면 먼저 AWS SAM 템플릿에 Lambda 계층을 작성해야 합니다. 이 작업 수행과 관련된 자세한 내용과 예제는 [에서 Lambda 계층을 사용하여 효율성 향상 AWS SAM](serverless-sam-cli-layers.md) 섹션을 참조하세요.

사용자 지정 계층을 빌드하려면 AWS Serverless Application Model (AWS SAM) 템플릿 파일에 계층을 선언하고 `Metadata` 리소스 속성 섹션을 `BuildMethod` 항목과 함께 포함합니다. `BuildMethod`의 유효한 값은 [AWS Lambda 런타임의](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html) 혹은 `makefile`의 식별자입니다. 레이어가 지원하는 명령어 세트 아키텍처를 지정하기 위해 `BuildArchitecture`을 포함하십시오. `BuildArchitecture`의 유효한 값은 [Lambda 명령 세트 아키텍처](https://docs.aws.amazon.com/lambda/latest/dg/foundation-arch.html)입니다.

`makefile`을 지정하는 경우 사용자 지정 makefile을 제공하고 거기에서 레이어의 빌드 명령이 포함된 `build-layer-logical-id` 양식의 빌드 대상을 선언하십시오. makefile은 필요한 경우 레이어를 컴파일하고 워크플로의 후속 단계에 필요한 적절한 위치에 빌드 아티팩트를 복사합니다. makefile의 위치는 레이어 리소스의 `ContentUri` 속성으로 지정되며 `Makefile`라는 이름을 지정해야 합니다.

**참고**  
사용자 지정 계층을 생성할 때는 환경 변수에 AWS Lambda 따라 계층 코드를 찾습니다. Lambda 런타임에는 레이어 코드가 복사되어 들어가는 `/opt` 디렉토리의 경로가 포함됩니다. 사용자 지정 레이어 코드를 찾을 수 있도록 프로젝트의 빌드 아티팩트 폴더 구조가 런타임의 예상 폴더 구조와 일치해야 합니다.  
예를 들어, Python의 경우 귀하의 코드를 `python/` 하위 디렉터리에 배치할 수 있습니다. NodeJS의 경우 코드를 `nodejs/node_modules/` 하위 디렉터리에 배치할 수 있습니다.  
자세한 내용은 [개발자 가이드](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path)의 레이어에 *AWS Lambda 라이브러리 종속 항목 포함하기*를 참조하세요.

다음은 예제 `Metadata` 리소스 속성 섹션입니다.

```
    Metadata:
      BuildMethod: python3.12
      BuildArchitecture: arm64
```

**참고**  
`Metadata` 리소스 속성 섹션을 포함하지 않으면 계층을 빌드 AWS SAM 하지 않습니다. 대신 그것은 레이어 리소스의 `CodeUri` 속성에 지정된 위치에서 빌드 아티팩트를 복사합니다. 자세한 내용은 [리소스 유형](sam-resource-layerversion.md#sam-layerversion-contenturi)의 `AWS::Serverless::LayerVersion`ContentUri 속성을 참조하세요.

`Metadata` 리소스 속성 섹션을 포함할 때 `sam build` 명령을 사용하여 독립 객체 또는 AWS Lambda 함수의 종속성으로 계층을 빌드할 수 있습니다.
+ ****독립 객체로서.**** 예를 들어 전체 애플리케이션을 빌드하지 않아도 레이어에 대한 코드 변경을 로컬에서 테스트하는 경우에는 레이어 객체만 빌드하는 것이 좋습니다. 레이어를 독립적으로 구축하려면 `sam build layer-logical-id` 명령으로 레이어 리소스를 지정하십시오.
+ **Lambda 함수의 종속 항목으로서.** 동일한 `Layers` 템플릿 파일에 있는 Lambda 함수의 AWS SAM 속성에 레이어의 논리적 ID를 포함시키면 레이어는 해당 Lambda 함수의 종속 항목이 됩니다. 해당 레이어에 `Metadata` 항목이 포함된 `BuildMethod` 리소스 속성 섹션도 포함된 경우 `sam build` 명령으로 전체 애플리케이션을 빌드하거나 `sam build function-logical-id` 명령으로 함수 리소스를 지정하여 레이어를 구축합니다.

## 예제
<a name="building-applications-examples"></a>

### 템플릿 예제 1: Python 3.12 런타임 환경에 대한 계층 구축
<a name="building-applications-examples-python"></a>

다음 예제 AWS SAM 템플릿은 Python 3.12 런타임 환경에 대한 계층을 빌드합니다.

```
Resources:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: my_layer
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: python3.12   # Required to have AWS SAM build this layer
```

### 템플릿 예제 2: 사용자 지정 makefile을 사용하여 레이어 구축
<a name="building-applications-examples-makefile"></a>

다음 예제 AWS SAM 템플릿은 사용자 지정를 사용하여 계층`makefile`을 빌드합니다.

```
Resources:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: my_layer
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: makefile
```

다음`makefile`은 빌드 타겟과 실행될 명령을 포함합니다. 참고로 `ContentUri` 속성은 `my_layer`로 설정되었으므로 makefile은 `my_layer` 하위 디렉토리의 루트에 있어야 하고 파일 이름은 `Makefile`이어야 합니다. 또한 빌드 아티팩트는 `python/` 하위 디렉터리로 복사되므로 AWS Lambda 에서 계층 코드를 찾을 수 있습니다.

```
build-MyLayer:
  mkdir -p "$(ARTIFACTS_DIR)/python"
  cp *.py "$(ARTIFACTS_DIR)/python"
  python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)/python"
```

**참고**  
`makefile`이(가) 호출되면 적절한 대상이 트리거되고 아티팩트가 노출된 환경 변수 `$ARTIFACTS_DIR`에 복사되어야 합니다. 자세한 내용은 [GitHub의 aws-lambda-builders](https://github.com/aws/aws-lambda-builders/blob/develop/aws_lambda_builders/workflows/custom_make/DESIGN.md)를 참조하세요.

### sam build 명령어 예시
<a name="building-applications-examples-commands"></a>

다음 `sam build` 명령은 `Metadata` 리소스 속성 섹션을 포함하는 레이어를 구축합니다.

```
# Build the 'layer-logical-id' resource independently
$ sam build layer-logical-id
            
# Build the 'function-logical-id' resource and layers that this function depends on
$ sam build function-logical-id

# Build the entire application, including the layers that any function depends on
$ sam build
```