

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

# ファイルを作成する
<a name="tutorial-lambda-create-files"></a>

 インフラストラクチャを作成するには、次のファイルを作成する必要があります。
+ `template.yml`
+ `myDateTimeFunction.js`
+ `beforeAllowTraffic.js`
+ `afterAllowTraffic.js`

**Topics**
+ [AWS SAM テンプレートを作成する](tutorial-lambda-sam-template.md)
+ [Lambda 関数のファイルを作成します](tutorial-lambda-sam-create-lambda-function.md)
+ [[BeforeAllowTraffic] Lambda 関数のファイルを作成する](tutorial-lambda-sam-create-lambda-before-traffic.md)
+ [[AfterAllowTraffic] Lambda 関数のファイルを作成する](tutorial-lambda-sam-create-lambda-after-traffic.md)

# AWS SAM テンプレートを作成する
<a name="tutorial-lambda-sam-template"></a>

インフラストラクチャ内のコンポーネントを指定する AWS SAM テンプレートファイルを作成します。

**AWS SAM テンプレートを作成するには**

1.  `SAM-Tutorial` という名前のディレクトリを作成します。

1.  `SAM-Tutorial` ディレクトリに `template.yml` という名前のファイルを作成します。

1.  次の YAML コードを `template.yml` にコピーします。これが使用する AWS SAM テンプレートです。

   ```
   AWSTemplateFormatVersion : '2010-09-09'
   Transform: AWS::Serverless-2016-10-31
   Description: A sample SAM template for deploying Lambda functions.
   
   Resources:
   # Details about the myDateTimeFunction Lambda function
     myDateTimeFunction:
       Type: AWS::Serverless::Function
       Properties:
         Handler: myDateTimeFunction.handler
         Runtime: nodejs18.x
   # Instructs your myDateTimeFunction is published to an alias named "live".      
         AutoPublishAlias: live
   # Grants this function permission to call lambda:InvokeFunction
         Policies:
           - Version: "2012-10-17"		 	 	 
             Statement: 
             - Effect: "Allow"
               Action: 
                 - "lambda:InvokeFunction"
               Resource: '*'
         DeploymentPreference:
   # Specifies the deployment configuration      
             Type: Linear10PercentEvery1Minute
   # Specifies Lambda functions for deployment lifecycle hooks
             Hooks:
               PreTraffic: !Ref beforeAllowTraffic
               PostTraffic: !Ref afterAllowTraffic
               
   # Specifies the BeforeAllowTraffic lifecycle hook Lambda function
     beforeAllowTraffic:
       Type: AWS::Serverless::Function
       Properties:
         Handler: beforeAllowTraffic.handler
         Policies:
           - Version: "2012-10-17"		 	 	 
   # Grants this function permission to call codedeploy:PutLifecycleEventHookExecutionStatus        
             Statement: 
             - Effect: "Allow"
               Action: 
                 - "codedeploy:PutLifecycleEventHookExecutionStatus"
               Resource:
                 !Sub 'arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
           - Version: "2012-10-17"		 	 	 
   # Grants this function permission to call lambda:InvokeFunction        
             Statement: 
             - Effect: "Allow"
               Action: 
                 - "lambda:InvokeFunction"
               Resource: !Ref myDateTimeFunction.Version
         Runtime: nodejs18.x
   # Specifies the name of the Lambda hook function      
         FunctionName: 'CodeDeployHook_beforeAllowTraffic'
         DeploymentPreference:
           Enabled: false
         Timeout: 5
         Environment:
           Variables:
             NewVersion: !Ref myDateTimeFunction.Version
             
   # Specifies the AfterAllowTraffic lifecycle hook Lambda function
     afterAllowTraffic:
       Type: AWS::Serverless::Function
       Properties:
         Handler: afterAllowTraffic.handler
         Policies:
           - Version: "2012-10-17"		 	 	 
             Statement: 
   # Grants this function permission to call codedeploy:PutLifecycleEventHookExecutionStatus         
             - Effect: "Allow"
               Action: 
                 - "codedeploy:PutLifecycleEventHookExecutionStatus"
               Resource:
                 !Sub 'arn:aws:codedeploy:${AWS::Region}:${AWS::AccountId}:deploymentgroup:${ServerlessDeploymentApplication}/*'
           - Version: "2012-10-17"		 	 	 
             Statement: 
   # Grants this function permission to call lambda:InvokeFunction          
             - Effect: "Allow"
               Action: 
                 - "lambda:InvokeFunction"
               Resource: !Ref myDateTimeFunction.Version
         Runtime: nodejs18.x
   # Specifies the name of the Lambda hook function      
         FunctionName: 'CodeDeployHook_afterAllowTraffic'
         DeploymentPreference:
           Enabled: false
         Timeout: 5
         Environment:
           Variables:
             NewVersion: !Ref myDateTimeFunction.Version
   ```

このテンプレートは以下を指定します。詳細については、[AWS SAM template concepts (テンプレートの概念)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html) を参照してください。

**`myDateTimeFunction` と呼ばれるLambda 関数**  
 この Lambda 関数が発行されると、テンプレート中の `AutoPublishAlias` の行は、それを `live` という名前のエイリアスにリンクします。このチュートリアルの後半で、この関数の更新により、本番トラフィックを元のバージョンから更新されたバージョンに段階的に移行 AWS CodeDeploy する によるデプロイがトリガーされます。

**2 つの Lambda デプロイ検証関数**  
 次の Lambda 関数は、CodeDeploy ライフサイクルフック中に実行されます。関数には、更新された `myDateTimeFunction` のデプロイを検証するコードが含まれています。検証テストの結果は、`PutLifecycleEventHookExecutionStatus` のAPI メソッドを使用して CodeDeploy に渡されます。検証テストが失敗すると、デプロイは失敗し、ロールバックされます。  
+  `CodeDeployHook_beforeAllowTraffic` は、`BeforeAllowTraffic` フック中に実行します。
+  `CodeDeployHook_afterAllowTraffic` は、`AfterAllowTraffic` フック中に実行します。
両方の関数の名前は `CodeDeployHook_` で始まります。`CodeDeployRoleForLambda` のロールは、このプレフィックスで始まる名前の Lambda 関数でのみ、Lambda の `invoke` のメソッドへの呼び出しを許可します。詳細については、[AWS Lambda デプロイの AppSpec 'hooks' セクション](reference-appspec-file-structure-hooks.md#appspec-hooks-lambda) および *CodeDeploy API Reference* 中の [PutLifecycleEventHookExecutionStatus](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_PutLifecycleEventHookExecutionStatus.html) を参照してください。

**更新された Lambda 関数の自動検出**  
 `AutoPublishAlias` 条件は、`myDateTimeFunction` 関数が変更されたときに検出し、`live` エイリアスを使用してデプロイするようにフレームワークに指示します。

**デプロイ設定**  
 デプロイ設定により、CodeDeploy アプリケーションが Lambda 関数の元のバージョンから新しいバージョンにトラフィックを移行するレートが決まります。このテンプレートは、事前定義されたデプロイ設定 `Linear10PercentEvery1Minute` を指定します。  
 AWS SAM テンプレートでカスタムデプロイ設定を指定することはできません。詳細については、「[CodeDeploy を使用してデプロイ設定を作成する](deployment-configurations-create.md)」を参照してください。

**デプロイライフサイクルフック関数**  
 `Hooks` セクションでは、ライフサイクルイベントフック中に実行する関数を指定します。`PreTraffic` は、`PostTraffic` フック中に実行する関数を指定します。`BeforeAllowTraffic` は、フック中に `AfterAllowTraffic` が実行する関数を指定します。

**Lambda が別の Lambda 関数を呼び出すための許可**  
 指定された`lambda:InvokeFunction`アクセス許可は、SAM AWS アプリケーションで使用されるロールに Lambda 関数を呼び出すアクセス許可を付与します。これは、`CodeDeployHook_beforeAllowTraffic` および `CodeDeployHook_afterAllowTraffic` の関数が、検証テスト中に、デプロイされた Lambda 関数を呼び出す場合に必要です。

# Lambda 関数のファイルを作成します
<a name="tutorial-lambda-sam-create-lambda-function"></a>

このチュートリアルの後半で更新してデプロイする関数のファイルを作成します。

**注記**  
 Lambda 関数は、 AWS Lambdaでサポートされている任意のランタイムを使用できます。詳細については、「[AWS Lambda ランタイム](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)」を参照してください。

**Lambda 関数を作成するには**

1.  テキストファイルを作成し、`myDateTimeFunction.js` という名前で `SAM-Tutorial` ディレクトリに保存します。

1.  次の Node.js コードを `myDateTimeFunction.js` にコピーします。

   

   ```
   'use strict';
       
       exports.handler = function(event, context, callback) {
       
         if (event.body) {
           event = JSON.parse(event.body);
         }
       
         var sc; // Status code
         var result = ""; // Response payload
       
         switch(event.option) {
           case "date": 
             switch(event.period) {
               case "yesterday":
                 result = setDateResult("yesterday");
                 sc = 200;
                 break;
               case "today":
                 result = setDateResult();
                 sc = 200;
                 break;
               case "tomorrow":
                 result = setDateResult("tomorrow");
                 sc = 200;
                 break;
               default:
                 result = {
                   "error": "Must specify 'yesterday', 'today', or 'tomorrow'."
                 };
                 sc = 400;
                 break;
             }
             break;
             
       /*      Later in this tutorial, you update this function by uncommenting 
               this section. The framework created by AWS SAM detects the update 
               and triggers a deployment by CodeDeploy. The deployment shifts 
               production traffic to the updated version of this function.
               
               case "time":
               var d = new Date();
               var h = d.getHours();
               var mi = d.getMinutes();
               var s = d.getSeconds();
       
               result = {
                 "hour": h,
                 "minute": mi,
                 "second": s
               };
               sc = 200;
               break;
       */
             default:
               result = {
                 "error": "Must specify 'date' or 'time'."
               };
               sc = 400;
             break;
         }
       
         const response = {
           statusCode: sc,
           headers: { "Content-type": "application/json" },
           body: JSON.stringify( result )
         };
       
         callback(null, response);
       
         function setDateResult(option) {
       
           var d = new Date(); // Today
           var mo; // Month
           var da; // Day
           var y; // Year
       
           switch(option) {
             case "yesterday":
               d.setDate(d.getDate() - 1);
               break;
             case "tomorrow":
               d.setDate(d.getDate() + 1);
             default:
              break;
           }
       
           mo = d.getMonth() + 1; // Months are zero offset (0-11)
           da = d.getDate();
           y = d.getFullYear();
       
           result = {
             "month": mo,
             "day": da,
             "year": y
           };
       
           return result;
         }
       };
   ```

Lambda 関数は、昨日、今日、または明日に対して年月日を返します。このチュートリアルの後半では、指定した日または時間に関する情報(年月日または現在の時、分、秒など)を返す関数を更新するコードをコメント解除します。によって作成されたフレームワークは、関数の更新バージョン AWS SAM を検出してデプロイします。

**注記**  
 この Lambda 関数は、 AWS Cloud9 チュートリアルでも使用されます。 はクラウドベースの統合開発環境 AWS Cloud9 です。でこの関数を作成、実行、更新、デバッグする方法については AWS Cloud9、[AWS Lambda 「」のチュートリアル AWS Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/tutorial-lambda.html)を参照してください。

# [BeforeAllowTraffic] Lambda 関数のファイルを作成する
<a name="tutorial-lambda-sam-create-lambda-before-traffic"></a>

`beforeAllowTraffic` のフック Lambda 関数のファイルを作成します。

1.  テキストファイルを作成し、`beforeAllowTraffic.js` という名前で `SAM-Tutorial` ディレクトリに保存します。

1.  次の Node.js コードを `beforeAllowTraffic.js` にコピーします。この関数は、デプロイの `BeforeAllowTraffic` フック中に実行されます。

   ```
   'use strict';
       
       const AWS = require('aws-sdk'); 
       const codedeploy = new AWS.CodeDeploy({apiVersion: '2014-10-06'});
       var lambda = new AWS.Lambda();
       
       exports.handler = (event, context, callback) => {
       
       	console.log("Entering PreTraffic Hook!");
       	
       	// Read the DeploymentId and LifecycleEventHookExecutionId from the event payload
         var deploymentId = event.DeploymentId;
       	var lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;
       
       	var functionToTest = process.env.NewVersion;
       	console.log("BeforeAllowTraffic hook tests started");
       	console.log("Testing new function version: " + functionToTest);
       
       	// Create parameters to pass to the updated Lambda function that
       	// include the newly added "time" option. If the function did not
       	// update, then the "time" option is invalid and function returns
       	// a statusCode of 400 indicating it failed.
       	var lambdaParams = {
       		FunctionName: functionToTest,    
       		Payload: "{\"option\": \"time\"}", 
       		InvocationType: "RequestResponse"
       	};
       
       	var lambdaResult = "Failed";
       	// Invoke the updated Lambda function.
       	lambda.invoke(lambdaParams, function(err, data) {
       		if (err){	// an error occurred
       			console.log(err, err.stack);
       			lambdaResult = "Failed";
       		}
       		else{	// successful response
       			var result = JSON.parse(data.Payload);
       			console.log("Result: " +  JSON.stringify(result));
             console.log("statusCode: " + result.statusCode);
             
             // Check if the status code returned by the updated
             // function is 400. If it is, then it failed. If 
             // is not, then it succeeded.
       			if (result.statusCode != "400"){
               console.log("Validation succeeded");
       				lambdaResult = "Succeeded";
             }
             else {
               console.log("Validation failed");
             }
       
       			// Complete the PreTraffic Hook by sending CodeDeploy the validation status
       			var params = {
       				deploymentId: deploymentId,
       				lifecycleEventHookExecutionId: lifecycleEventHookExecutionId,
       				status: lambdaResult // status can be 'Succeeded' or 'Failed'
       			};
       			
       			// Pass CodeDeploy the prepared validation test results.
       			codedeploy.putLifecycleEventHookExecutionStatus(params, function(err, data) {
       				if (err) {
       					// Validation failed.
       					console.log("CodeDeploy Status update failed");
       					console.log(err, err.stack);
       					callback("CodeDeploy Status update failed");
       				} else {
       					// Validation succeeded.
       					console.log("CodeDeploy status updated successfully");
       					callback(null, "CodeDeploy status updated successfully");
       				}
       			});
       		}  
       	});
       }
   ```

# [AfterAllowTraffic] Lambda 関数のファイルを作成する
<a name="tutorial-lambda-sam-create-lambda-after-traffic"></a>

`afterAllowTraffic` のフック Lambda 関数のファイルを作成します。

1.  テキストファイルを作成し、`afterAllowTraffic.js` という名前で `SAM-Tutorial` ディレクトリに保存します。

1.  次の Node.js コードを `afterAllowTraffic.js` にコピーします。この関数は、デプロイの `AfterAllowTraffic` フック中に実行されます。

   ```
   'use strict';
       
       const AWS = require('aws-sdk');
       const codedeploy = new AWS.CodeDeploy({apiVersion: '2014-10-06'});
       var lambda = new AWS.Lambda();
       
       exports.handler = (event, context, callback) => {
       
       	console.log("Entering PostTraffic Hook!");
       	
       	// Read the DeploymentId and LifecycleEventHookExecutionId from the event payload
         var deploymentId = event.DeploymentId;
       	var lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;
       
       	var functionToTest = process.env.NewVersion;
       	console.log("AfterAllowTraffic hook tests started");
       	console.log("Testing new function version: " + functionToTest);
       
       	// Create parameters to pass to the updated Lambda function that
       	// include the original "date" parameter. If the function did not 
       	// update as expected, then the "date" option might be invalid. If 
       	// the parameter is invalid, the function returns
       	// a statusCode of 400 indicating it failed.
       	var lambdaParams = {
       		FunctionName: functionToTest,    
       		Payload: "{\"option\": \"date\", \"period\": \"today\"}", 
       		InvocationType: "RequestResponse"
       	};
       
       	var lambdaResult = "Failed";
       	// Invoke the updated Lambda function.
       	lambda.invoke(lambdaParams, function(err, data) {
       		if (err){	// an error occurred
       			console.log(err, err.stack);
       			lambdaResult = "Failed";
       		}
       		else{	// successful response
       			var result = JSON.parse(data.Payload);
       			console.log("Result: " +  JSON.stringify(result));
             console.log("statusCode: " + result.statusCode);
             
             // Check if the status code returned by the updated
             // function is 400. If it is, then it failed. If 
             // is not, then it succeeded.
       			if (result.statusCode != "400"){
               console.log("Validation of time parameter succeeded");
       				lambdaResult = "Succeeded";
             }
             else {
               console.log("Validation failed");
             }
       
       			// Complete the PostTraffic Hook by sending CodeDeploy the validation status
       			var params = {
       				deploymentId: deploymentId,
       				lifecycleEventHookExecutionId: lifecycleEventHookExecutionId,
       				status: lambdaResult // status can be 'Succeeded' or 'Failed'
       			};
       			
       			// Pass CodeDeploy the prepared validation test results.
       			codedeploy.putLifecycleEventHookExecutionStatus(params, function(err, data) {
       				if (err) {
       					// Validation failed.
       					console.log("CodeDeploy Status update failed");
       					console.log(err, err.stack);
       					callback("CodeDeploy Status update failed");
       				} else {
       					// Validation succeeded.
       					console.log("CodeDeploy status updated successfully");
       					callback(null, "CodeDeploy status updated successfully");
       				}
       			});
       		}  
       	});
       }
   ```