

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 步驟 3：建立 lifecycle hook Lambda 函數
<a name="tutorial-ecs-with-hooks-create-hooks"></a>

在本節中，您會為 Amazon ECS 部署的`AfterAllowTestTraffic`掛鉤實作一個 Lambda 函數。Lambda 函數會在安裝更新的 Amazon ECS 應用程式之前執行驗證測試。在此教學課程中，Lambda 函數會傳回 `Succeeded`。在真實世界部署期間，驗證測試會傳回 `Succeeded` 或 `Failed`，取決於驗證測試的結果。此外，在實際部署期間，您可以為一或多個其他 Amazon ECS 部署生命週期事件掛鉤 (`BeforeInstall`、`BeforeAllowTraffic`、 `AfterInstall`和 ) 實作 Lambda 測試函數`AfterAllowTraffic`。如需詳細資訊，請參閱[Amazon ECS 部署的生命週期事件掛鉤清單](reference-appspec-file-structure-hooks.md#reference-appspec-file-structure-hooks-list-ecs)。

 建立 Lambda 函數需要 IAM 角色。此角色授予 Lambda 函數寫入 CloudWatch Logs 的許可，並設定 CodeDeploy 生命週期掛鉤的狀態。

**若要建立一個 IAM 角色**

1. 前往 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 開啟 IAM 主控台。

1. 從導覽窗格，選擇 **Roles (角色)**，然後選擇 **Create role (建立角色)**。

1.  建立具備下列屬性的角色：
   +  **Trusted entity (信任實體)**：**AWS Lambda**。
   +  **Permissions (許可)**：**AWSLambdaBasicExecutionRole**。這會授予 Lambda 函數寫入 CloudWatch Logs 的許可。
   +  **Role name (角色名稱)**：**`lambda-cli-hook-role`**。

   如需詳細資訊，請參閱[建立 AWS Lambda 執行角色](https://docs.aws.amazon.com/lambda/latest/dg/with-userapp.html#with-userapp-walkthrough-custom-events-create-iam-role)。

1.  將許可 `codedeploy:PutLifecycleEventHookExecutionStatus` 連接至您建立的角色。這會授予 Lambda 函數在部署期間設定 CodeDeploy 生命週期掛鉤狀態的許可。如需詳細資訊，請參閱*AWS Identity and Access Management 《 使用者指南*》中的[新增 IAM 身分許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html#add-policies-console)和《*CodeDeploy API 參考*》中的 [PutLifecycleEventHookExecutionStatus](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_PutLifecycleEventHookExecutionStatus.html)。

**建立`AfterAllowTestTraffic`勾點 Lambda 函數**

1.  使用下列內容建立名為 `AfterAllowTestTraffic.js` 的檔案。

   ```
   'use strict';
    
    const AWS = require('aws-sdk');
    const codedeploy = new AWS.CodeDeploy({apiVersion: '2014-10-06'});
    
    exports.handler = (event, context, callback) => {
    
    	console.log("Entering AfterAllowTestTraffic hook.");
    	
    	// Read the DeploymentId and LifecycleEventHookExecutionId from the event payload
     var deploymentId = event.DeploymentId;
    	var lifecycleEventHookExecutionId = event.LifecycleEventHookExecutionId;
    	var validationTestResult = "Failed";
    	
    	// Perform AfterAllowTestTraffic validation tests here. Set the test result 
    	// to "Succeeded" for this tutorial.
    	console.log("This is where AfterAllowTestTraffic validation tests happen.")
    	validationTestResult = "Succeeded";
    	
    	// Complete the AfterAllowTestTraffic hook by sending CodeDeploy the validation status
    	var params = {
    		deploymentId: deploymentId,
    		lifecycleEventHookExecutionId: lifecycleEventHookExecutionId,
    		status: validationTestResult // 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('AfterAllowTestTraffic validation tests failed');
    			console.log(err, err.stack);
    			callback("CodeDeploy Status update failed");
    		} else {
    			// Validation succeeded.
    			console.log("AfterAllowTestTraffic validation tests succeeded");
    			callback(null, "AfterAllowTestTraffic validation tests succeeded");
    		}
    	});
    }
   ```

1.  建立 Lambda 部署套件。

   ```
   zip AfterAllowTestTraffic.zip AfterAllowTestTraffic.js 
   ```

1.  使用 `create-function`命令為您的`AfterAllowTestTraffic`勾點建立 Lambda 函數。

   ```
   aws lambda create-function --function-name AfterAllowTestTraffic \
          --zip-file fileb://AfterAllowTestTraffic.zip \
          --handler AfterAllowTestTraffic.handler \
          --runtime nodejs10.x \
          --role arn:aws:iam::aws-account-id:role/lambda-cli-hook-role
   ```

1.  在`create-function`回應中記下您的 Lambda 函數 ARN。在下一個步驟中更新 CodeDeploy 部署的 AppSpec 檔案時，您會使用此 ARN。