

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# でビルドをカスタマイズする 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 関数を構築してパッケージ化するには、esbuild AWS SAM CLIJavaScript バンドルャで を使用できます。esbuild バンドラーは TypeScript で記述されて Lambda 関数をサポートします。

esbuild を使用して Node.js Lambda 関数を構築するには、`AWS:Serverless::Function` リソースに `Metadata` オブジェクトを追加し、`BuildMethod` に `esbuild` を指定します。**sam build** コマンドを実行すると、 は esbuild AWS SAM を使用して Lambda 関数コードをバンドルします。

## Metadata プロパティ
<a name="serverless-sam-cli-using-build-typescript-metadata"></a>

`Metadata` オブジェクトは esbuild の以下のプロパティをサポートします。

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

アプリケーションのバンドルを指定します。`esbuild` はサポートされる唯一の値です。

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

Lambda 関数コードの構築プロパティを指定します。

`BuildProperties` オブジェクトは esbuild の以下のプロパティをサポートします。プロパティはすべてオプションです。デフォルトでは、 はエントリポイントに Lambda 関数ハンドラー AWS SAM を使用します。

**EntryPoint**  
アプリケーションのエントリポイントを指定します。

**外部**  
構築から除外するパッケージのリストを指定します。詳細については、esbuild ウェブサイトの「[External](https://esbuild.github.io/api/#external)」を参照してください。

**形式**  
アプリケーションで生成される JavaScript ファイルの出力形式を指定します。詳細については、*esbuild ウェブサイト*で「[Format](https://esbuild.github.io/api/#format)」を参照してください。

**[ローダー]**  
特定のファイルタイプのデータをロードするための設定のリストを指定します。

**MainFields**  
パッケージを解決する際にインポートを試行する `package.json` フィールドを指定します。デフォルト値は `main,module` です。

**Minify**  
バンドルされた出力コードを縮小するかどうかを指定します。デフォルト値は `true` です。

**OutExtension**  
esbuild が生成するファイルのファイル拡張子をカスタマイズします。詳細については、*esbuild ウェブサイト*で「[Out extension](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>

( AWS Serverless Application Model AWS SAM) を使用して .NET 8 AWS Lambda 関数を構築およびパッケージ化し、ネイティブAhead-of-TimeAOT) コンパイルを利用して 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 SAM CLI を使用してアプリケーションを構築する](#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 の詳細については、GitHub の dotnet リポジトリで「[ネイティブ AOT の使用](https://github.com/dotnet/runtime/tree/main/src/coreclr/nativeaot#readme)」を参照してください。

## .NET 8 Lambda 関数 AWS SAM での の使用
<a name="build-dotnet7-sam"></a>

 AWS Serverless Application Model (AWS SAM) を使用して.NET 8 Lambda 関数を設定するには、次の手順を実行します。
+ 開発マシンに前提条件をインストールする。
+  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 SAM CLI がインストールされているかを確認するには、次のコマンドを実行します。

   ```
   sam --version
   ```

1. をインストールするには AWS SAM CLI、「」を参照してください[AWS SAM CLI のインストール](install-sam-cli.md)。

1. のインストール済みバージョンをアップグレードするには AWS SAM CLI、「」を参照してください[AWS SAM CLI のアップグレード](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade)。

**.NET Core CLI をインストールする**

1. .NET Core CLI をダウンロードしてインストールするには、Microsoft の Web サイトで「[.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 Tool の詳細については、GitHub の [AWS Extensions for .NET CLI](https://github.com/aws/aws-extensions-for-dotnet-cli) リポジトリを参照してください。

**Docker をインストールする**
+ ネイティブ AOT を構築に使用するには、Docker をインストールする必要があります。インストール手順については、「[AWS SAM CLI で 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 SAM CLI で 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 SAM CLI を使用してアプリケーションを構築する
<a name="build-dotnet7-sam-build"></a>

 プロジェクトのルートディレクトリから `sam build` コマンドを実行して、アプリケーションの構築を開始します。.NET 8 プロジェクトファイルで `PublishAot` プロパティを定義済みの場合、 AWS SAM CLI はネイティブ AOT コンパイルにより構築されます。`PublishAot` プロパティの詳細については、Microsoft の「*.NET ドキュメント*」で「[ネイティブ AOT デプロイ](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/)」を参照してください。

関数を構築する際、 AWS SAM CLI は 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 SAM CLI では、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 ドキュメント*」で「[Installation](https://www.cargo-lambda.info/guide/installation.html)」を参照してください。

**Docker**  
Rust Lambda 関数の構築とテストには Docker が必要です。インストール手順については、「[Docker のインストール](install-docker.md)」を参照してください。

** AWS SAM CLI ベータ機能にオプトインする**  
この機能はプレビュー段階にあるため、次のいずれかの方法を使用してオプトインする必要があります。  

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 SAM CLI のコマンドを使用する場合は、`--beta-features` オプションを使用します。例えば、次のようになります。

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

1.  AWS SAM CLI でオプトインするよう促すプロンプトが表示されたら、オプション `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 テンプレートを設定します。
+ **Binary** – オプション。テンプレートに複数の Rust Lambda 関数が含まれる場合に指定します。
+ **BuildMethod** – `rust-cargolambda`。
+ **CodeUri** – `Cargo.toml` ファイルへのパス。
+ **Handler** – `bootstrap`。
+ **Runtime** – `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 SAM CLI を使用する
<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 SAM CLI は `.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>

**1 つの 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**  
には[https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)、非常に高速な Python パッケージインストーラおよびリゾルバーである のインストール AWS SAM CLIが必要です。インストール手順については、「*uv ドキュメント*」で「[Installation](https://docs.astral.sh/uv/getting-started/installation/)」を参照してください。

** AWS SAM CLI ベータ機能にオプトインする**  
この機能はプレビュー段階にあるため、次のいずれかの方法を使用してオプトインする必要があります。  

1. 次の環境変数を使用します: `SAM_CLI_BETA_PYTHON_UV=1`。

1. 次のコードを `samconfig.toml` ファイルに追加します。

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

1. サポートされている AWS SAM CLI のコマンドを使用する場合は、`--beta-features` オプションを使用します。例えば、次のようになります。

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

1.  AWS SAM CLI でオプトインするよう促すプロンプトが表示されたら、オプション `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 SAM CLI は `.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 関数に必要なカスタムランタイムを構築できます。Lambda 関数に `Runtime: provided` を指定することによって、その関数がカスタムランタイムを使用するように宣言します。

カスタムランタイムを構築するには、`BuildMethod: makefile` エントリを使用して `Metadata` リソース属性を宣言します。ユーザーは、ランタイムの build コマンドが含まれた `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)
```

上記の `makefile` で `cargo build` コマンドを実行するための開発環境のセットアップに関する詳細については、「[Rust Runtime for AWS Lambda](https://aws.amazon.com/blogs/opensource/rust-runtime-for-aws-lambda/)」ブログ記事を参照してください。

### 例 2: Python 3.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 Lambda デベロッパーガイド*の「[AWS Lambda レイヤー](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)」参照してください。

## で 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` を指定する場合は、レイヤーの build コマンドが含まれた `build-layer-logical-id` フォームのビルドターゲットを宣言するカスタム makefile を提供します。Makefile は、必要に応じてレイヤーをコンパイルして、ワークフローにおける後続のステップに必要となる適切な場所にビルドアーティファクトをコピーする責任を担います。Makefile の場所は、レイヤーリソースの `ContentUri` プロパティによって指定され、`Makefile` と命名される必要があります。

**注記**  
カスタムレイヤーを作成すると、 は環境変数 AWS Lambda に応じてレイヤーコードを見つけます。Lambda ランタイムは、レイヤーコードがコピーされた `/opt` ディレクトリにパスを含めます。カスタムレイヤーコードを見つけられるようにするため、プロジェクトのビルドアーティファクトのフォルダ構造が、ランタイムが期待するフォルダ構造と一致している必要があります。  
例えば、Python ではコードを `python/` サブディレクトリに置くことができます。NodeJS では、コードを `nodejs/node_modules/` サブディレクトリに置くことができます。  
詳細については、*AWS Lambda デベロッパーガイド*の「[ライブラリの依存関係をレイヤーに含める](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path)」を参照してください。

以下は、`Metadata` リソース属性セクションの例です。

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

**注記**  
`Metadata` リソース属性セクションを含めない場合、 AWS SAM はレイヤーを構築しません。その代わりに、レイヤーリソースの `CodeUri` プロパティで指定された場所からビルドアーティファクトをコピーします。詳細については、`AWS::Serverless::LayerVersion` リソースタイプの「[ContentUri](sam-resource-layerversion.md#sam-layerversion-contenturi)」プロパティを参照してください。

`Metadata` リソース属性セクションを含めると、 `sam build` コマンドを使用して、独立したオブジェクトとして、または AWS Lambda 関数の依存関係としてレイヤーを構築できます。
+ ****独立したオブジェクトとして。****レイヤーに対するコード変更をローカルでテストしており、アプリケーション全体を構築する必要がないときなど、レイヤーオブジェクトだけを構築したい場合があります。レイヤーを個別に構築するには、`sam build layer-logical-id` コマンドでレイヤーリソースを指定します。
+ **Lambda 関数の依存関係として。**同じ AWS SAM テンプレートファイルにある Lambda 関数の `Layers` プロパティにレイヤーの論理 ID を含めると、レイヤーはその Lambda 関数の依存関係になります。そのレイヤーに `BuildMethod` エントリがある `Metadata` リソース属性セクションも含める場合は、`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
```