AWS CDK 스택 - AWS Cloud Development Kit (AWS CDK) v2

AWS CDK v2 개발자 안내서입니다. 구형 CDK v1은 2022년 6월 1일에 유지 보수에 들어갔고 2023년 6월 1일에 지원이 종료되었습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS CDK 스택

AWS Cloud Development Kit (AWS CDK) 스택은 리소스를 정의하는 AWS 하나 이상의 구문의 모음입니다. 각 CDK 스택은 CDK 앱의 AWS CloudFormation 스택을 나타냅니다. 배포 시 스택 내의 구조는 스택이라는 단일 단위로 프로비저닝됩니다. AWS CloudFormation AWS CloudFormation 스택에 대해 자세히 알아보려면 사용 설명서의 스택 작업을 참조하십시오.AWS CloudFormation

CDK스택은 AWS CloudFormation 스택을 통해 구현되므로 AWS CloudFormation 할당량과 제한이 적용됩니다. 자세히 알아보려면 할당량을 참조하십시오.AWS CloudFormation

스택을 정의하는 방법

스택은 앱 컨텍스트 내에서 정의됩니다. Stack AWS 구성 라이브러리의 구문을 사용하여 스택을 정의합니다. 스택은 다음 방법 중 하나로 정의할 수 있습니다.

  • 앱 범위 내에서 바로 사용할 수 있습니다.

  • 트리 내의 모든 구문을 통해 간접적으로

다음 예제에서는 스택이 두 개 포함된 CDK 앱을 정의합니다.

TypeScript
const app = new App(); new MyFirstStack(app, 'stack1'); new MySecondStack(app, 'stack2'); app.synth();
JavaScript
const app = new App(); new MyFirstStack(app, 'stack1'); new MySecondStack(app, 'stack2'); app.synth();
Python
app = App() MyFirstStack(app, 'stack1') MySecondStack(app, 'stack2') app.synth()
Java
App app = new App(); new MyFirstStack(app, "stack1"); new MySecondStack(app, "stack2"); app.synth();
C#
var app = new App(); new MyFirstStack(app, "stack1"); new MySecondStack(app, "stack2"); app.Synth();

다음 예제는 별도의 파일에 스택을 정의하는 일반적인 패턴입니다. 여기서는 Stack 클래스를 확장하거나 상속하고, 및 를 허용하는 scope 생성자를 정의합니다. id props 그런 다음 수신된, 및 를 super 사용하여 기본 Stack 클래스 생성자를 호출합니다. scope id props

TypeScript
class HelloCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); //... } }
JavaScript
class HelloCdkStack extends Stack { constructor(scope, id, props) { super(scope, id, props); //... } }
Python
class HelloCdkStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # ...
Java
public class HelloCdkStack extends Stack { public HelloCdkStack(final Construct scope, final String id) { this(scope, id, null); } public HelloCdkStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); // ... } }
C#
public class HelloCdkStack : Stack { public HelloCdkStack(Construct scope, string id, IStackProps props=null) : base(scope, id, props) { //... } }
Go
func HelloCdkStack(scope constructs.Construct, id string, props *HelloCdkStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) return stack }

다음 예제는 Amazon S3 버킷 하나를 MyFirstStack 포함하는 이름이 지정된 스택 클래스를 선언합니다.

TypeScript
class MyFirstStack extends Stack { constructor(scope: Construct, id: string, props?: StackProps) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket'); } }
JavaScript
class MyFirstStack extends Stack { constructor(scope, id, props) { super(scope, id, props); new s3.Bucket(this, 'MyFirstBucket'); } }
Python
class MyFirstStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) s3.Bucket(self, "MyFirstBucket")
Java
public class MyFirstStack extends Stack { public MyFirstStack(final Construct scope, final String id) { this(scope, id, null); } public MyFirstStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); new Bucket(this, "MyFirstBucket"); } }
C#
public class MyFirstStack : Stack { public MyFirstStack(Stack scope, string id, StackProps props = null) : base(scope, id, props) { new Bucket(this, "MyFirstBucket"); } }
Go
func MyFirstStack(scope constructs.Construct, id string, props *MyFirstStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) s3.NewBucket(stack, jsii.String("MyFirstBucket"), &s3.BucketProps{}) return stack }

하지만 이 코드에서는 스택만 선언했습니다. 스택을 실제로 AWS CloudFormation 템플릿으로 합성하여 배포하려면 인스턴스화해야 합니다. 또한 모든 CDK 구문과 마찬가지로 일부 컨텍스트에서 인스턴스화해야 합니다. App바로 그 컨텍스트입니다.

표준 AWS CDK 개발 템플릿을 사용하는 경우 스택은 객체를 인스턴스화하는 동일한 파일에서 인스턴스화됩니다. App

TypeScript

프로젝트 폴더에 있는 프로젝트 이름을 딴 파일 (예:hello-cdk.ts). bin

JavaScript

프로젝트 bin 폴더에 있는 프로젝트 이름을 딴 파일 (예:hello-cdk.js)

Python

프로젝트의 기본 디렉터리에 app.py 있는 파일입니다.

Java

예를 들어 ProjectNameApp.javaHelloCdkApp.java, 이름이 지정된 파일은 src/main 디렉터리 깊숙이 중첩되어 있습니다.

C#

예를 들어 src\ProjectNamesrc\HelloCdk\Program.cs, Program.cs under 라는 이름의 파일입니다.

스택 API

Stack 객체는 다음을 API 포함한 풍부한 기능을 제공합니다.

  • Stack.of(construct)— 구문이 정의된 Stack을 반환하는 정적 메서드입니다. 이는 재사용 가능한 구조 내에서 스택과 상호 작용해야 하는 경우에 유용합니다. 스코프에서 스택을 찾을 수 없는 경우 호출이 실패합니다.

  • stack.stackName(Python:stack_name) — 스택의 물리적 이름을 반환합니다. 앞서 언급했듯이 모든 AWS CDK 스택에는 합성 중에 AWS CDK 확인할 수 있는 물리적 이름이 있습니다.

  • stack.regionstack.account — 이 스택을 배포할 AWS 지역과 계정을 각각 반환합니다. 이러한 속성은 다음 중 하나를 반환합니다.

    • 스택이 정의될 때 명시적으로 지정된 계정 또는 지역

    • 계정 및 지역의 AWS CloudFormation 유사 매개변수로 확인되는 문자열 인코딩 토큰으로, 이 스택이 환경에 구애받지 않는다는 것을 나타냅니다.

    스택의 환경을 결정하는 방법에 대한 자세한 내용은 을 참조하십시오. 를 위한 환경 AWS CDK

  • stack.addDependency(stack)(Python: stack.add_dependency(stack) — 두 스택 간의 종속성 순서를 명시적으로 정의하는 데 사용할 수 있습니다. 여러 스택을 한 번에 배포할 때는 cdk deploy 명령이 이 순서를 따릅니다.

  • stack.tags— 스택 수준 태그를 추가하거나 제거하는 데 사용할 수 TagManager있는 a를 반환합니다. 이 태그 관리자는 스택 내의 모든 리소스에 태그를 지정하고 스택이 생성될 때 스택 자체에도 태그를 지정합니다. AWS CloudFormation

  • stack.partition, stack.urlSuffix (Python:url_suffix), stack.stackId (Python:stack_id), stack.notificationArn (Python:notification_arn) — 각 가상 파라미터 (예:) 로 AWS CloudFormation 확인되는 토큰을 반환합니다. { "Ref": "AWS::Partition" } 이러한 토큰은 특정 스택 개체와 연결되므로 AWS CDK 프레임워크에서 스택 간 참조를 식별할 수 있습니다.

  • stack.availabilityZones(Python:availability_zones) — 이 스택이 배포된 환경에서 사용 가능한 가용 영역 세트를 반환합니다. 환경에 구애받지 않는 스택의 경우, 이렇게 하면 항상 두 개의 가용 영역이 있는 배열이 반환됩니다. 환경별 스택의 경우 환경을 AWS CDK 쿼리하여 지정한 지역에서 사용 가능한 정확한 가용 영역 세트를 반환합니다.

  • stack.parseArn(arn)and stack.formatArn(comps) (Python:parse_arn,format_arn) — Amazon 리소스 이름 (ARNs) 을 사용하는 데 사용할 수 있습니다.

  • stack.toJsonString(obj)(Python:to_json_string) — 임의의 객체를 AWS CloudFormation 템플릿에 포함할 수 있는 JSON 문자열로 포맷하는 데 사용할 수 있습니다. 객체에는 토큰, 속성 및 참조가 포함될 수 있으며, 이러한 토큰, 속성 및 참조는 배포 중에만 확인됩니다.

  • stack.templateOptions(Python:template_options) — 스택의 AWS CloudFormation 템플릿 옵션 (예: 변환, 설명, 메타데이터) 을 지정하는 데 사용합니다.

스택 작업

스택은 AWS CloudFormation 스택의 일부로 AWS 환경에 배포됩니다. 환경에는 특정 AND가 포함됩니다 AWS 계정 . AWS 리전

여러 스택이 있는 앱에 대해 cdk synth 명령을 실행하면 클라우드 어셈블리에 각 스택 인스턴스에 대한 별도의 템플릿이 포함됩니다. 두 스택이 같은 클래스의 인스턴스인 경우에도 는 두 개의 개별 AWS CDK 템플릿으로 내보냅니다.

명령에서 스택 이름을 지정하여 각 템플릿을 합성할 수 있습니다. cdk synth 다음 예제는 stack1의 템플릿을 합성합니다.

$ cdk synth stack1

이 접근 방식은 AWS CloudFormation 템플릿을 여러 번 배포하고 매개 변수를 통해 매개 변수화할 수 있는 일반적인 템플릿 사용 방식과 개념적으로 다릅니다.AWS CloudFormation 에서 AWS CloudFormation 매개 변수를 정의할 수 있지만 매개 변수는 AWS CDK배포 중에만 확인되므로 AWS CloudFormation 일반적으로 사용하지 않는 것이 좋습니다. 즉, 코드에서는 해당 값을 확인할 수 없습니다.

예를 들어 매개변수 값을 기반으로 앱에 리소스를 조건부로 포함하려면 조건을 설정하고 해당 AWS CloudFormation 조건으로 리소스에 태그를 지정해야 합니다. 는 합성 시 구체적인 템플릿을 해석하는 접근 방식을 AWS CDK 취합니다. 따라서 if 문을 사용하여 값을 검사하여 리소스를 정의해야 하는지 아니면 일부 동작을 적용해야 하는지를 결정할 수 있습니다.

참고

는 합성 시간 동안 최대한 많은 해상도를 AWS CDK 제공하므로 프로그래밍 언어를 관용적이고 자연스럽게 사용할 수 있습니다.

다른 구성과 마찬가지로 스택도 그룹으로 구성할 수 있습니다. 다음 코드는 제어 플레인, 데이터 플레인, 모니터링 스택의 세 가지 스택으로 구성된 서비스의 예를 보여줍니다. 서비스 구조는 두 번 정의됩니다. 한 번은 베타 환경용이고 다른 한 번은 프로덕션 환경용입니다.

TypeScript
import { App, Stack } from 'aws-cdk-lib'; import { Construct } from 'constructs'; interface EnvProps { prod: boolean; } // imagine these stacks declare a bunch of related resources class ControlPlane extends Stack {} class DataPlane extends Stack {} class Monitoring extends Stack {} class MyService extends Construct { constructor(scope: Construct, id: string, props?: EnvProps) { super(scope, id); // we might use the prod argument to change how the service is configured new ControlPlane(this, "cp"); new DataPlane(this, "data"); new Monitoring(this, "mon"); } } const app = new App(); new MyService(app, "beta"); new MyService(app, "prod", { prod: true }); app.synth();
JavaScript
const { App, Stack } = require('aws-cdk-lib'); const { Construct } = require('constructs'); // imagine these stacks declare a bunch of related resources class ControlPlane extends Stack {} class DataPlane extends Stack {} class Monitoring extends Stack {} class MyService extends Construct { constructor(scope, id, props) { super(scope, id); // we might use the prod argument to change how the service is configured new ControlPlane(this, "cp"); new DataPlane(this, "data"); new Monitoring(this, "mon"); } } const app = new App(); new MyService(app, "beta"); new MyService(app, "prod", { prod: true }); app.synth();
Python
from aws_cdk import App, Stack from constructs import Construct # imagine these stacks declare a bunch of related resources class ControlPlane(Stack): pass class DataPlane(Stack): pass class Monitoring(Stack): pass class MyService(Construct): def __init__(self, scope: Construct, id: str, *, prod=False): super().__init__(scope, id) # we might use the prod argument to change how the service is configured ControlPlane(self, "cp") DataPlane(self, "data") Monitoring(self, "mon") app = App(); MyService(app, "beta") MyService(app, "prod", prod=True) app.synth()
Java
package com.myorg; import software.amazon.awscdk.App; import software.amazon.awscdk.Stack; import software.constructs.Construct; public class MyApp { // imagine these stacks declare a bunch of related resources static class ControlPlane extends Stack { ControlPlane(Construct scope, String id) { super(scope, id); } } static class DataPlane extends Stack { DataPlane(Construct scope, String id) { super(scope, id); } } static class Monitoring extends Stack { Monitoring(Construct scope, String id) { super(scope, id); } } static class MyService extends Construct { MyService(Construct scope, String id) { this(scope, id, false); } MyService(Construct scope, String id, boolean prod) { super(scope, id); // we might use the prod argument to change how the service is configured new ControlPlane(this, "cp"); new DataPlane(this, "data"); new Monitoring(this, "mon"); } } public static void main(final String argv[]) { App app = new App(); new MyService(app, "beta"); new MyService(app, "prod", true); app.synth(); } }
C#
using Amazon.CDK; using Constructs; // imagine these stacks declare a bunch of related resources public class ControlPlane : Stack { public ControlPlane(Construct scope, string id=null) : base(scope, id) { } } public class DataPlane : Stack { public DataPlane(Construct scope, string id=null) : base(scope, id) { } } public class Monitoring : Stack { public Monitoring(Construct scope, string id=null) : base(scope, id) { } } public class MyService : Construct { public MyService(Construct scope, string id, Boolean prod=false) : base(scope, id) { // we might use the prod argument to change how the service is configured new ControlPlane(this, "cp"); new DataPlane(this, "data"); new Monitoring(this, "mon"); } } class Program { static void Main(string[] args) { var app = new App(); new MyService(app, "beta"); new MyService(app, "prod", prod: true); app.Synth(); } }

이 AWS CDK 앱은 결국 각 환경에 3개씩 총 6개의 스택으로 구성됩니다.

$ cdk ls betacpDA8372D3 betadataE23DB2BA betamon632BD457 prodcp187264CE proddataF7378CE5 prodmon631A1083

AWS CloudFormation 스택의 물리적 이름은 트리의 스택 구성 경로를 AWS CDK 기반으로 에 의해 자동으로 결정됩니다. 기본적으로 스택 이름은 Stack 개체의 구성 ID에서 파생됩니다. 하지만 다음과 같이 stackName prop (Python에서는stack_name) 를 사용하여 명시적인 이름을 지정할 수 있습니다.

TypeScript
new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' });
JavaScript
new MyStack(this, 'not:a:stack:name', { stackName: 'this-is-stack-name' });
Python
MyStack(self, "not:a:stack:name", stack_name="this-is-stack-name")
Java
new MyStack(this, "not:a:stack:name", StackProps.builder() .StackName("this-is-stack-name").build());
C#
new MyStack(this, "not:a:stack:name", new StackProps { StackName = "this-is-stack-name" });

중첩 스택

NestedStack구조는 스택의 AWS CloudFormation 리소스 500개 제한을 우회하는 방법을 제공합니다. 중첩된 스택은 스택에서 해당 스택을 포함하는 하나의 리소스로만 계산됩니다. 하지만 추가 중첩 스택을 포함하여 최대 500개의 리소스를 포함할 수 있습니다.

중첩된 스택의 범위는 or Stack 구문이어야 합니다. NestedStack 중첩 스택은 부모 스택 내에서 어휘적으로 선언할 필요가 없습니다. 중첩된 스택을 인스턴스화할 때는 부모 스택을 첫 번째 매개 변수 (scope) 로 전달하기만 하면 됩니다. 이러한 제한을 제외하면, 중첩된 스택에서 구문을 정의하는 것은 일반 스택과 완전히 동일하게 작동합니다.

합성 시 중첩된 스택은 자체 AWS CloudFormation 템플릿에 합성되며, 이 템플릿은 배포 시 AWS CDK 스테이징 버킷에 업로드됩니다. 중첩된 스택은 상위 스택에 바인딩되며 독립 배포 아티팩트로 취급되지 않습니다. 목록에 없으며 배포에 cdk list 사용할 수도 없습니다. cdk deploy

부모 스택과 중첩 스택 간의 참조는 스택 간 참조와 마찬가지로 생성된 AWS CloudFormation 템플릿의 스택 매개 변수 및 출력으로 자동 변환됩니다.

주의

중첩된 스택의 경우 배포 전에는 보안 상태의 변경 사항이 표시되지 않습니다. 이 정보는 최상위 스택에만 표시됩니다.