CDK AWS v2 개발자 안내서입니다. 이전 CDK v1은 2022년 6월 1일에 유지 관리에 들어갔으며 2023년 6월 1일에 지원이 종료되었습니다.
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
CDK Toolkit 메시지 및 상호 작용 구성
AWS CDK Toolkit Library는 CDK 작업 중에 메시지 및 상호 작용이 처리되는 방식을 사용자 지정하는 IIoHost
인터페이스를 제공하므로 배포 진행 상황, 오류 메시지 및 사용자 프롬프트 표시를 제어하여 애플리케이션의 사용자 경험과 더 잘 통합할 수 있습니다.
배포 또는 합성과 같은 작업을 수행하기 전에 CDK Toolkit이 사용자와 통신하는 방식을 이해해야 합니다. IIoHost
인터페이스는 CDK Toolkit과 애플리케이션 간의 통신 채널 역할을 하여 발신 메시지와 수신 사용자 응답을 모두 처리합니다.
CDK Toolkit은 작업을 실행할 때 다음 두 가지 기본 메커니즘을 통해 통신합니다.
-
메시지: 작업 진행 상황을 알려주는 정보 출력(예: "배포 시작" 또는 "리소스 생성").
-
요청: 입력 또는 확인이 필요한 결정 지점(예: "이 변경 사항을 배포하시겠습니까?")으로, 사전에 필요하지 않은 정보를 제공할 수 있는 기회를 제공합니다.
IIoHost
인터페이스 사용
IIoHost
인터페이스는 두 가지 기본 방법으로 구성됩니다.
-
notify
: 단방향 정보 메시지를 처리합니다. -
requestResponse
: 응답이 필요한 대화형 요청을 처리합니다.
import { IoMessage, IoRequest } from '@aws-cdk/toolkit-lib'; interface IIoHost { // Handle informational messages notify(message: IoMessage): Promise<void>; // Handle requests that need responses requestResponse(request: IoRequest): Promise<any>; }
메시지 수준 및 요청 유형
CDK Toolkit은 여러 유형의 메시지와 요청을 생성합니다.
메시지 수준
-
디버그: 문제 해결을 위한 세부 메시지입니다.
-
오류: 작업에 영향을 미칠 수 있는 오류 메시지입니다.
-
정보: 일반 정보 메시지입니다.
-
결과 - 작업의 기본 메시지입니다.
-
추적: 매우 상세한 실행 흐름 정보입니다.
-
경고: 작업을 방해하지 않는 경고 메시지입니다.
전체 목록은 CDK Toolkit Library API 참조의 IoMessages 레지스트리를 참조하세요. AWS
요청 유형
CDK 도구 키트는 사용자의 입력 또는 확인이 필요할 때 요청을 보냅니다. 이는 응답을 허용하는 특수 메시지입니다. 응답이 제공되지 않으면 도구 키트는 사용 가능한 경우 기본 응답을 사용합니다.
기본 IIoHost
구현
다음은 사용자 지정 io 호스트를 구현하는 간단한 예입니다.
import { Toolkit } from '@aws-cdk/toolkit-lib'; // Create a toolkit with custom message handling const toolkit = new Toolkit({ ioHost: { // Implementing the IIoHost interface // Handle informational messages notify: async function (msg) { // Example: Handle different message levels appropriately switch (msg.level) { case 'error': console.error(`[${msg.time}] ERROR: ${msg.message}`); break; case 'warning': console.warn(`[${msg.time}] WARNING: ${msg.message}`); break; case 'info': console.info(`[${msg.time}] INFO: ${msg.message}`); break; case 'debug': console.debug(`[${msg.time}] DEBUG: ${msg.message}`); break; case 'trace': console.debug(`[${msg.time}] TRACE: ${msg.message}`); break; default: console.log(`[${msg.time}] ${msg.level}: ${msg.message}`); } }, // Handle requests that need responses requestResponse: async function (msg) { // Example: Log the request and use default response console.log(`Request: ${msg.message}, using default: ${msg.defaultResponse}`); return msg.defaultResponse; // Or implement custom logic to provide responses // if (msg.type === 'deploy') { // return promptUserForDeployment(msg); // } } } as IIoHost // Explicitly cast to IIoHost interface });
CDK 도구 키트는 각 호출이 완료될 때까지 대기하므로 메시지를 처리할 때 HTTP 요청 또는 사용자 프롬프트와 같은 비동기 작업을 수행할 수 있습니다.
기본 IIoHost
동작
사용자 지정 io 호스트를 제공하지 않는 경우 CDK Toolkit Library는 기본 비대화형 구현을 사용합니다.
-
메시지에 대한 콘솔 출력(다양한 메시지 유형에 적절한 색상 사용).
-
사용자 입력에 대한 프롬프트 없이 완전 비대화형입니다.
-
가능한 경우 자동으로 기본 응답을 사용합니다(프롬프트에 "예"라고 답하는 것과 동일).
-
입력이 필요하지만 기본 응답을 사용할 수 없는 경우 실패합니다.
이 기본 동작은 무인 작업에 적합하지만 대화형 명령줄 애플리케이션에는 적합하지 않습니다. 사용자 상호 작용이 필요한 명령줄 애플리케이션의 경우 사용자 지정 io 호스트를 구현해야 합니다. 사용자 지정 구현은 로깅 시스템, UIs 또는 기타 특수 환경과 통합하는 데에도 유용합니다.
고급 io 호스트 구현
보다 복잡한 시나리오의 경우 NonInteractiveIoHost
클래스를 시작점으로 확장하는 것이 좋습니다. 이 접근 방식을 사용하면 변경해야 하는 특정 동작만 사용자 지정하면서 기존의 비대화형 구현을 활용할 수 있습니다.
다음은 기본 구현을 확장하는 사용자 지정 io 호스트의 예입니다.
import { NonInteractiveIoHost } from '@aws-cdk/toolkit-lib'; class MyCustomIoHost extends NonInteractiveIoHost { // Override only the methods you need to customize // Example: Custom implementation for notify public async notify(msg: IoMessage<unknown>): Promise<void> { // Add custom notification handling logic if (msg.level === 'error') { console.error(`ERROR: ${msg.message}`); // Optionally log to a service or notify a monitoring system await this.logToMonitoringService(msg); } else { await super.notify(msg); } } // Example: Custom implementation for requestResponse public async requestResponse<T, U>(request: IoRequest<T, U>): Promise<U> { // Implement custom request handling console.log(`Received request: ${request.message}`); return request.defaultResponse; } private async logToMonitoringService(msg: IoMessage<unknown>): Promise<void> { // Implementation for monitoring service integration console.log(`Logging to monitoring service: ${msg.level} - ${msg.message}`); } }
이 접근 방식은 사용자 지정 동작이 필요한 특정 방법만 재정의하면 되므로 전체 IIoHost
인터페이스를 처음부터 구현하는 것보다 유지 관리가 더 쉽습니다.
다양한 환경과 통합
웹 애플리케이션 통합
import { Toolkit } from '@aws-cdk/toolkit-lib'; // Example for integrating with a web application const toolkit = new Toolkit({ ioHost: { notify: async function (msg) { // Send message to frontend via WebSocket webSocketServer.send(JSON.stringify({ type: 'cdk-notification', messageLevel: msg.level, message: msg.message, time: msg.time })); }, requestResponse: async function (msg) { // Create a promise that will be resolved when the user responds return new Promise((resolve) => { const requestId = generateUniqueId(); // Store the resolver function pendingRequests[requestId] = resolve; // Send request to frontend webSocketServer.send(JSON.stringify({ type: 'cdk-request', requestId: requestId, requestType: msg.type, message: msg.message, defaultResponse: msg.defaultResponse })); // Frontend would call an API endpoint with the response, // which would then call pendingRequests[requestId](response) }); } } as IIoHost // Explicitly cast to IIoHost interface });
CI/CD 환경 통합
import { Toolkit } from '@aws-cdk/toolkit-lib'; // Example for CI/CD environments (non-interactive) const toolkit = new Toolkit({ ioHost: { notify: async function (msg) { // Log all messages with appropriate level switch (msg.level) { case 'error': console.error(msg.message); break; case 'warning': console.warn(msg.message); break; default: console.log(msg.message); } }, requestResponse: async function (msg) { // In CI/CD, always use default responses or predefined answers console.log(`Auto-responding to request: ${msg.message} with ${msg.defaultResponse}`); return msg.defaultResponse; } } as IIoHost // Explicitly cast to IIoHost interface });
io 호스트 구현 모범 사례
사용자 지정 io 호스트를 구현할 때는 다음 모범 사례를 고려하세요.
-
오류 처리: io 호스트 메서드에 강력한 오류 처리를 구현하여 장애가 CDK 작업에 영향을 미치지 않도록 합니다.
-
제한 시간: 사용자 상호 작용에 대한 제한 시간을 구현하여 무기한 대기를 방지하는 것이 좋습니다.
-
로깅: 특히 비대화형 환경에서 문제 해결을 위해 중요한 메시지를 로그에 저장합니다.
-
기본 응답: 사용자 상호 작용이 불가능한 자동화된 환경에 적합한 기본 응답을 제공합니다.
-
진행 상황 표시: 장기 실행 작업의 경우 명확한 진행 상황 지표를 제공하여 사용자 경험을 개선합니다.
다음 예제에서는 오류 처리, 사용자 상호 작용 제한 시간 및 적절한 로깅이 포함된 사용자 지정 io 호스트를 구현하여 이러한 모범 사례를 보여줍니다. 이 구현은 사용자 응답성과 안정적인 작업의 균형을 맞춰야 하는 대화형 애플리케이션에 적합합니다.
import { Toolkit } from '@aws-cdk/toolkit-lib'; // Example with error handling and timeouts const toolkit = new Toolkit({ ioHost: { notify: async function (msg) { try { console.log(`[${msg.time}] ${msg.level}: ${msg.message}`); // Additional logging or UI updates } catch (error) { // Ensure errors in notification handling don't break the CDK operation console.error("Error handling notification:", error); } }, requestResponse: async function (msg) { try { // Implement timeout for user response const response = await Promise.race([ getUserResponse(msg), new Promise(resolve => setTimeout(() => resolve(msg.defaultResponse), 60000)) ]); return response; } catch (error) { console.error("Error handling request:", error); return msg.defaultResponse; } } } as IIoHost // Explicitly cast to IIoHost interface });
문제 해결
사용자 지정 io 호스트를 구현할 때 고려 사항:
-
처리되지 않은 promise 거부: 모든 비동기 작업이 try/catch 블록으로 올바르게 처리되는지 확인합니다.
-
무한 대기: 애플리케이션이 중단되지 않도록 모든 사용자 상호 작용에 대한 제한 시간을 구현합니다.
-
누락된 메시지 수준: 향후 CDK 버전에서 추가될 수 있는 새 메시지 수준을 처리할 준비를 합니다.
-
일관되지 않은 응답: requestResponse 구현이 예상 형식으로 값을 반환하는지 확인합니다.
다음 예제는 향후 CDK 버전에 도입될 수 있는 알 수 없는 메시지 유형의 정상적인 처리를 포함하여 메시지 수준을 처리하는 강력한 접근 방식을 보여줍니다. 이 구현을 통해 io 호스트는 적절한 로깅을 유지하면서 CDK 업데이트와 호환됩니다.
import { Toolkit } from '@aws-cdk/toolkit-lib'; // Example of handling unknown message levels const toolkit = new Toolkit({ ioHost: { notify: async function (msg) { // Handle known levels const knownLevels = ['info', 'warning', 'error', 'debug', 'trace', 'status']; if (knownLevels.includes(msg.level)) { // Handle known level handleKnownMessageLevel(msg); } else { // Handle unknown level as info console.log(`Unknown message level "${msg.level}": ${msg.message}`); } }, requestResponse: async function (msg) { // Default implementation return msg.defaultResponse; } } as IIoHost // Explicitly cast to IIoHost interface });