CDK AWS v2 개발자 안내서입니다. 이전 CDK v1은 2022년 6월 1일에 유지 관리에 들어갔으며 2023년 6월 1일에 지원이 종료되었습니다.
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
CDK Toolkit 프로그래밍 방식 작업 구성
AWS CDK Toolkit Library는 합성, 배포 및 스택 관리와 같은 애플리케이션 수명 주기 작업을 위한 프로그래밍 인터페이스를 제공합니다. 이 가이드에서는 코드에서 각 작업을 사용하는 방법을 설명합니다.
synth를 사용하여 클라우드 어셈블리 생성
synth
작업은 클라우드 어셈블리 소스에서 클라우드 어셈블리를 생성합니다. 합성에 대한 자세한 내용은 CDK 스택 합성 구성 및 수행을 참조하세요. 클라우드 어셈블리에는 CDK 앱의 다음과 같은 배포 아티팩트가 포함되어 있습니다.
-
인프라를 정의하는 AWS CloudFormation 템플릿입니다.
-
Lambda 함수 코드 또는 Docker 이미지와 같은 자산.
-
배포 메타데이터 및 구성.
작업을 사용하여 클라우드 어셈블리를 synth
생성하는 방법은 다음과 같습니다.
// Create a toolkit instance const toolkit = new Toolkit(); // Create a cloud assembly source from a TypeScript app const cloudAssemblySource = await toolkit.fromCdkApp("ts-node app.ts"); // Generate a cloud assembly const cloudAssembly = await toolkit.synth(cloudAssemblySource); // Use the cloud assembly for operations await toolkit.list(cloudAssembly); await toolkit.deploy(cloudAssembly); await toolkit.diff(cloudAssembly); // Query information from the cloud assembly const template = cloudAssembly.getStack("my-stack").template;
작은 정보
합성은 한 번만 수행되므로 클라우드 어셈블리를 사용하면 여러 작업을 수행해야 할 때 성능을 최적화할 수 있습니다. 캐싱 및 폐기를 포함한 클라우드 어셈블리 관리에 대한 자세한 내용은 클라우드 어셈블리 생성 및 관리를 참조하세요.
목록을 사용하여 스택 정보 보기
list
작업은 종속성 및 현재 상태를 포함하여 CDK 애플리케이션의 스택에 대한 정보를 검색합니다. 배포 전에 인프라를 검사하거나 보고서를 생성하려면이 작업을 사용합니다.
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; // Get information about specific stacks const stackDetails = await toolkit.list(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.PATTERN_MUST_MATCH, patterns: ["my-stack"], // Only include stacks matching this pattern } }); // Process the returned stack information for (const stack of stackDetails) { console.log(`Stack: ${stack.id}, Dependencies: ${stack.dependencies}`); }
배포를 사용하여 인프라 프로비저닝
이 deploy
작업은 합성 중에 생성된 클라우드 어셈블리를 AWS 사용하여에서 인프라를 프로비저닝하거나 업데이트합니다. 배포에 대한 소개는 AWS CDK 애플리케이션 배포를 참조하세요. 스택 선택, 파라미터 값 및 롤백 동작과 같은 배포 옵션을 제어할 수 있습니다.
// Deploy stacks with parameter values await toolkit.deploy(cloudAssemblySource, { parameters: StackParameters.exactly({ "MyStack": { "BucketName": "amzn-s3-demo-bucket" } }) });
배포 작업은 다양한 워크플로를 수용하기 위해 다양한 배포 방법을 지원합니다. 대부분의 시나리오, 특히 프로덕션 환경에서는 CloudFormation 변경 세트를 사용하는 기본 배포 방법을 사용하는 것이 좋습니다. 반복 속도가 중요한 개발 환경의 경우 핫스왑과 같은 대체 방법을 사용할 수 있습니다.
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; // Deploy using default deployment method (recommended for production) await toolkit.deploy(cloudAssemblySource, { parameters: StackParameters.exactly({ "MyStack": { "BucketName": "amzn-s3-demo-bucket" } }) }); // For development environments only: Deploy with hotswap for faster iterations // Note: We recommend using default deployment methods for production environments await toolkit.deploy(cloudAssemblySource, { deploymentMethod: { method: "hotswap", fallback: true }, // Faster but introduces drift stacks: { strategy: StackSelectionStrategy.PATTERN_MUST_MATCH, patterns: ["dev-stack"] } });
롤백을 사용하여 실패한 배포 되돌리기
rollback
작업은 배포가 실패하고 자동으로 되돌릴 수 없는 경우 스택을 마지막 안정 상태로 반환합니다. 수동 개입이 필요한 실패한 배포에서 복구하려면이 작업을 사용합니다.
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; // Roll back stacks to their last stable state await toolkit.rollback(cloudAssemblySource, { orphanFailedResources: false, // When true, removes failed resources from CloudFormation management stacks: { strategy: StackSelectionStrategy.PATTERN_MUST_MATCH, patterns: ["failed-stack"] } });
watch를 사용하여 변경 사항 모니터링
이 watch
작업은 CDK 앱에서 로컬 파일 변경 사항을 지속적으로 모니터링하고 배포 또는 핫스왑을 자동으로 수행합니다. 이렇게 하면 코드가 종료되거나 종료될 때까지 실행되는 파일 감시자가 생성됩니다.
주의
핫스왑 배포는 가능한 경우 CloudFormation을 거치지 않고 리소스를 직접 업데이트하므로 개발 중에 더 빠르게 업데이트할 수 있습니다. watch
명령에 대해 기본적으로 활성화됩니다. 이렇게 하면 개발 주기가 빨라지지만 CloudFormation 템플릿과 배포된 리소스 간에 드리프트가 발생합니다. 따라서 프로덕션 환경에서는 핫스왑을 사용하지 않는 것이 좋습니다.
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; // Start watching for changes const watcher = await toolkit.watch(cloudAssemblySource, { include: ["lib/**/*.ts"], // Only watch TypeScript files in the lib directory exclude: ["**/*.test.ts"], // Ignore test files deploymentMethod: { method: "hotswap" }, // This is the default, shown here for clarity stacks: { strategy: StackSelectionStrategy.ALL // Watch all stacks } }); // Later in your code, you can explicitly stop watching: // await watcher.dispose();
감시 함수는 감시를 중지할 시기를 명시적으로 제어할 수 있는 IWatcher
객체를 반환합니다. 감시 프로세스를 종료하려면이 객체에서 dispose()
메서드를 호출합니다.
폐기를 사용하여 인프라 제거
destroy
작업은 CDK 스택 및 관련 리소스를 제거합니다 AWS. 더 이상 필요하지 않은 리소스를 정리하려면이 작업을 사용합니다.
중요
삭제 작업은이 명령의 CLI 버전과 달리 확인 메시지를 표시하지 않고 리소스를 영구적으로 제거합니다. 스택을 삭제하기 전에 중요한 데이터를 백업해야 합니다.
import { StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; // Remove specific stacks and their resources await toolkit.destroy(cloudAssemblySource, { stacks: { strategy: StackSelectionStrategy.PATTERN_MUST_MATCH, patterns: ["dev-stack"], // Only destroy stacks matching this pattern } });