为您的 BeforeAllowTraffic Lambda 函数创建一个文件 - Amazon CodeDeploy
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

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

为您的 BeforeAllowTraffic Lambda 函数创建一个文件

beforeAllowTraffic 挂钩 Lambda 函数创建文件。

  1. 创建文本文件,并以 beforeAllowTraffic.js 文件形式保存到 SAM-Tutorial 目录中。

  2. 将以下 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"); } }); } }); }