

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 步骤 3：创建生命周期挂钩 Lambda 函数
<a name="tutorial-ecs-with-hooks-create-hooks"></a>

在本部分中，您将为 Amazon ECS 部署的 `AfterAllowTestTraffic` 挂钩实施一个 Lambda 函数。在安装更新的 Amazon ECS 应用程序之前，Lambda 函数将运行验证测试。对于本教程，Lambda 函数返回 `Succeeded`。在实际部署过程中，验证测试可能返回 `Succeeded` 或 `Failed`，具体取决于验证测试的结果。此外，您可能会对其他 Amazon ECS 部署生命周期事件挂钩（`BeforeInstall`、`AfterInstall`、`BeforeAllowTraffic` 和 `AfterAllowTraffic`）中的一个或多个实施 Lambda 测试函数。有关更多信息，请参阅 [用于 Amazon ECS 部署的生命周期事件挂钩的列表](reference-appspec-file-structure-hooks.md#reference-appspec-file-structure-hooks-list-ecs)。

 必须具有 IAM 角色才能创建 Lambda 函数。该角色向 Lambda 函数授予写入 CloudWatch 日志和设置 CodeDeploy 生命周期挂钩状态的权限。

**创建 IAM 角色**

1. 使用 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 打开 IAM 控制台。

1. 从导航窗格中选择**角色**，然后选择**创建角色**。

1.  创建具有以下属性的角色：
   +  **Trusted entity（可信任的实体）**：**AWS Lambda**。
   +  **权限**：**AWSLambdaBasicExecutionRole**。这会授予您的 Lambda 函数写入日志的权限。 CloudWatch 
   +  **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 用户指南*和 [PutLifecycleEventHookExecutionStatusCodeDeploy ](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_PutLifecycleEventHookExecutionStatus.html)*API 参考*中的[添加 IAM 身份权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html#add-policies-console)。

**创建 `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。