AWS CDK v2 개발자 안내서입니다. 구형 CDK v1은 2022년 6월 1일에 유지 보수에 들어갔고 2023년 6월 1일에 지원이 종료되었습니다.
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
서버리스 헬로월드 애플리케이션 만들기
이 자습서에서는 를 사용하여 다음과 같이 구성된 기본 API 백엔드를 구현하는 간단한 서버리스 Hello World 애플리케이션을 만듭니다. AWS Cloud Development Kit (AWS CDK)
-
Amazon API Gateway REST API — HTTP GET 요청을 통해 함수를 호출하는 데 사용되는 HTTP 엔드포인트를 제공합니다.
-
AWS Lambda 함수 - 엔드포인트와 함께 호출될 때 Hello World!
메시지를 반환하는 함수입니다. HTTP
-
통합 및 권한 — 리소스가 서로 상호 작용하고 CloudWatch Amazon에 로그를 쓰는 등의 작업을 수행할 수 있는 구성 세부 정보 및 권한
다음 다이어그램은 이 애플리케이션의 구성 요소를 보여줍니다.
이 자습서에서는 다음 단계에 따라 애플리케이션을 생성하고 애플리케이션과 상호 작용해 보겠습니다.
-
AWS CDK 프로젝트 만들기.
-
구성 라이브러리의 L2 구조를 사용하여 Lambda 함수와 API Gateway REST API를 정의합니다. AWS
-
에 애플리케이션을 배포하십시오. AWS 클라우드
-
에서 애플리케이션과 상호 작용하십시오 AWS 클라우드.
-
AWS 클라우드에서 샘플 애플리케이션을 삭제합니다.
필수 조건
이 자습서를 시작하기 전에 다음을 완료하십시오.
자세한 정보는 시작하기 AWS CDK을 참조하세요.
또한 다음 사항에 대한 기본적인 이해를 권장합니다.
1단계: CDK 프로젝트 만들기
이 단계에서는 명령어를 사용하여 새 CDK 프로젝트를 만듭니다. AWS CDK CLI cdk init
CDK 프로젝트를 만들려면
-
선택한 시작 디렉터리에서 cdk-hello-world
컴퓨터에 이름이 지정된 프로젝트 디렉터리를 만들고 탐색합니다.
$
mkdir cdk-hello-world && cd cdk-hello-world
-
cdk init
명령을 사용하여 원하는 프로그래밍 언어로 새 프로젝트를 생성하십시오.
- TypeScript
-
$
cdk init --language typescript
AWS CDK 라이브러리 설치:
$
npm install aws-cdk-lib constructs
- JavaScript
-
$
cdk init --language javascript
AWS CDK 라이브러리 설치:
$
npm install aws-cdk-lib constructs
- Python
-
$
cdk init --language python
가상 환경 활성화:
$
source .venv/bin/activate
# On Windows, run '.\venv\Scripts\activate' instead
AWS CDK 라이브러리 및 프로젝트 종속성 설치:
(.venv)$
python3 -m pip install -r requirements.txt
- Java
-
$
cdk init --language java
AWS CDK 라이브러리 및 프로젝트 종속성 설치:
$
mvn package
- C#
-
$
cdk init --language csharp
AWS CDK 라이브러리 및 프로젝트 종속성 설치:
$
dotnet restore src
- Go
-
$
cdk init --language go
프로젝트 종속성 설치:
$
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
CLICDK는 다음과 같은 구조의 프로젝트를 생성합니다.
- 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
CDK는 단일 스택이 포함된 CDK 앱을 CLI 자동으로 생성합니다. CDK 앱 인스턴스는 클래스에서 생성됩니다. App
다음은 CDK 애플리케이션 파일의 일부입니다.
- TypeScript
-
위치: bin/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
-
위치bin/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
-
위치app.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
-
위치src/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#
-
위치src/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
-
위치cdk-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
}
2단계: Lambda 함수 생성
CDK 프로젝트 내에서 새 파일이 포함된 lambda
디렉토리를 생성하십시오. hello.js
다음은 그 예제입니다.
- TypeScript
-
프로젝트 루트에서 다음을 실행합니다.
$
mkdir lambda && cd lambda
$
touch hello.js
이제 다음을 CDK 프로젝트에 추가해야 합니다.
cdk-hello-world
└── lambda
└── hello.js
- JavaScript
-
프로젝트 루트에서 다음을 실행하세요.
$
mkdir lambda && cd lambda
$
touch hello.js
이제 다음을 CDK 프로젝트에 추가해야 합니다.
cdk-hello-world
└── lambda
└── hello.js
- Python
-
프로젝트 루트에서 다음을 실행하세요.
$
mkdir lambda && cd lambda
$
touch hello.js
이제 다음을 CDK 프로젝트에 추가해야 합니다.
cdk-hello-world
└── lambda
└── hello.js
- Java
-
프로젝트 루트에서 다음을 실행하세요.
$
mkdir -p src/main/resources/lambda
$
cd src/main/resources/lambda
$
touch hello.js
이제 다음을 CDK 프로젝트에 추가해야 합니다.
cdk-hello-world
└── src
└── main
└──resources
└──lambda
└──hello.js
- C#
-
프로젝트 루트에서 다음을 실행하세요.
$
mkdir lambda && cd lambda
$
touch hello.js
이제 다음을 CDK 프로젝트에 추가해야 합니다.
cdk-hello-world
└── lambda
└── hello.js
- Go
-
프로젝트 루트에서 다음을 실행하세요.
$
mkdir lambda && cd lambda
$
touch hello.js
이제 다음을 CDK 프로젝트에 추가해야 합니다.
cdk-hello-world
└── lambda
└── hello.js
이 자습서를 간단하게 하기 위해 모든 CDK 프로그래밍 JavaScript 언어에 Lambda 함수를 사용합니다.
새로 생성된 파일에 다음을 추가하여 Lambda 함수를 정의합니다.
exports.handler = async (event) => {
return {
statusCode: 200,
headers: { "Content-Type": "text/plain" },
body: JSON.stringify({ message: "Hello, World!" }),
};
};
3단계: 구문 정의
이 단계에서는 L2 구조를 사용하여 Lambda 및 API Gateway 리소스를 AWS CDK 정의합니다.
CDK 스택을 정의하는 프로젝트 파일을 엽니다. 이 파일을 수정하여 구문을 정의합니다. 다음은 시작 스택 파일의 예입니다.
- TypeScript
-
위치lib/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
-
위치lib/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
-
위치cdk_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
-
위치src/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#
-
위치src/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
-
위치cdk-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
}
이 파일에서 AWS CDK 는 다음과 같은 작업을 수행합니다.
Lambda 함수 리소스를 정의하십시오.
Lambda 함수 리소스를 정의하려면 구성 라이브러리에서 L2 구문을 가져와서 사용합니다aws-lambda
. AWS
다음과 같이 스택 파일을 수정하십시오.
- 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
)
aws_lambda
모듈을 임포트하는 lambda
이유는 내장 식별자가 있기 _lambda
때문입니다. 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
}
// ...
여기에서 Lambda 함수 리소스를 생성하고 다음 속성을 정의합니다.
-
runtime
— 함수가 실행되는 환경. 여기서는 Node.js 버전을 사용합니다20.x.
-
code
— 로컬 컴퓨터에 있는 함수 코드의 경로.
-
handler
— 함수 코드가 들어 있는 특정 파일의 이름.
API Gateway REST API 리소스 정의
API Gateway REST API 리소스를 정의하려면 AWS 구성 라이브러리에서 aws-apigateway
L2 구문을 가져와 사용합니다.
다음과 같이 스택 파일을 수정합니다.
- 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
}
// ...
여기에서 다음과 함께 API Gateway REST API 리소스를 생성합니다.
-
Lambda 함수와 Lambda 함수를 통합하여 API가 함수를 호출할 수 있도록 합니다. REST API 여기에는 Lambda 권한 리소스 생성이 포함됩니다.
-
API 엔드포인트의 루트에 hello
추가되는 이름이 지정된 새 리소스 또는 경로. 그러면 기본 엔드포인트가 /hello
추가되는 새 엔드포인트가 생성됩니다URL.
-
hello
리소스의 GET 메서드. GET 요청이 /hello
엔드포인트로 전송되면 Lambda 함수가 호출되고 해당 응답이 반환됩니다.
4단계: 배포를 위한 애플리케이션 준비
이 단계에서는 필요한 경우 AWS CDK CLI cdk synth
명령을 사용하여 빌드하고 기본 검증을 수행하여 배포할 애플리케이션을 준비합니다.
필요한 경우 애플리케이션을 빌드하세요.
- TypeScript
-
프로젝트 루트에서 다음을 실행합니다.
$
npm run build
- JavaScript
-
빌드는 필요하지 않습니다.
- Python
-
건물은 필요하지 않습니다.
- Java
-
프로젝트 루트에서 다음을 실행하세요.
$
mvn package
- C#
-
프로젝트 루트에서 다음을 실행합니다.
$
dotnet build src
- Go
-
빌드는 필요하지 않습니다.
cdk synth
를 실행하면 CDK 코드에서 AWS CloudFormation 템플릿을 합성할 수 있습니다. L2 구조를 사용하면 Lambda 함수와 Lambda 함수 간의 상호 작용을 촉진하는 AWS CloudFormation 데 필요한 많은 구성 세부 정보가 에서 자동으로 REST API 프로비저닝됩니다. AWS CDK
프로젝트의 루트에서 다음을 실행합니다.
$
cdk synth
다음과 같은 오류가 발생하면 cdk-hello-world
디렉터리에 있는지 확인하고 다시 시도하세요.
--app is required either in command-line, in cdk.json or in ~/.cdk.json
성공하면 명령 프롬프트에 AWS CloudFormation 템플릿이 YAML 형식으로 출력됩니다. AWS CDK CLI JSON형식이 지정된 템플릿도 cdk.out
디렉터리에 저장됩니다.
다음은 AWS CloudFormation 템플릿의 출력 예제입니다.
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.
L2 구문을 사용하면 몇 가지 속성을 정의하여 리소스를 구성하고 도우미 메서드를 사용하여 리소스를 통합할 수 있습니다. 는 AWS CDK 애플리케이션을 프로비저닝하는 데 필요한 대부분의 AWS CloudFormation 리소스와 속성을 구성합니다.
5단계: 애플리케이션 배포
이 단계에서는 AWS CDK CLI cdk deploy
명령을 사용하여 애플리케이션을 배포합니다. 는 AWS CloudFormation 서비스와 함께 AWS CDK 작동하여 리소스를 프로비저닝합니다.
배포 전에 AWS 환경을 한 번 부트스트래핑해야 합니다. 지침은 환경 부트스트랩을 참조하십시오.
프로젝트 루트에서 다음을 실행합니다. 메시지가 표시되면 변경 내용을 확인합니다.
$
cdk deploy
✨ Synthesis time: 2.44s
...
Do you wish to deploy these changes (y/n)? y
배포가 완료되면 엔드포인트 AWS CDK CLI URL이 출력됩니다. 다음 단계를 위해 이 URL을 복사하세요. 다음은 그 예제입니다.
...
✅ 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
...
6단계: 애플리케이션과 상호작용
이 단계에서는 API 엔드포인트에 대한 GET 요청을 시작하고 Lambda 함수 응답을 받습니다.
이전 단계에서 엔드포인트 URL을 찾아 경로를 추가합니다. /hello
그런 다음 브라우저 또는 명령 프롬프트를 사용하여 엔드포인트에 GET 요청을 보냅니다. 다음은 그 예제입니다.
$
curl https://<api-id>
.execute-api.<region>
.amazonaws.com/prod/hello
{"message":"Hello World!"}%
축하합니다. 를 사용하여 애플리케이션을 성공적으로 생성, 배포 및 상호 작용했습니다. AWS CDK
7단계: 애플리케이션 삭제
이 단계에서는 를 AWS CDK CLI 사용하여 에서 애플리케이션을 삭제합니다 AWS 클라우드.
애플리케이션을 삭제하려면 를 실행합니다cdk destroy
. 메시지가 표시되면 애플리케이션 삭제 요청을 확인합니다.
$
cdk destroy
Are you sure you want to delete: CdkHelloWorldStack (y/n)? y
CdkHelloWorldStack: destroying... [1/1]
...
✅ CdkHelloWorldStack: destroyed
문제 해결
오류: {“message”: “내부 서버 오류”}%
배포된 Lambda 함수를 호출할 때 이 오류가 발생합니다. 이 오류는 여러 가지 이유로 발생할 수 있습니다.
추가 문제 해결 방법
를 AWS CLI 사용하여 Lambda 함수를 호출할 수 있습니다.
-
스택 파일을 수정하여 배포된 Lambda 함수 이름의 출력 값을 캡처합니다. 다음은 그 예제입니다.
...
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
// ...
-
애플리케이션을 다시 배포하십시오. 배포된 Lambda 함수 이름의 값이 AWS CDK CLI 출력됩니다.
$
cdk deploy
✨ Synthesis time: 0.29s
...
✅ CdkHelloWorldStack
✨ Deployment time: 20.36s
Outputs:
...
CdkHelloWorldStack.HelloWorldFunctionName = CdkHelloWorldStack-HelloWorldFunctionunique-identifier
...
-
AWS CLI 를 사용하여 에서 AWS 클라우드 Lambda 함수를 호출하고 텍스트 파일에 대한 응답을 출력합니다.
$
aws lambda invoke --function-name CdkHelloWorldStack-HelloWorldFunctionunique-identifier
output.txt
-
output.txt
결과를 확인해 보십시오.
- 가능한 원인: API Gateway 리소스가 스택 파일에 잘못 정의되었습니다.
-
성공적인 Lambda 함수 응답이 output.txt
표시되는 경우 API Gateway REST API를 정의한 방식에 문제가 있을 수 있습니다. 는 AWS CLI 엔드포인트를 통하지 않고 Lambda를 직접 호출합니다. 코드가 이 자습서와 일치하는지 확인하십시오. 그런 다음 다시 배포하세요.
- 가능한 원인: Lambda 리소스가 스택 파일에 잘못 정의되었습니다.
-
오류가 output.txt
반환되는 경우 Lambda 함수를 정의한 방법이 문제일 수 있습니다. 코드가 이 자습서와 일치하는지 확인하십시오. 그런 다음 다시 배포하세요.