

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Erstellen Sie Ihre Dateien
<a name="tutorial-lambda-create-files"></a>

 Um Ihre Infrastruktur zu erstellen, müssen Sie die folgenden Dateien erstellen: 
+ `template.yml`
+ `myDateTimeFunction.js`
+ `beforeAllowTraffic.js`
+ `afterAllowTraffic.js`

**Topics**
+ [Erstellen Sie Ihre AWS SAM-Vorlage](tutorial-lambda-sam-template.md)
+ [Erstellen Sie eine Datei für Ihre Lambda-Funktion](tutorial-lambda-sam-create-lambda-function.md)
+ [Erstellen Sie eine Datei für Ihre BeforeAllowTraffic Lambda-Funktion](tutorial-lambda-sam-create-lambda-before-traffic.md)
+ [Erstellen Sie eine Datei für Ihre AfterAllowTraffic Lambda-Funktion](tutorial-lambda-sam-create-lambda-after-traffic.md)

# Erstellen Sie Ihre AWS SAM-Vorlage
<a name="tutorial-lambda-sam-template"></a>

Erstellen Sie eine AWS SAM-Vorlagendatei, die die Komponenten in Ihrer Infrastruktur spezifiziert.

**Um Ihre AWS SAM-Vorlage zu erstellen**

1.  Erstellen Sie ein Verzeichnis mit dem Namen `SAM-Tutorial`. 

1.  Erstellen Sie in Ihrem Verzeichnis `SAM-Tutorial` eine Datei namens `template.yml`. 

1.  Kopieren Sie den folgenden YAML-Code in `template.yml`. Dies ist Ihre AWS SAM -Vorlage. 

   ```
   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
   ```

Diese Vorlage gibt Folgendes an. Weitere Informationen finden Sie unter [AWS SAM Vorlagenkonzepte](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-template-basics.html).

**Eine Lambda-Funktion namens `myDateTimeFunction`**  
 Wenn diese Lambda-Funktion veröffentlicht wird, verknüpft sie die `AutoPublishAlias` Zeile in der Vorlage mit einem Alias namens`live`. Später in diesem Tutorial löst ein Update dieser Funktion eine Bereitstellung aus, bei der der Produktionsdatenverkehr schrittweise von der Originalversion auf die aktualisierte Version verlagert wird. AWS CodeDeploy 

**Zwei Validierungsfunktionen für die Lambda-Bereitstellung**  
 Die folgenden Lambda-Funktionen werden während CodeDeploy Lifecycle-Hooks ausgeführt. Die Funktionen enthalten Code, der die Bereitstellung der aktualisierten `myDateTimeFunction` validiert. Das Ergebnis der Validierungstests wird mithilfe der `PutLifecycleEventHookExecutionStatus`-API-Methode an CodeDeploy übergeben. Wenn ein Validierungstest fehlschlägt, schlägt die Bereitstellung fehl und wird zurückgesetzt.   
+  `CodeDeployHook_beforeAllowTraffic` wird während des `BeforeAllowTraffic`-Hooks ausgeführt. 
+  `CodeDeployHook_afterAllowTraffic` wird während des `AfterAllowTraffic`-Hooks ausgeführt. 
Der Name beider Funktionen beginnt mit `CodeDeployHook_`. Die `CodeDeployRoleForLambda` Rolle erlaubt Aufrufe der `invoke` Lambda-Methode nur in Lambda-Funktionen, deren Namen mit diesem Präfix beginnen. Weitere Informationen finden Sie unter [AppSpec Abschnitt „Hooks“ für eine AWS Lambda-Bereitstellung](reference-appspec-file-structure-hooks.md#appspec-hooks-lambda) und [PutLifecycleEventHookExecutionStatus](https://docs.aws.amazon.com/codedeploy/latest/APIReference/API_PutLifecycleEventHookExecutionStatus.html) in der *CodeDeploy -API-Referenz*. 

**Automatische Erkennung einer aktualisierten Lambda-Funktion**  
 Der `AutoPublishAlias`-Begriff weist das Framework an, zu erkennen, wenn sich die `myDateTimeFunction`-Funktion ändert, und sie dann mit dem `live`-Alias bereitzustellen. 

**Eine Bereitstellungskonfiguration**  
 Die Bereitstellungskonfiguration bestimmt die Geschwindigkeit, mit der Ihre CodeDeploy Anwendung den Datenverkehr von der ursprünglichen Version der Lambda-Funktion auf die neue Version verlagert. Diese Vorlage gibt die vordefinierte Bereitstellungskonfiguration `Linear10PercentEvery1Minute` an.   
 Sie können keine benutzerdefinierte Bereitstellungskonfiguration in einer AWS SAM-Vorlage angeben. Weitere Informationen finden Sie unter [Erstellen Sie eine Bereitstellungskonfiguration mit CodeDeploy](deployment-configurations-create.md).

**Funktionen von Bereitstellungslebenszyklus-Hooks**  
 Der `Hooks`-Abschnitt gibt die Funktionen an, die während Lebenszyklusereignis-Hooks ausgeführt werden. `PreTraffic` gibt die Funktion an, die während des `BeforeAllowTraffic`-Hooks ausgeführt wird. `PostTraffic` gibt die Funktion an, die während des `AfterAllowTraffic`-Hooks ausgeführt wird. 

**Berechtigungen für Lambda zum Aufrufen einer anderen Lambda-Funktion**  
 Die angegebene `lambda:InvokeFunction` Berechtigung gewährt der von der AWS SAM-Anwendung verwendeten Rolle die Berechtigung, eine Lambda-Funktion aufzurufen. Dies ist erforderlich, wenn die `CodeDeployHook_afterAllowTraffic` Funktionen `CodeDeployHook_beforeAllowTraffic` und die bereitgestellte Lambda-Funktion während der Validierungstests aufrufen. 

# Erstellen Sie eine Datei für Ihre Lambda-Funktion
<a name="tutorial-lambda-sam-create-lambda-function"></a>

Erstellen Sie die Datei für die Funktion, die Sie später in diesem Tutorial aktualisieren und bereitstellen.

**Anmerkung**  
 Eine Lambda-Funktion kann jede Laufzeit verwenden, die von AWS Lambda unterstützt wird. Weitere Informationen finden Sie unter [AWS Lambda -Laufzeiten](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html). 

**Um Ihre Lambda-Funktion zu erstellen**

1.  Erstellen Sie eine Textdatei und speichern Sie sie als `myDateTimeFunction.js` im `SAM-Tutorial`-Verzeichnis. 

1.  Kopieren Sie den folgenden Node.js-Code in `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;
         }
       };
   ```

Die Lambda-Funktion gibt den Tag, den Monat und das Jahr für gestern, heute oder morgen zurück. Später in diesem Tutorial entfernen Sie die Kommentarzeichen von Code, der die Funktion aktualisiert, um Informationen über den Tag oder die Uhrzeit zurückzugeben, die Sie angeben (z. B. Tag, Monat und Jahr oder die aktuelle Stunde, Minute und Sekunde). Das von erstellte Framework AWS SAM erkennt die aktualisierte Version der Funktion und stellt sie bereit. 

**Anmerkung**  
 Diese Lambda-Funktion wird auch in einem AWS Cloud9 Tutorial verwendet. AWS Cloud9 ist eine cloudbasierte integrierte Entwicklungsumgebung. Informationen zum Erstellen, Ausführen, Aktualisieren und Debuggen dieser Funktion finden Sie unter [AWS Lambda Tutorial für AWS Cloud9](https://docs.aws.amazon.com/cloud9/latest/user-guide/tutorial-lambda.html). AWS Cloud9

# Erstellen Sie eine Datei für Ihre BeforeAllowTraffic Lambda-Funktion
<a name="tutorial-lambda-sam-create-lambda-before-traffic"></a>

Erstellen Sie die Datei für Ihre `beforeAllowTraffic` Hook-Lambda-Funktion.

1.  Erstellen Sie eine Textdatei und speichern Sie sie als `beforeAllowTraffic.js` im `SAM-Tutorial`-Verzeichnis. 

1.  Kopieren Sie den folgenden Node.js-Code in `beforeAllowTraffic.js`. Diese Funktion wird während des `BeforeAllowTraffic`-Hooks Ihrer Bereitstellung ausgeführt. 

   ```
   '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");
       				}
       			});
       		}  
       	});
       }
   ```

# Erstellen Sie eine Datei für Ihre AfterAllowTraffic Lambda-Funktion
<a name="tutorial-lambda-sam-create-lambda-after-traffic"></a>

Erstellen Sie die Datei für Ihre `afterAllowTraffic` Hook-Lambda-Funktion.

1.  Erstellen Sie eine Textdatei und speichern Sie sie als `afterAllowTraffic.js` im `SAM-Tutorial`-Verzeichnis. 

1.  Kopieren Sie den folgenden Node.js-Code in `afterAllowTraffic.js`. Diese Funktion wird während des `AfterAllowTraffic`-Hooks Ihrer Bereitstellung ausgeführt. 

   ```
   '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");
       				}
       			});
       		}  
       	});
       }
   ```