CDK AWS v2 개발자 안내서입니다. 이전 CDK v1은 2022년 6월 1일에 유지 관리에 들어갔으며 2023년 6월 1일에 지원이 종료되었습니다.
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
고급 CDK Toolkit Library 예제
실제 예제를 통해 AWS CDK Toolkit Library의 고급 기능을 사용하는 방법을 알아봅니다. 이 가이드에서는 다른 섹션에서 다루는 기본 개념을 기반으로 하는 오류 처리, 배포 모니터링 및 클라우드 어셈블리 관리를 위한 자세한 코드 샘플을 제공합니다.
기능 통합
다음 예제에서는 클라우드 어셈블리 소스, 사용자 지정 io 호스트 구현 및 배포 옵션을 결합하는 방법을 보여줍니다.
import { Toolkit, StackSelectionStrategy, IIoHost } from '@aws-cdk/toolkit-lib'; async function deployApplication(appPath, environment, options = {}) { // Create toolkit with custom message handling const toolkit = new Toolkit({ ioHost: { notify: async (msg) => { // Add environment to all messages console.log(`[${environment}][${msg.time}] ${msg.level}: ${msg.message}`); }, requestResponse: async (msg) => { // In production environments, use default responses if (environment === 'production') { console.log(`Auto-approving for production: ${msg.message}`); return msg.defaultResponse; } // For other environments, implement custom approval logic return promptForApproval(msg); } } as IIoHost }); try { // Create cloud assembly source from the CDK app console.log(`Creating cloud assembly source from ${appPath}`); const cloudAssemblySource = await toolkit.fromCdkApp(appPath); // Synthesize the cloud assembly console.log(`Synthesizing cloud assembly`); const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // Deploy with environment-specific options console.log(`Deploying to ${environment} environment`); return await toolkit.deploy(cloudAssembly, { stacks: options.stacks || { strategy: StackSelectionStrategy.ALL_STACKS }, parameters: options.parameters || {}, tags: { Environment: environment, DeployedBy: 'CDK-Toolkit-Library', DeployTime: new Date().toISOString() } }); } finally { // Always dispose when done await cloudAssembly.dispose(); } } catch (error) { console.error(`Deployment to ${environment} failed:`, error); throw error; } } // Example usage await deployApplication('ts-node app.ts', 'staging', { parameters: { MyStack: { InstanceType: 't3.small' } } });
배포 진행 상황 추적
세부 상태 업데이트를 사용하여 배포 진행 상황을 추적합니다.
import { Toolkit, StackSelectionStrategy, IIoHost } from '@aws-cdk/toolkit-lib'; // Create a progress tracker class DeploymentTracker { private startTime: Date; private resources = new Map<string, string>(); constructor() { this.startTime = new Date(); } onStackEvent(stackName: string, event: string, timestamp: string) { // Calculate elapsed time if needed, or use the provided timestamp const elapsed = (new Date().getTime() - this.startTime.getTime()) / 1000; console.log(`[${timestamp}] (${elapsed.toFixed(1)}s elapsed) Stack ${stackName}: ${event}`); } onResourceEvent(resourceId: string, status: string) { this.resources.set(resourceId, status); this.printProgress(); } private printProgress() { console.log('\nResource Status:'); for (const [id, status] of this.resources.entries()) { console.log(`- ${id}: ${status}`); } console.log(); } } // Use the tracker with the toolkit const tracker = new DeploymentTracker(); const toolkit = new Toolkit({ ioHost: { notify: async (msg) => { if (msg.code.startsWith('CDK_DEPLOY')) { // Track deployment events if (msg.data && 'stackName' in msg.data) { tracker.onStackEvent(msg.data.stackName, msg.message, msg.time); } } else if (msg.code.startsWith('CDK_RESOURCE')) { // Track resource events if (msg.data && 'resourceId' in msg.data) { tracker.onResourceEvent(msg.data.resourceId, msg.message); } } } } as IIoHost }); // Example usage with progress tracking async function deployWithTracking(cloudAssemblySource: any) { try { // Synthesize the cloud assembly const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // Deploy using the cloud assembly await toolkit.deploy(cloudAssembly, { stacks: { strategy: StackSelectionStrategy.ALL_STACKS } }); } finally { // Always dispose when done await cloudAssembly.dispose(); } } catch (error) { // Display the error message console.error("Operation failed:", error.message); throw error; } }
복구 시 오류 처리
복구 전략을 사용하여 강력한 오류 처리를 구현합니다.
import { Toolkit, ToolkitError, StackSelectionStrategy } from '@aws-cdk/toolkit-lib'; async function deployWithRetry(toolkit: Toolkit, cloudAssemblySource: any) { try { // Synthesize the cloud assembly const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // Deploy using the cloud assembly await toolkit.deploy(cloudAssembly, { stacks: { strategy: StackSelectionStrategy.ALL_STACKS } }); } finally { // Always dispose when done await cloudAssembly.dispose(); } } catch (error) { // Simply show the error to the user console.error("Operation failed:", error.message); throw error; } } // Example usage try { await deployWithRetry(toolkit, cloudAssemblySource); } catch (error) { console.error("Operation failed:", error.message); process.exit(1); }
CI/CD 파이프라인과 통합
CDK Toolkit Library를 CI/CD 파이프라인에 통합합니다.
import { Toolkit, StackSelectionStrategy, IIoHost } from '@aws-cdk/toolkit-lib'; import * as fs from 'fs'; import * as path from 'path'; async function cicdDeploy() { // Create a non-interactive toolkit for CI/CD environments const toolkit = new Toolkit({ ioHost: { notify: async (msg) => { // Write to both console and log file const logMessage = `${msg.time} [${msg.level}] ${msg.message}`; console.log(logMessage); // Append to deployment log file fs.appendFileSync('deployment.log', logMessage + '\n'); }, requestResponse: async (msg) => { // Always use default responses in CI/CD console.log(`Auto-responding to: ${msg.message} with: ${msg.defaultResponse}`); return msg.defaultResponse; } } as IIoHost }); // Determine environment from CI/CD variables const environment = process.env.DEPLOYMENT_ENV || 'development'; // Load environment-specific parameters const paramsPath = path.join(process.cwd(), `params.${environment}.json`); const parameters = fs.existsSync(paramsPath) ? JSON.parse(fs.readFileSync(paramsPath, 'utf8')) : {}; try { // Use pre-synthesized cloud assembly from build step const cloudAssemblySource = await toolkit.fromAssemblyDirectory('cdk.out'); // Synthesize the cloud assembly const cloudAssembly = await toolkit.synth(cloudAssemblySource); try { // Deploy with CI/CD specific options const result = await toolkit.deploy(cloudAssembly, { stacks: { strategy: StackSelectionStrategy.ALL_STACKS }, parameters, tags: { Environment: environment, BuildId: process.env.BUILD_ID || 'unknown', CommitHash: process.env.COMMIT_HASH || 'unknown' } }); // Write outputs to a file for subsequent pipeline steps fs.writeFileSync( 'stack-outputs.json', JSON.stringify(result.outputs, null, 2) ); return result; } finally { // Always dispose when done await cloudAssembly.dispose(); } } catch (error) { // Display the error message console.error("Operation failed:", error.message); process.exit(1); } } // Run the CI/CD deployment cicdDeploy().then(() => { console.log('CI/CD deployment completed successfully'); });
추가 리소스
이 예제에서 사용되는 특정 구성 요소에 대한 자세한 내용은 다음을 참조하세요.
-
클라우드 어셈블리 소스 관리 - 클라우드 어셈블리 소스를 생성하고 관리하는 방법을 알아봅니다.
-
메시지 및 상호 작용 구성 -
IIoHost
인터페이스 사용자 지정에 대한 자세한 가이드입니다.