

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

# チュートリアル: を使用して Hello World アプリケーションをデプロイする AWS SAM
<a name="serverless-getting-started-hello-world"></a>

このチュートリアルでは、 AWS Serverless Application Model コマンドラインインターフェイス (AWS SAM CLI) を使用して以下を完了します。
+ サンプルの **Hello World** アプリケーションを初期化、構築、デプロイします。
+ ローカルで変更を行い、 に同期します AWS CloudFormation。
+ 開発ホストでローカルテストを実行します。
+  AWS クラウドからサンプルアプリケーションを削除します。

サンプルの **Hello World** アプリケーションは、基本的な API バックエンドを実装しています。これは次のリソースで構成されます。
+ **Amazon API Gateway** – 関数を呼び出すために使用する API エンドポイント。
+ **AWS Lambda** – HTTP API GET リクエストを処理し、`hello world` メッセージを返す関数。
+ **AWS Identity and Access Management (IAM) ロール** – サービスが安全にやり取りするためのアクセス許可をプロビジョニングします。

以下の図は、このアプリケーションのコンポーネントを示しています。

![\[API Gateway エンドポイントに GET リクエストを送信するときに呼び出される Lambda 関数の図。\]](http://docs.aws.amazon.com/ja_jp/serverless-application-model/latest/developerguide/images/gs-01.png)


**Topics**
+ [前提条件](#serverless-getting-started-hello-world-prerequisites)
+ [ステップ 1: サンプルの Hello World アプリケーションを初期化する](#serverless-getting-started-hello-world-init)
+ [ステップ 2: アプリケーションを構築する](#serverless-getting-started-hello-world-build)
+ [ステップ 3: アプリケーションを にデプロイする AWS クラウド](#serverless-getting-started-hello-world-deploy)
+ [ステップ 4: アプリケーションを実行する](#serverless-getting-started-hello-world-run)
+ [ステップ 5: で 関数を操作する AWS クラウド](#serverless-getting-started-hello-world-remote-invoke)
+ [ステップ 6: アプリケーションを変更して に同期する AWS クラウド](#serverless-getting-started-hello-world-sync)
+ [ステップ 7: (オプション) アプリケーションをローカルでテストする](#serverless-getting-started-hello-world-test)
+ [ステップ 8: からアプリケーションを削除する AWS クラウド](#serverless-getting-started-hello-world-delete)
+ [トラブルシューティング](#serverless-getting-started-hello-world-troubleshoot)
+ [詳細情報](#serverless-getting-started-hello-world-learn)

## 前提条件
<a name="serverless-getting-started-hello-world-prerequisites"></a>

次を完了していることを確認します。
+ [AWS SAM 前提条件](prerequisites.md)
+ [AWS SAM CLI のインストール](install-sam-cli.md)

**注記**  
サーバーレス開発に Visual Studio Code を使用する場合は、「 AWS Toolkit for VS Code ユーザーガイド」の[「サーバーレスアプリケーションの作成](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/sam-get-started.html#serverless-apps-create)step-by-step 」を参照してください。

## ステップ 1: サンプルの Hello World アプリケーションを初期化する
<a name="serverless-getting-started-hello-world-init"></a>

このステップでは、 AWS SAM CLI を使用して、ローカルマシン上にサンプルの **Hello World** アプリケーションプロジェクトを作成します。

**サンプルの Hello World アプリケーションを初期化するには**

1. コマンドラインで、選択した開始ディレクトリから次を実行します。

   ```
   $ sam init
   ```
**注記**  
このコマンドは、サーバーレスアプリケーションを初期化し、プロジェクトディレクトリを作成します。ディレクトリには、 AWS SAM テンプレートである ファイルを含む複数の`template.yaml`ファイルとフォルダが含まれています。  
インストールされた Python バージョンは、`template.yaml` で指定された `Runtime` プロパティと一致する必要があります。本稼働ワークロードでは、 AWS 環境で完全にサポートされている Python 3.12 以前のバージョンを使用することをお勧めします。Python バージョンが一致しない場合、ビルドエラーが発生します。  
バージョン互換性の問題を解決するには、以下を実行します。  
 初期化中に互換性のある[ランタイム](sam-cli-command-reference-sam-init.md#sam-cli-command-reference-sam-init-options-runtime)を指定: `sam init --runtime python3.9`
初期化後に `template.yaml` で `Runtime` プロパティを変更

1.  AWS SAM CLI は、新しいアプリケーションの初期化を通じてユーザーをガイドします。次を設定します。

   1. **[AWS クイックスタートテンプレート]** を選択して、開始テンプレートを選択します。

   1. **[Hello World Example]** テンプレートを選択してダウンロードします。

   1. Python ランタイムと `zip` パッケージタイプを使用します。

   1. このチュートリアルでは、 AWS X-Ray トレースをオプトアウトします。詳細については、「 *AWS X-Ray デベロッパーガイド*」の[「What is AWS X-Ray?](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html)」を参照してください。

   1. このチュートリアルでは、Amazon CloudWatch Application Insights によるモニタリングをオプトアウトします。詳細については、「*Amazon CloudWatch ユーザーガイド*」の「[Amazon CloudWatch Application Insights](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html)」を参照してください。

   1. このチュートリアルでは、Lambda 関数で JSON 形式の構造化ログ記録の設定をオプトアウトします。

   1. アプリケーションに **sam-app** という名前を付けます。

    AWS SAM CLI インタラクティブフローを使用するには:
   + 括弧 (`[ ]`) はデフォルト値を示します。回答を空白のままにすると、デフォルト値が選択されます。
   + **はい**の場合は **`y`** と入力し、**いいえ**の場合は **`n`** と入力します。

   `sam init` インタラクティブフローの例を次に示します。

   ```
   $ sam init
   ...
   Which template source would you like to use?
       1 - AWS Quick Start Templates
       2 - Custom Template Location
   Choice: 1
   
   Choose an AWS Quick Start application template
       1 - Hello World Example
       2 - Data processing
       3 - Hello World Example with Powertools for AWS Lambda
       4 - Multi-step workflow
       5 - Scheduled task
       6 - Standalone function
       7 - Serverless API
       8 - Infrastructure event management 
       9 - Lambda Response Streaming
      10 - GraphQLApi Hello World Example
      11 - Full Stack
      12 - Lambda EFS example
      13 - Serverless Connector Hello World Example
      14 - Multi-step workflow with Connectors
      15 - DynamoDB Example
      16 - Machine Learning
   Template: 1
   
   Use the most popular runtime and package type? (Python and zip) [y/N]: y
   
   Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER
   
   Would you like to enable monitoring using CloudWatch Application Insights?
   For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER
   					
   Would you like to set Structured Logging in JSON format on your Lambda functions?  [y/N]: ENTER
   
   Project name [sam-app]: ENTER
   ```

1. は開始テンプレート AWS SAM CLIをダウンロードし、ローカルマシンにアプリケーションプロジェクトディレクトリ構造を作成します。次は AWS SAM CLI の出力例です。

   ```
   Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
   
       -----------------------
       Generating application:
       -----------------------
       Name: sam-app
       Runtime: python3.9
       Architectures: x86_64
       Dependency Manager: pip
       Application Template: hello-world
       Output Directory: .
       Configuration file: sam-app/samconfig.toml
   
       Next steps can be found in the README file at sam-app/README.md
   
   
   Commands you can use next
   =========================
   [*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
   [*] Validate SAM template: cd sam-app && sam validate
   [*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch
   ```

1. コマンドラインから、新しく作成した `sam-app` ディレクトリに移動します。 AWS SAM CLI が作成したものの例を次に示します。
**注記**  
`tree` コマンドが自動でインストールされていない場合は、`brew install tree` コマンドを実行してください。

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

   強調すべきいくつかの重要なファイル:
   + `hello_world/app.py` – Lambda 関数コードが含まれます。
   + `hello_world/requirements.txt` – Lambda 関数に必要な Python 依存関係が含まれます。
   + `samconfig.toml` – で使用されるデフォルトのパラメータを保存するアプリケーションの設定ファイル AWS SAM CLI。
   + `template.yaml` – アプリケーションインフラストラクチャコードを含む AWS SAM テンプレート。

これで、サーバーレスアプリケーションがローカルマシン上に完成しました。

## ステップ 2: アプリケーションを構築する
<a name="serverless-getting-started-hello-world-build"></a>

このステップでは、 AWS SAM CLI を使用してアプリケーションを構築し、デプロイの準備をします。構築すると、 AWS SAM CLI は `.aws-sam` ディレクトリを作成し、そこに関数の依存関係、プロジェクトコード、およびプロジェクトファイルを整理します。

**アプリケーションを構築するには**
+ コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

  ```
  $ sam build
  ```
**注記**  
 ローカルマシンに Python がない場合は、代わりに **sam build --use-container ** コマンドを使用します。 AWS SAM CLI は、関数のランタイムと依存関係を含む Docker コンテナを作成します。このコマンドを使用するには、ローカルマシン上に Docker が必要です。Docker をインストールするには、「[Docker のインストール](install-docker.md)」を参照してください。

  次は AWS SAM CLI の出力例です。

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

   AWS SAM CLI によって作成される `.aws-sam` ディレクトリの短い例を次に示します。

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

強調すべきいくつかの重要なファイル:
+ `build/HelloWorldFunction` – Lambda 関数のコードと依存関係が含まれます。 AWS SAM CLI は、アプリケーション内の関数ごとにディレクトリを作成します。
+ `build/template.yaml` – デプロイ CloudFormation 時に によって参照される AWS SAM テンプレートのコピーが含まれます。
+ `build.toml` – アプリケーションの構築およびデプロイ時に AWS SAM CLI によって参照されるデフォルトのパラメータ値を保存する設定ファイル。

これで、アプリケーションを AWS クラウドにデプロイする準備が整いました。

## ステップ 3: アプリケーションを にデプロイする AWS クラウド
<a name="serverless-getting-started-hello-world-deploy"></a>

**注記**  
このステップでは、 AWS 認証情報の設定が必要です。詳細については、「[AWS SAM 前提条件](prerequisites.md)」の [ステップ 5: AWS CLI を使用して AWS 認証情報を設定する](prerequisites.md#prerequisites-configure-credentials) を参照してください。

このステップでは、 AWS SAM CLI を使用してアプリケーションを AWS クラウドにデプロイします。 AWS SAM CLI は以下を実行します。
+ デプロイのためのアプリケーション設定を通じてユーザーをガイドします。
+ アプリケーションファイルを Amazon Simple Storage Service (Amazon S3) にアップロードします。
+  AWS SAM テンプレートを CloudFormation テンプレートに変換します。次に、 テンプレートを CloudFormation サービスにアップロードしてリソースをプロビジョニングします AWS 。

**アプリケーションをデプロイするには**

1. コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

   ```
   $ sam deploy --guided
   ```

1.  AWS SAM CLI のインタラクティブフローに従って、アプリケーション設定を構成します。次を設定します。

   1. **CloudFormation スタック名** – スタックは、単一のユニットとして管理できる AWS リソースのコレクションです。詳細については、「*AWS CloudFormation ユーザーガイド*」の「[スタックの使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html)」を参照してください。

   1.  CloudFormation スタックをデプロイ**AWS リージョン**する 。詳細については、「*AWS CloudFormation ユーザーガイド」の「[CloudFormation endpoints](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-endpoints.html)*」を参照してください。

   1. このチュートリアルでは、**デプロイ前の変更の確認**をオプトアウトします。

   1. **IAM ロールの作成**を許可する – これにより、API Gateway リソースと Lambda 関数リソースがやり取りするために必要な IAM ロール AWS SAM を作成できます。

   1. このチュートリアルでは、**ロールバックの無効化**をオプトアウトします。

   1. **認可が定義されていない HelloWorldFunction** を許可 – このメッセージは、認可なしで API Gateway エンドポイントにパブリックにアクセスできるように設定されているために表示されます。これは Hello World アプリケーション用に意図された設定であるため、 AWS SAM CLI の続行を許可します。認可の設定の詳細については、「[AWS SAM テンプレートを使用して API アクセスを制御する](serverless-controlling-access-to-apis.md)」を参照してください。

   1. **引数を設定ファイルに保存** – これにより、アプリケーションの `samconfig.toml` ファイルがデプロイ設定で更新されます。

   1. デフォルトの**設定ファイル名**を選択します。

   1. デフォルトの**設定環境**を選択します。

   `sam deploy --guided` インタラクティブフローの出力例を次に示します。

   ```
   $ sam deploy --guided
   
   Configuring SAM deploy
   ======================
   
       Looking for config file [samconfig.toml] :  Found
       Reading default arguments  :  Success
   
       Setting default arguments for 'sam deploy'
       =========================================
       Stack Name [sam-app]: ENTER
       AWS Region [us-west-2]: ENTER
       #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
       Confirm changes before deploy [Y/n]: n
       #SAM needs permission to be able to create roles to connect to the resources in your template
       Allow SAM CLI IAM role creation [Y/n]: ENTER
       #Preserves the state of previously provisioned resources when an operation fails
       Disable rollback [y/N]: ENTER
       HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y
       Save arguments to configuration file [Y/n]: ENTER
       SAM configuration file [samconfig.toml]: ENTER
       SAM configuration environment [default]: ENTER
   ```

1. は、以下を実行してアプリケーションを AWS SAM CLIデプロイします。
   +  AWS SAM CLI は Amazon S3 バケットを作成し、`.aws-sam` ディレクトリをアップロードします。
   + は AWS SAM テンプレートを AWS SAM CLIに変換 CloudFormation し、 CloudFormation サービスにアップロードします。
   + CloudFormation は リソースをプロビジョニングします。

   デプロイ中、 AWS SAM CLI は進行状況を表示します。以下は、その出力例です。

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

これで、アプリケーションがデプロイされ、 で実行されます AWS クラウド。

## ステップ 4: アプリケーションを実行する
<a name="serverless-getting-started-hello-world-run"></a>

このステップでは、API エンドポイントに GET リクエストを送信し、Lambda 関数の出力を確認します。

**API エンドポイントの値を取得するには**

1. 前のステップで AWS SAM CLI によって表示された情報から、`Outputs` セクションを見つけます。このセクションで、`HelloWorldApi` リソースを見つけて HTTP エンドポイントの値を確認します。出力例を次に示します。

   ```
   ----------------------------------------------------------------------------------------------------------------------------------------------
   Outputs
   ----------------------------------------------------------------------------------------------------------------------------------------------
   ...
   Key                 HelloWorldApi
   Description         API Gateway endpoint URL for Prod stage for Hello World function
   Value               https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
   ...
   ----------------------------------------------------------------------------------------------------------------------------------------------
   ```

1. あるいは、**sam list endpoints --output json** コマンドを使用してこの情報を取得することもできます。出力例を次に示します。

   ```
   $ sam list endpoints --output json
   2023-03-15 12:39:19 Loading policies from IAM...
   2023-03-15 12:39:25 Finished loading policies from IAM.
   [
     {
       "LogicalResourceId": "HelloWorldFunction",
       "PhysicalResourceId": "sam-app-HelloWorldFunction-yQDNe17r9maD",
       "CloudEndpoint": "-",
       "Methods": "-"
     },
     {
       "LogicalResourceId": "ServerlessRestApi",
       "PhysicalResourceId": "ets1gv8lxi",
       "CloudEndpoint": [
         "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod",
         "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Stage"
       ],
       "Methods": [
         "/hello['get']"
       ]
     }
   ]
   ```

**関数を呼び出すには**
+ ブラウザまたはコマンドラインを使用して、API エンドポイントに GET リクエストを送信します。curl コマンドを使用した例を次に示します。

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

## ステップ 5: で 関数を操作する AWS クラウド
<a name="serverless-getting-started-hello-world-remote-invoke"></a>

このステップでは、 AWS SAM CLI を使用して AWS クラウド内の Lambda 関数を呼び出します。

**クラウド内の Lambda 関数を呼び出す**

1. 前のステップから、関数の `LogicalResourceId` を書き留めておきます。これは、`HelloWorldFunction` になります。

1. コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

   ```
   $ sam remote invoke HelloWorldFunction --stack-name sam-app
   ```

1. はクラウドで関数を AWS SAM CLI呼び出し、レスポンスを返します。以下は、その出力例です。

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

## ステップ 6: アプリケーションを変更して に同期する AWS クラウド
<a name="serverless-getting-started-hello-world-sync"></a>

このステップでは、 **sam sync --watch** コマンドを使用してローカルの変更を AWS SAM CLI に同期します AWS クラウド。

**sam sync を使用するには**

1. コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

   ```
   $ sam sync --watch
   ```

1.  AWS SAM CLI は、開発スタックを同期しようとしていることを確認するよう促すプロンプトを表示します。**sam sync --watch** コマンドはローカルの変更を AWS クラウド にリアルタイムで自動的にデプロイするため、開発環境にのみお勧めします。

    AWS SAM CLI は、ローカルの変更のモニタリングを開始する前に、初期デプロイを実行します。以下は、その出力例です。

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

次に、Lambda 関数のコードを変更します。 AWS SAM CLI は、この変更を自動的に検出し、アプリケーションを に同期します AWS クラウド。

**アプリケーションを変更して同期するには**

1. 選択した IDE で `sam-app/hello_world/app.py` ファイルを開きます。

1. `message` を変更してファイルを保存します。以下に例を示します。

   ```
   import json
   ...
   def lambda_handler(event, context):
       ...
       return {
           "statusCode": 200,
           "body": json.dumps({
               "message": "hello everyone!",
               ...
           }),
       }
   ```

1. は AWS SAM CLI変更を検出し、アプリケーションを に同期します AWS クラウド。以下は、その出力例です。

   ```
   Syncing Lambda Function HelloWorldFunction...
   Manifest is not changed for (HelloWorldFunction), running incremental build
   Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
   Running PythonPipBuilder:CopySource
   Finished syncing Lambda Function HelloWorldFunction.
   ```

1. 変更を確認するには、API エンドポイントに GET リクエストを再度送信します。

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

## ステップ 7: (オプション) アプリケーションをローカルでテストする
<a name="serverless-getting-started-hello-world-test"></a>

**注記**  
この手順は省略可能です。

**重要**  
このステップを使用するには、ローカルマシン上に Docker が必要です。ローカルテストに Docker  AWS SAMを使用するには、CLI をインストールして設定しておく必要があります。詳細については、「[Docker のインストール](install-docker.md)」を参照してください。

このステップでは、 **sam local** コマンドを使用して AWS SAM CLIアプリケーションをローカルでテストします。これを実現するために、 AWS SAM CLI は Docker を使用してローカル環境を作成します。このローカル環境は、Lambda 関数のクラウドベースの実行環境をエミュレートします。

以下の作業を実行します。

1. Lambda 関数のローカル環境を作成し、呼び出します。

1. HTTP API エンドポイントをローカルでホストし、それを使用して Lambda 関数を呼び出します。

**Lambda 関数をローカルで呼び出すには**

1. コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

   ```
   $ sam local invoke
   ```

1.  AWS SAM CLI はローカル Docker コンテナを作成し、関数を呼び出します。以下は、その出力例です。

   ```
   $ sam local invoke
   Invoking app.lambda_handler (python3.9)
   Local image was not found.
   Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9
   Building image.....................
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
   START RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 Version: $LATEST
   END RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6
   REPORT RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6    Init Duration: 1.01 ms    Duration: 633.45 ms    Billed Duration: 634 ms    Memory Size: 128 MB    Max Memory Used: 128 MB
   {"statusCode": 200, "body": "{\"message\": \"hello world\"}"}
   ```

**API をローカルでホストするには**

1. コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

   ```
   $ sam local start-api
   ```

1.  AWS SAM CLI は、Lambda 関数用にローカル Docker コンテナを作成し、API エンドポイントをシミュレートするローカル HTTP サーバーを作成します。以下は、その出力例です。

   ```
   $ sam local start-api
   Initializing the lambda functions containers.
   Local image is up-to-date
   Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64.
   
   Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
   Containers Initialization is done.
   Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]
   You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart AWS SAM CLI if you update your AWS SAM template
   2023-03-15 14:25:21 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
    * Running on http://127.0.0.1:3000
   2023-03-15 14:25:21 Press CTRL+C to quit
   ```

1. ブラウザまたはコマンドラインを使用して、ローカル API エンドポイントに GET リクエストを送信します。curl コマンドを使用した例を次に示します。

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

## ステップ 8: からアプリケーションを削除する AWS クラウド
<a name="serverless-getting-started-hello-world-delete"></a>

このステップでは、 **sam delete** コマンドを使用して AWS SAM CLI からアプリケーションを削除します AWS クラウド。

**からアプリケーションを削除するには AWS クラウド**

1. コマンドラインで、`sam-app` プロジェクトディレクトリから次を実行します。

   ```
   $ sam delete
   ```

1.  AWS SAM CLI から確認するよう求められます。次に、アプリケーションの Amazon S3 バケットと CloudFormation スタックが削除されます。出力例を次に示します。

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

## トラブルシューティング
<a name="serverless-getting-started-hello-world-troubleshoot"></a>

のトラブルシューティングについては AWS SAM CLI、「」を参照してください[AWS SAMCLI トラブルシューティング](sam-cli-troubleshooting.md)。

## 詳細情報
<a name="serverless-getting-started-hello-world-learn"></a>

詳細については AWS SAM、次のリソースを参照してください。
+ **[The Complete AWS SAM Workshop](https://s12d.com/sam-ws-en-intro)** – AWS SAM が提供する多くの主要機能を学べるように設計されたワークショップ。
+ **[ SAM を使用したセッション](https://www.youtube.com/playlist?list=PLJo-rJlep0ED198FJnTzhIB5Aut_1vDAd)** – AWS Serverless Developer Advocate チームによって作成された動画シリーズ AWS SAM。
+ **[Serverless Land](https://serverlessland.com/)** – AWS サーバーレスに関する最新情報、ブログ、動画、コード、学習リソースをまとめたサイト。