Tutorial: Eine serverlose Hello World-Anwendung erstellen - AWS Cloud Development Kit (AWS CDK) v2

Dies ist der AWS CDK v2-Entwicklerhandbuch. Das ältere CDK v1 wurde am 1. Juni 2022 in die Wartung aufgenommen und der Support wurde am 1. Juni 2023 eingestellt.

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.

Tutorial: Eine serverlose Hello World-Anwendung erstellen

In diesem Tutorial verwenden Sie die, AWS Cloud Development Kit (AWS CDK) um ein einfaches serverloses System zu erstellen Hello World Anwendung, die ein grundlegendes API-Backend implementiert, das aus folgenden Komponenten besteht:

  • Amazon API Gateway REST API— Stellt einen HTTP-Endpunkt bereit, der verwendet wird, um Ihre Funktion über einen aufzurufen HTTP GET Anfrage.

  • AWS Lambda Funktion — Funktion, die eine Hello World! Nachricht zurückgibt, wenn sie mit dem aufgerufen wird HTTP Endpunkt.

  • Integrationen und Berechtigungen — Konfigurationsdetails und Berechtigungen für Ihre Ressourcen, miteinander zu interagieren und Aktionen auszuführen, wie z. B. das Schreiben von Protokollen an Amazon CloudWatch.

Das folgende Diagramm zeigt die Komponenten dieser Anwendung:

Diagramm einer Lambda-Funktion, die aufgerufen wird, wenn Sie eine GET-Anfrage an den API-Gateway-Endpunkt senden.

In diesem Tutorial werden Sie Ihre Anwendung in den folgenden Schritten erstellen und mit ihr interagieren:

  1. Erstellen Sie ein AWS CDK Projekt.

  2. Definieren Sie eine Lambda-Funktion und eine API-Gateway-REST-API mithilfe von L2-Konstrukten aus der AWS Construct-Bibliothek.

  3. Stellen Sie Ihre Anwendung auf dem bereit. AWS Cloud

  4. Interagieren Sie mit Ihrer Anwendung in der AWS Cloud.

  5. Löschen Sie die Beispielanwendung aus dem AWS Cloud.

Voraussetzungen

Bevor Sie mit diesem Tutorial beginnen, müssen Sie folgende Aufgaben ausführen:

  • Erstellen Sie ein AWS-Konto und lassen Sie das AWS Command Line Interface (AWS CLI) installieren und konfigurieren.

  • Installieren Node.js and npm.

  • Installieren Sie das CDK Toolkit global mit. npm install -g aws-cdk

Weitere Informationen finden Sie unter Erste Schritte mit dem AWS CDK.

Wir empfehlen außerdem ein grundlegendes Verständnis der folgenden Themen:

Schritt 1: Erstellen Sie ein CDK-Projekt

In diesem Schritt erstellen Sie ein neues CDK-Projekt mit dem AWS CDK CLI cdk initBefehl.

Um ein CDK-Projekt zu erstellen
  1. Erstellen Sie von einem Startverzeichnis Ihrer Wahl aus ein Projektverzeichnis mit dem Namen cdk-hello-world auf Ihrem Computer und navigieren Sie zu diesem:

    $ mkdir cdk-hello-world && cd cdk-hello-world
  2. Verwenden Sie den cdk init Befehl, um ein neues Projekt in Ihrer bevorzugten Programmiersprache zu erstellen:

    TypeScript
    $ cdk init --language typescript

    AWS CDK Bibliotheken installieren:

    $ npm install aws-cdk-lib constructs
    JavaScript
    $ cdk init --language javascript

    AWS CDK Bibliotheken installieren:

    $ npm install aws-cdk-lib constructs
    Python
    $ cdk init --language python

    Aktivieren Sie die virtuelle Umgebung:

    $ source .venv/bin/activate # On Windows, run '.\venv\Scripts\activate' instead

    AWS CDK Bibliotheken und Projektabhängigkeiten installieren:

    (.venv)$ python3 -m pip install -r requirements.txt
    Java
    $ cdk init --language java

    AWS CDK Bibliotheken und Projektabhängigkeiten installieren:

    $ mvn package
    C#
    $ cdk init --language csharp

    AWS CDK Bibliotheken und Projektabhängigkeiten installieren:

    $ dotnet restore src
    Go
    $ cdk init --language go

    Installieren Sie Projektabhängigkeiten:

    $ go get github.com/aws/aws-cdk-go/awscdk/v2 $ go get github.com/aws/aws-cdk-go/awscdk/v2/awslambda $ go get github.com/aws/aws-cdk-go/awscdk/v2/awsapigateway $ go mod tidy

    Das CDK CLI erstellt ein Projekt mit der folgenden Struktur:

    TypeScript
    cdk-hello-world ├── .git ├── .gitignore ├── .npmignore ├── README.md ├── bin │ └── cdk-hello-world.ts ├── cdk.json ├── jest.config.js ├── lib │ └── cdk-hello-world-stack.ts ├── node_modules ├── package-lock.json ├── package.json ├── test │ └── cdk-hello-world.test.ts └── tsconfig.json
    JavaScript
    cdk-hello-world ├── .git ├── .gitignore ├── .npmignore ├── README.md ├── bin │ └── cdk-hello-world.js ├── cdk.json ├── jest.config.js ├── lib │ └── cdk-hello-world-stack.js ├── node_modules ├── package-lock.json ├── package.json └── test └── cdk-hello-world.test.js
    Python
    cdk-hello-world ├── .git ├── .gitignore ├── .venv ├── README.md ├── app.py ├── cdk.json ├── cdk_hello_world │ ├── __init__.py │ └── cdk_hello_world_stack.py ├── requirements-dev.txt ├── requirements.txt ├── source.bat └── tests
    Java
    cdk-hello-world ├── .git ├── .gitignore ├── README.md ├── cdk.json ├── pom.xml ├── src │ ├── main │ │ └── java │ │ └── com │ │ └── myorg │ │ ├── CdkHelloWorldApp.java │ │ └── CdkHelloWorldStack.java └── target
    C#
    cdk-hello-world ├── .git ├── .gitignore ├── README.md ├── cdk.json └── src ├── CdkHelloWorld │ ├── CdkHelloWorld.csproj │ ├── CdkHelloWorldStack.cs │ ├── GlobalSuppressions.cs │ └── Program.cs └── CdkHelloWorld.sln
    Go
    cdk-hello-world ├── .git ├── .gitignore ├── README.md ├── cdk-hello-world.go ├── cdk-hello-world_test.go ├── cdk.json ├── go.mod └── go.sum

Das CDK CLI erstellt automatisch eine CDK-App, die einen einzelnen Stack enthält. Die CDK-App-Instanz wird aus der App Klasse erstellt. Das Folgende ist ein Teil Ihrer CDK-Anwendungsdatei:

TypeScript

Befindet sich inbin/cdk-hello-world.ts:

#!/usr/bin/env node import 'source-map-support/register'; import * as cdk from 'aws-cdk-lib'; import { CdkHelloWorldStack } from '../lib/cdk-hello-world-stack'; const app = new cdk.App(); new CdkHelloWorldStack(app, 'CdkHelloWorldStack', { });
JavaScript

Befindet sich inbin/cdk-hello-world.js:

#!/usr/bin/env node const cdk = require('aws-cdk-lib'); const { CdkHelloWorldStack } = require('../lib/cdk-hello-world-stack'); const app = new cdk.App(); new CdkHelloWorldStack(app, 'CdkHelloWorldStack', { });
Python

Befindet sich inapp.py:

#!/usr/bin/env python3 import os import aws_cdk as cdk from cdk_hello_world.cdk_hello_world_stack import CdkHelloWorldStack app = cdk.App() CdkHelloWorldStack(app, "CdkHelloWorldStack",) app.synth()
Java

Befindet sich insrc/main/java/.../CdkHelloWorldApp.java:

package com.myorg; import software.amazon.awscdk.App; import software.amazon.awscdk.Environment; import software.amazon.awscdk.StackProps; import java.util.Arrays; public class JavaApp { public static void main(final String[] args) { App app = new App(); new JavaStack(app, "JavaStack", StackProps.builder() .build()); app.synth(); } }
C#

Befindet sich insrc/CdkHelloWorld/Program.cs:

using Amazon.CDK; using System; using System.Collections.Generic; using System.Linq; namespace CdkHelloWorld { sealed class Program { public static void Main(string[] args) { var app = new App(); new CdkHelloWorldStack(app, "CdkHelloWorldStack", new StackProps { }); app.Synth(); } } }
Go

Befindet sich incdk-hello-world.go:

package main import ( "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/constructs-go/constructs/v10" "github.com/aws/jsii-runtime-go" ) // ... func main() { defer jsii.Close() app := awscdk.NewApp(nil) NewCdkHelloWorldStack(app, "CdkHelloWorldStack", &CdkHelloWorldStackProps{ awscdk.StackProps{ Env: env(), }, }) app.Synth(nil) } func env() *awscdk.Environment { return nil }

Schritt 2: Erstellen Sie Ihre Lambda-Funktion

Erstellen Sie in Ihrem CDK-Projekt ein lambda Verzeichnis, das eine neue hello.js Datei enthält. Im Folgenden wird ein Beispiel gezeigt:

TypeScript

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mkdir lambda && cd lambda $ touch hello.js

Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:

cdk-hello-world └── lambda └── hello.js
JavaScript

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mkdir lambda && cd lambda $ touch hello.js

Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:

cdk-hello-world └── lambda └── hello.js
Python

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mkdir lambda && cd lambda $ touch hello.js

Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:

cdk-hello-world └── lambda └── hello.js
Java

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mkdir -p src/main/resources/lambda $ cd src/main/resources/lambda $ touch hello.js

Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:

cdk-hello-world └── src └── main └──resources └──lambda └──hello.js
C#

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mkdir lambda && cd lambda $ touch hello.js

Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:

cdk-hello-world └── lambda └── hello.js
Go

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mkdir lambda && cd lambda $ touch hello.js

Folgendes sollte jetzt zu Ihrem CDK-Projekt hinzugefügt werden:

cdk-hello-world └── lambda └── hello.js
Anmerkung

Um dieses Tutorial einfach zu halten, verwenden wir JavaScript Lambda-Funktion für alle CDK-Programmiersprachen.

Definieren Sie Ihre Lambda-Funktion, indem Sie der neu erstellten Datei Folgendes hinzufügen:

exports.handler = async (event) => { return { statusCode: 200, headers: { "Content-Type": "text/plain" }, body: JSON.stringify({ message: "Hello, World!" }), }; };

Schritt 3: Definieren Sie Ihre Konstrukte

In diesem Schritt definieren Sie Ihre Lambda- und API-Gateway-Ressourcen mithilfe von AWS CDK L2-Konstrukten.

Öffnen Sie die Projektdatei, die Ihren CDK-Stack definiert. Sie werden diese Datei ändern, um Ihre Konstrukte zu definieren. Das Folgende ist ein Beispiel für Ihre Start-Stack-Datei:

TypeScript

Befindet sich inlib/cdk-hello-world-stack.ts:

import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; export class CdkHelloWorldStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // Your constructs will go here } }
JavaScript

Befindet sich inlib/cdk-hello-world-stack.js:

const { Stack, Duration } = require('aws-cdk-lib'); const lambda = require('aws-cdk-lib/aws-lambda'); const apigateway = require('aws-cdk-lib/aws-apigateway'); class CdkHelloWorldStack extends Stack { constructor(scope, id, props) { super(scope, id, props); // Your constructs will go here } } module.exports = { CdkHelloWorldStack }
Python

Befindet sich incdk_hello_world/cdk_hello_world_stack.py:

from aws_cdk import Stack from constructs import Construct class CdkHelloWorldStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) // Your constructs will go here
Java

Befindet sich insrc/main/java/.../CdkHelloWorldStack.java:

package com.myorg; import software.constructs.Construct; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; public class CdkHelloWorldStack extends Stack { public CdkHelloWorldStack(final Construct scope, final String id) { this(scope, id, null); } public CdkHelloWorldStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); // Your constructs will go here } }
C#

Befindet sich insrc/CdkHelloWorld/CdkHelloWorldStack.cs:

using Amazon.CDK; using Constructs; namespace CdkHelloWorld { public class CdkHelloWorldStack : Stack { internal CdkHelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // Your constructs will go here } } }
Go

Befindet sich incdk-hello-world.go:

package main import ( "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/constructs-go/constructs/v10" "github.com/aws/jsii-runtime-go" ) type CdkHelloWorldStackProps struct { awscdk.StackProps } func NewCdkHelloWorldStack(scope constructs.Construct, id string, props *CdkHelloWorldStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) // Your constructs will go here return stack } func main() { // ... } func env() *awscdk.Environment { return nil }

In dieser Datei AWS CDK macht der Folgendes:

  • Ihre CDK-Stack-Instanz wird aus der Klasse instanziiert. Stack

  • Die Constructs Basisklasse wird importiert und als Bereich oder übergeordnetes Objekt Ihrer Stack-Instance bereitgestellt.

Definieren Sie Ihre Lambda-Funktionsressource

Um Ihre Lambda-Funktionsressource zu definieren, importieren und verwenden Sie das aws-lambda L2-Konstrukt aus der AWS Construct-Bibliothek.

Ändern Sie Ihre Stack-Datei wie folgt:

TypeScript
import * as cdk from 'aws-cdk-lib'; import { Construct } from 'constructs'; // Import Lambda L2 construct import * as lambda from 'aws-cdk-lib/aws-lambda'; export class CdkHelloWorldStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // Define the Lambda function resource const helloWorldFunction = new lambda.Function(this, 'HelloWorldFunction', { runtime: lambda.Runtime.NODEJS_20_X, // Choose any supported Node.js runtime code: lambda.Code.fromAsset('lambda'), // Points to the lambda directory handler: 'hello.handler', // Points to the 'hello' file in the lambda directory }); } }
JavaScript
const { Stack, Duration } = require('aws-cdk-lib'); // Import Lambda L2 construct const lambda = require('aws-cdk-lib/aws-lambda'); class CdkHelloWorldStack extends Stack { constructor(scope, id, props) { super(scope, id, props); // Define the Lambda function resource const helloWorldFunction = new lambda.Function(this, 'HelloWorldFunction', { runtime: lambda.Runtime.NODEJS_20_X, // Choose any supported Node.js runtime code: lambda.Code.fromAsset('lambda'), // Points to the lambda directory handler: 'hello.handler', // Points to the 'hello' file in the lambda directory }); } } module.exports = { CdkHelloWorldStack }
Python
from aws_cdk import ( Stack, # Import Lambda L2 construct aws_lambda as _lambda, ) # ... class CdkHelloWorldStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # Define the Lambda function resource hello_world_function = _lambda.Function( self, "HelloWorldFunction", runtime = _lambda.Runtime.NODEJS_20_X, # Choose any supported Node.js runtime code = _lambda.Code.from_asset("lambda"), # Points to the lambda directory handler = "hello.handler", # Points to the 'hello' file in the lambda directory )
Anmerkung

Wir importieren das aws_lambda Modul, _lambda weil es ein eingebauter Bezeichner lambda ist Python.

Java
// ... // Import Lambda L2 construct import software.amazon.awscdk.services.lambda.Code; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.Runtime; public class CdkHelloWorldStack extends Stack { public CdkHelloWorldStack(final Construct scope, final String id) { this(scope, id, null); } public CdkHelloWorldStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); // Define the Lambda function resource Function helloWorldFunction = Function.Builder.create(this, "HelloWorldFunction") .runtime(Runtime.NODEJS_20_X) // Choose any supported Node.js runtime .code(Code.fromAsset("src/main/resources/lambda")) // Points to the lambda directory .handler("hello.handler") // Points to the 'hello' file in the lambda directory .build(); } }
C#
// ... // Import Lambda L2 construct using Amazon.CDK.AWS.Lambda; namespace CdkHelloWorld { public class CdkHelloWorldStack : Stack { internal CdkHelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // Define the Lambda function resource var helloWorldFunction = new Function(this, "HelloWorldFunction", new FunctionProps { Runtime = Runtime.NODEJS_20_X, // Choose any supported Node.js runtime Code = Code.FromAsset("lambda"), // Points to the lambda directory Handler = "hello.handler" // Points to the 'hello' file in the lambda directory }); } } }
Go
package main import ( // ... // Import Lambda L2 construct "github.com/aws/aws-cdk-go/awscdk/v2/awslambda" // Import S3 assets construct "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" // ... ) // ... func NewCdkHelloWorldStack(scope constructs.Construct, id string, props *CdkHelloWorldStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) // Define the Lambda function resource helloWorldFunction := awslambda.NewFunction(stack, jsii.String("HelloWorldFunction"), &awslambda.FunctionProps{ Runtime: awslambda.Runtime_NODEJS_20_X(), // Choose any supported Node.js runtime Code: awslambda.Code_FromAsset(jsii.String("lambda"), &awss3assets.AssetOptions{}), // Points to the lambda directory Handler: jsii.String("hello.handler"), // Points to the 'hello' file in the lambda directory }) return stack } // ...

Hier erstellen Sie eine Lambda-Funktionsressource und definieren die folgenden Eigenschaften:

  • runtime— Die Umgebung, in der die Funktion ausgeführt wird. Hier verwenden wir Node.js version 20.x.

  • code— Der Pfad zum Funktionscode auf Ihrem lokalen Computer.

  • handler— Der Name der spezifischen Datei, die Ihren Funktionscode enthält.

Definieren Sie Ihr API Gateway REST API Ressource

Um Ihr API Gateway zu definieren REST API Ressource, importieren und verwenden Sie das aws-apigateway L2-Konstrukt aus der AWS Construct-Bibliothek.

Ändern Sie Ihre Stack-Datei wie folgt:

TypeScript
// ... //Import API Gateway L2 construct import * as apigateway from 'aws-cdk-lib/aws-apigateway'; export class CdkHelloWorldStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); // ... // Define the API Gateway resource const api = new apigateway.LambdaRestApi(this, 'HelloWorldApi', { handler: helloWorldFunction, proxy: false, }); // Define the '/hello' resource with a GET method const helloResource = api.root.addResource('hello'); helloResource.addMethod('GET'); } }
JavaScript
// ... // Import API Gateway L2 construct const apigateway = require('aws-cdk-lib/aws-apigateway'); class CdkHelloWorldStack extends Stack { constructor(scope, id, props) { super(scope, id, props); // ... // Define the API Gateway resource const api = new apigateway.LambdaRestApi(this, 'HelloWorldApi', { handler: helloWorldFunction, proxy: false, }); // Define the '/hello' resource with a GET method const helloResource = api.root.addResource('hello'); helloResource.addMethod('GET'); }; }; // ...
Python
from aws_cdk import ( # ... # Import API Gateway L2 construct aws_apigateway as apigateway, ) from constructs import Construct class CdkHelloWorldStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) # ... # Define the API Gateway resource api = apigateway.LambdaRestApi( self, "HelloWorldApi", handler = hello_world_function, proxy = False, ) # Define the '/hello' resource with a GET method hello_resource = api.root.add_resource("hello") hello_resource.add_method("GET")
Java
// ... // Import API Gateway L2 construct import software.amazon.awscdk.services.apigateway.LambdaRestApi; import software.amazon.awscdk.services.apigateway.Resource; public class CdkHelloWorldStack extends Stack { public CdkHelloWorldStack(final Construct scope, final String id) { this(scope, id, null); } public CdkHelloWorldStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); // ... // Define the API Gateway resource LambdaRestApi api = LambdaRestApi.Builder.create(this, "HelloWorldApi") .handler(helloWorldFunction) .proxy(false) // Turn off default proxy integration .build(); // Define the '/hello' resource and its GET method Resource helloResource = api.getRoot().addResource("hello"); helloResource.addMethod("GET"); } }
C#
// ... // Import API Gateway L2 construct using Amazon.CDK.AWS.APIGateway; namespace CdkHelloWorld { public class CdkHelloWorldStack : Stack { internal CdkHelloWorldStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { // ... // Define the API Gateway resource var api = new LambdaRestApi(this, "HelloWorldApi", new LambdaRestApiProps { Handler = helloWorldFunction, Proxy = false }); // Add a '/hello' resource with a GET method var helloResource = api.Root.AddResource("hello"); helloResource.AddMethod("GET"); } } }
Go

// ... import ( // ... // Import Api Gateway L2 construct "github.com/aws/aws-cdk-go/awscdk/v2/awsapigateway" // ... ) // ... func NewCdkHelloWorldStack(scope constructs.Construct, id string, props *CdkHelloWorldStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) // Define the Lambda function resource // ... // Define the API Gateway resource api := awsapigateway.NewLambdaRestApi(stack, jsii.String("HelloWorldApi"), &awsapigateway.LambdaRestApiProps{ Handler: helloWorldFunction, Proxy: jsii.Bool(false), }) // Add a '/hello' resource with a GET method helloResource := api.Root().AddResource(jsii.String("hello"), &awsapigateway.ResourceOptions{}) helloResource.AddMethod(jsii.String("GET"), awsapigateway.NewLambdaIntegration(helloWorldFunction, &awsapigateway.LambdaIntegrationOptions{}), &awsapigateway.MethodOptions{}) return stack } // ...

Hier erstellen Sie ein API Gateway REST API Ressource, zusammen mit dem Folgenden:

  • Eine Integration zwischen REST API und Ihre Lambda-Funktion, sodass die API Ihre Funktion aufrufen kann. Dies beinhaltet die Erstellung einer Lambda-Berechtigungsressource.

  • Eine neue Ressource oder ein neuer Pfad mit dem Namenhello, der dem Stamm des API-Endpunkts hinzugefügt wird. Dadurch wird ein neuer Endpunkt erstellt, der /hello Ihre Basis erweitert URL.

  • Eine GET-Methode für die hello Ressource. Wenn eine GET-Anfrage an den /hello Endpunkt gesendet wird, wird die Lambda-Funktion aufgerufen und ihre Antwort zurückgegeben.

Schritt 4: Bereiten Sie Ihre Anwendung für die Bereitstellung vor

In diesem Schritt bereiten Sie Ihre Anwendung für die Bereitstellung vor, indem Sie, falls erforderlich, eine grundlegende Validierung mit dem erstellen und durchführen AWS CDK CLI cdk synthBefehl.

Falls erforderlich, erstellen Sie Ihre Anwendung:

TypeScript

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ npm run build
JavaScript

Ein Gebäude ist nicht erforderlich.

Python

Ein Gebäude ist nicht erforderlich.

Java

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ mvn package
C#

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ dotnet build src
Go

Ein Gebäude ist nicht erforderlich.

Führen Sie auscdk synth, um eine AWS CloudFormation Vorlage aus Ihrem CDK-Code zu synthetisieren. Durch die Verwendung von L2-Konstrukten sind viele der Konfigurationsdetails erforderlich, AWS CloudFormation um die Interaktion zwischen Ihrer Lambda-Funktion und REST API werden von der für Sie bereitgestellt. AWS CDK

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus:

$ cdk synth
Anmerkung

Wenn Sie eine Fehlermeldung wie die folgende erhalten, überprüfen Sie, ob Sie sich im cdk-hello-world Verzeichnis befinden, und versuchen Sie es erneut:

--app is required either in command-line, in cdk.json or in ~/.cdk.json

Falls erfolgreich, AWS CDK CLI gibt die AWS CloudFormation Vorlage aus in YAML formatieren Sie in der Befehlszeile. A JSON Die formatierte Vorlage wird ebenfalls im cdk.out Verzeichnis gespeichert.

Im Folgenden finden Sie ein Beispiel für die Ausgabe der AWS CloudFormation Vorlage:

Resources: HelloWorldFunctionServiceRoleunique-identifier: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Statement: - Action: sts:AssumeRole Effect: Allow Principal: Service: lambda.amazonaws.com Version: "2012-10-17" ManagedPolicyArns: - Fn::Join: - "" - - "arn:" - Ref: AWS::Partition - :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldFunction/ServiceRole/Resource HelloWorldFunctionunique-identifier: Type: AWS::Lambda::Function Properties: Code: S3Bucket: Fn::Sub: cdk-unique-identifier-assets-${AWS::AccountId}-${AWS::Region} S3Key: unique-identifier.zip Handler: hello.handler Role: Fn::GetAtt: - HelloWorldFunctionServiceRoleunique-identifier - Arn Runtime: nodejs20.x DependsOn: - HelloWorldFunctionServiceRoleunique-identifier Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldFunction/Resource aws:asset:path: asset.unique-identifier aws:asset:is-bundled: false aws:asset:property: Code HelloWorldApiunique-identifier: Type: AWS::ApiGateway::RestApi Properties: Name: HelloWorldApi Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Resource HelloWorldApiDeploymentunique-identifier: Type: AWS::ApiGateway::Deployment Properties: Description: Automatically created by the RestApi construct RestApiId: Ref: HelloWorldApiunique-identifier DependsOn: - HelloWorldApihelloGETunique-identifier - HelloWorldApihellounique-identifier Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Deployment/Resource HelloWorldApiDeploymentStageprod012345ABC: Type: AWS::ApiGateway::Stage Properties: DeploymentId: Ref: HelloWorldApiDeploymentunique-identifier RestApiId: Ref: HelloWorldApiunique-identifier StageName: prod Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/DeploymentStage.prod/Resource HelloWorldApihellounique-identifier: Type: AWS::ApiGateway::Resource Properties: ParentId: Fn::GetAtt: - HelloWorldApiunique-identifier - RootResourceId PathPart: hello RestApiId: Ref: HelloWorldApiunique-identifier Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/Resource HelloWorldApihelloGETApiPermissionCdkHelloWorldStackHelloWorldApiunique-identifier: Type: AWS::Lambda::Permission Properties: Action: lambda:InvokeFunction FunctionName: Fn::GetAtt: - HelloWorldFunctionunique-identifier - Arn Principal: apigateway.amazonaws.com SourceArn: Fn::Join: - "" - - "arn:" - Ref: AWS::Partition - ":execute-api:" - Ref: AWS::Region - ":" - Ref: AWS::AccountId - ":" - Ref: HelloWorldApi9E278160 - / - Ref: HelloWorldApiDeploymentStageprodunique-identifier - /GET/hello Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/GET/ApiPermission.CdkHelloWorldStackHelloWorldApiunique-identifier.GET..hello HelloWorldApihelloGETApiPermissionTestCdkHelloWorldStackHelloWorldApiunique-identifier: Type: AWS::Lambda::Permission Properties: Action: lambda:InvokeFunction FunctionName: Fn::GetAtt: - HelloWorldFunctionunique-identifier - Arn Principal: apigateway.amazonaws.com SourceArn: Fn::Join: - "" - - "arn:" - Ref: AWS::Partition - ":execute-api:" - Ref: AWS::Region - ":" - Ref: AWS::AccountId - ":" - Ref: HelloWorldApiunique-identifier - /test-invoke-stage/GET/hello Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/GET/ApiPermission.Test.CdkHelloWorldStackHelloWorldApiunique-identifier.GET..hello HelloWorldApihelloGETunique-identifier: Type: AWS::ApiGateway::Method Properties: AuthorizationType: NONE HttpMethod: GET Integration: IntegrationHttpMethod: POST Type: AWS_PROXY Uri: Fn::Join: - "" - - "arn:" - Ref: AWS::Partition - ":apigateway:" - Ref: AWS::Region - :lambda:path/2015-03-31/functions/ - Fn::GetAtt: - HelloWorldFunctionunique-identifier - Arn - /invocations ResourceId: Ref: HelloWorldApihellounique-identifier RestApiId: Ref: HelloWorldApiunique-identifier Metadata: aws:cdk:path: CdkHelloWorldStack/HelloWorldApi/Default/hello/GET/Resource CDKMetadata: Type: AWS::CDK::Metadata Properties: Analytics: v2:deflate64:unique-identifier Metadata: aws:cdk:path: CdkHelloWorldStack/CDKMetadata/Default Condition: CDKMetadataAvailable Outputs: HelloWorldApiEndpointunique-identifier: Value: Fn::Join: - "" - - https:// - Ref: HelloWorldApiunique-identifier - .execute-api. - Ref: AWS::Region - "." - Ref: AWS::URLSuffix - / - Ref: HelloWorldApiDeploymentStageprodunique-identifier - / Conditions: CDKMetadataAvailable: Fn::Or: - Fn::Or: - Fn::Equals: - Ref: AWS::Region - af-south-1 - Fn::Equals: - Ref: AWS::Region - ap-east-1 - Fn::Equals: - Ref: AWS::Region - ap-northeast-1 - Fn::Equals: - Ref: AWS::Region - ap-northeast-2 - Fn::Equals: - Ref: AWS::Region - ap-south-1 - Fn::Equals: - Ref: AWS::Region - ap-southeast-1 - Fn::Equals: - Ref: AWS::Region - ap-southeast-2 - Fn::Equals: - Ref: AWS::Region - ca-central-1 - Fn::Equals: - Ref: AWS::Region - cn-north-1 - Fn::Equals: - Ref: AWS::Region - cn-northwest-1 - Fn::Or: - Fn::Equals: - Ref: AWS::Region - eu-central-1 - Fn::Equals: - Ref: AWS::Region - eu-north-1 - Fn::Equals: - Ref: AWS::Region - eu-south-1 - Fn::Equals: - Ref: AWS::Region - eu-west-1 - Fn::Equals: - Ref: AWS::Region - eu-west-2 - Fn::Equals: - Ref: AWS::Region - eu-west-3 - Fn::Equals: - Ref: AWS::Region - il-central-1 - Fn::Equals: - Ref: AWS::Region - me-central-1 - Fn::Equals: - Ref: AWS::Region - me-south-1 - Fn::Equals: - Ref: AWS::Region - sa-east-1 - Fn::Or: - Fn::Equals: - Ref: AWS::Region - us-east-1 - Fn::Equals: - Ref: AWS::Region - us-east-2 - Fn::Equals: - Ref: AWS::Region - us-west-1 - Fn::Equals: - Ref: AWS::Region - us-west-2 Parameters: BootstrapVersion: Type: AWS::SSM::Parameter::Value<String> Default: /cdk-bootstrap/hnb659fds/version Description: Version of the CDK Bootstrap resources in this environment, automatically retrieved from SSM Parameter Store. [cdk:skip] Rules: CheckBootstrapVersion: Assertions: - Assert: Fn::Not: - Fn::Contains: - - "1" - "2" - "3" - "4" - "5" - Ref: BootstrapVersion AssertDescription: CDK bootstrap stack version 6 required. Please run 'cdk bootstrap' with a recent version of the CDK CLI.

Mithilfe von L2-Konstrukten definieren Sie einige Eigenschaften, um Ihre Ressourcen zu konfigurieren, und verwenden Hilfsmethoden, um sie miteinander zu integrieren. Das AWS CDK konfiguriert den Großteil Ihrer AWS CloudFormation Ressourcen und Eigenschaften, die für die Bereitstellung Ihrer Anwendung erforderlich sind.

Schritt 5: Ihre Anwendung bereitstellen

In diesem Schritt verwenden Sie den AWS CDK CLI cdk deployBefehl zum Bereitstellen Ihrer Anwendung. Der AWS CDK arbeitet mit dem AWS CloudFormation Dienst zusammen, um Ihre Ressourcen bereitzustellen.

Wichtig

Sie müssen vor der Bereitstellung ein einmaliges Bootstrapping Ihrer AWS Umgebung durchführen. Detaillierte Anweisungen finden Sie unter Bootstrap Ihre Umgebung für die Verwendung mit dem AWS CDK.

Führen Sie im Stammverzeichnis Ihres Projekts Folgendes aus. Bestätigen Sie Änderungen, wenn Sie dazu aufgefordert werden:

$ cdk deploy ✨ Synthesis time: 2.44s ... Do you wish to deploy these changes (y/n)? y

Wenn die Bereitstellung abgeschlossen ist, AWS CDK CLI gibt Ihre Endpunkt-URL aus. Kopieren Sie diese URL für den nächsten Schritt. Im Folgenden wird ein Beispiel gezeigt:

... ✅ HelloWorldStack ✨ Deployment time: 45.37s Outputs: HelloWorldStack.HelloWorldApiEndpointunique-identifier = https://<api-id>.execute-api.<region>.amazonaws.com/prod/ Stack ARN: arn:aws:cloudformation:region:account-id:stack/HelloWorldStack/unique-identifier ...

Schritt 6: Interagieren Sie mit Ihrer Anwendung

In diesem Schritt initiieren Sie eine GET-Anfrage an Ihren API-Endpunkt und erhalten Ihre Lambda-Funktionsantwort.

Suchen Sie Ihre Endpunkt-URL aus dem vorherigen Schritt und fügen Sie den /hello Pfad hinzu. Senden Sie dann über Ihren Browser oder die Befehlszeile eine GET-Anfrage an Ihren Endpunkt. Im Folgenden wird ein Beispiel gezeigt:

$ curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/hello {"message":"Hello World!"}%

Herzlichen Glückwunsch! Sie haben Ihre Anwendung erfolgreich mit dem erstellt, bereitgestellt und mit ihr interagiert! AWS CDK

Schritt 7: Löschen Sie Ihre Anwendung

In diesem Schritt verwenden Sie AWS CDK CLI um Ihre Bewerbung aus dem zu löschen AWS Cloud.

Um Ihre Anwendung zu löschen, führen Sie den Befehl auscdk destroy. Wenn Sie dazu aufgefordert werden, bestätigen Sie Ihre Anfrage zum Löschen der Anwendung:

$ cdk destroy Are you sure you want to delete: CdkHelloWorldStack (y/n)? y CdkHelloWorldStack: destroying... [1/1] ... ✅ CdkHelloWorldStack: destroyed

Fehlerbehebung

Fehler: {„Nachricht“: „Interner Serverfehler“}%

Wenn Sie die bereitgestellte Lambda-Funktion aufrufen, erhalten Sie diesen Fehler. Dieser Fehler kann aus mehreren Gründen auftreten.

Um weitere Fehler zu beheben

Verwenden Sie die AWS CLI , um Ihre Lambda-Funktion aufzurufen.

  1. Ändern Sie Ihre Stack-Datei, um den Ausgabewert Ihres bereitgestellten Lambda-Funktionsnamens zu erfassen. Im Folgenden wird ein Beispiel gezeigt:

    ... class CdkHelloWorldStack extends Stack { constructor(scope, id, props) { super(scope, id, props); // Define the Lambda function resource // ... new CfnOutput(this, 'HelloWorldFunctionName', { value: helloWorldFunction.functionName, description: 'JavaScript Lambda function' }); // Define the API Gateway resource // ...
  2. Stellen Sie Ihre Anwendung erneut bereit. Das AWS CDK CLI gibt den Wert Ihres bereitgestellten Lambda-Funktionsnamens aus:

    $ cdk deploy ✨ Synthesis time: 0.29s ... ✅ CdkHelloWorldStack ✨ Deployment time: 20.36s Outputs: ... CdkHelloWorldStack.HelloWorldFunctionName = CdkHelloWorldStack-HelloWorldFunctionunique-identifier ...
  3. Verwenden Sie die AWS CLI , um Ihre Lambda-Funktion in der aufzurufen AWS Cloud und die Antwort in eine Textdatei auszugeben:

    $ aws lambda invoke --function-name CdkHelloWorldStack-HelloWorldFunctionunique-identifier output.txt
  4. Überprüfen Sieoutput.txt, um Ihre Ergebnisse zu sehen.

Mögliche Ursache: Die API-Gateway-Ressource ist in Ihrer Stack-Datei falsch definiert.

Wenn eine erfolgreiche Lambda-Funktionsantwort output.txt angezeigt wird, liegt das Problem möglicherweise daran, wie Sie Ihre API-Gateway-REST-API definiert haben. Das AWS CLI ruft Ihr Lambda direkt auf, nicht über Ihren Endpunkt. Überprüfen Sie Ihren Code, um sicherzustellen, dass er mit diesem Tutorial übereinstimmt. Stellen Sie es dann erneut bereit.

Mögliche Ursache: Die Lambda-Ressource ist in Ihrer Stack-Datei falsch definiert.

Wenn ein Fehler output.txt zurückgegeben wird, liegt das Problem möglicherweise daran, wie Sie Ihre Lambda-Funktion definiert haben. Überprüfen Sie Ihren Code, um sicherzustellen, dass er mit diesem Tutorial übereinstimmt. Stellen Sie es dann erneut bereit.