CDK AWS v2 개발자 안내서입니다. 이전 CDK v1은 2022년 6월 1일에 유지 관리에 들어갔으며 2023년 6월 1일에 지원이 종료되었습니다.
기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
CDK Toolkit용 플러그인 구성
AWS CDK Toolkit은 CDK 워크플로에 새 기능을 추가하는 플러그인을 지원합니다. 플러그인은 주로 CDK 명령줄 인터페이스(CDK CLI)와 함께 사용하도록 설계되었지만 CDK Toolkit Library와 함께 프로그래밍 방식으로도 사용할 수 있습니다. 대체 자격 증명 소스와 같은 기능을 확장하는 표준화된 방법을 제공합니다.
플러그인 시스템은 CDK CLI와 CDK Toolkit Library 모두에서 작동하지만 주로 CLI 사용을 위한 것입니다. CDK Toolkit Library를 프로그래밍 방식으로 사용하는 경우 플러그인 없이, 특히 자격 증명 관리를 위해 동일한 작업을 수행하는 더 간단하고 직접적인 방법이 있는 경우가 많습니다.
현재 CDK Toolkit은 하나의 플러그인 기능을 지원합니다.
플러그인을 생성하는 방법
CDK Toolkit 플러그인을 생성하려면 먼저 CDK Toolkit에서 로드할 수 있는 TypeScript 또는 JavaScript로 작성된 Node.js 모듈을 생성합니다. 이 모듈은 CDK Toolkit이 인식할 수 있는 특정 구조의 객체를 내보냅니다. 최소한 내보낸 객체에는 버전 식별자와 플러그인이 기능을 등록하는 데 사용하는 IPluginHost
인스턴스를 수신하는 초기화 함수가 포함되어야 합니다.
- TypeScript
-
- CommonJS
-
// Example plugin structure
import type { IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';
const plugin: Plugin = {
// Version of the plugin infrastructure (currently always '1')
version: '1',
// Initialization function called when the plugin is loaded
init(host: IPluginHost): void {
// Register your plugin functionality with the host
// For example, register a custom credential provider
}
};
export = plugin;
- ESM
-
// Example plugin structure
import type { IPluginHost, Plugin } from '@aws-cdk/cli-plugin-contract';
const plugin: Plugin = {
// Version of the plugin infrastructure (currently always '1')
version: '1',
// Initialization function called when the plugin is loaded
init(host: IPluginHost): void {
// Register your plugin functionality with the host
// For example, register a custom credential provider
}
};
export { plugin as 'module.exports' };
- JavaScript
-
- CommonJS
-
const plugin = {
// Version of the plugin infrastructure (currently always '1')
version: '1',
// Initialization function called when the plugin is loaded
init(host) {
// Register your plugin functionality with the host
// For example, register a custom credential provider
}
};
module.exports = plugin;
- ESM
-
const plugin = {
// Version of the plugin infrastructure (currently always '1')
version: '1',
// Initialization function called when the plugin is loaded
init(host) {
// Register your plugin functionality with the host
// For example, register a custom credential provider
}
};
export { plugin as 'module.exports' };
CDK Toolkit 플러그인은 CommonJS 모듈로 로드됩니다. 플러그인을 ECMAScript 모듈(ESM)로 빌드할 수 있지만 몇 가지 제약 조건을 준수해야 합니다.
CDK CLI를 사용하여 플러그인을 로드하는 방법
플러그인을 지정하는 두 가지 옵션이 있습니다.
- 옵션 1:
--plugin
명령줄 옵션 사용
-
# Load a single plugin
$ cdk list --plugin=my-custom-plugin
# Load multiple plugins
$ cdk deploy --plugin=custom-plugin-1 --plugin=custom-plugin-2
--plugin
인수의 값은 Node.js require()
함수를 통해 가져올 때 Plugin
인터페이스를 구현하는 객체를 반환하는 JavaScript 파일이어야 합니다.
- 옵션 2: 구성 파일에 항목 추가
-
프로젝트별 cdk.json
파일 또는 ~/.cdk.json
글로벌 구성 파일에 플러그인 사양을 추가할 수 있습니다.
{
"plugin": [
"custom-plugin-1",
"custom-plugin-2"
]
}
두 방법 중 하나를 사용하면 CDK CLI는 명령을 실행하기 전에 지정된 플러그인을 로드합니다.
CDK Toolkit Library를 사용하여 코드에 플러그인 로드
CDK Toolkit Library를 프로그래밍 방식으로 사용할 때 @aws-cdk/toolkit-lib
패키지의 PluginHost
인스턴스를 사용하여 코드에 직접 플러그인을 로드할 수 있습니다. 는 모듈 이름 또는 경로별로 플러그인을 로드하는 load()
방법을 PluginHost
제공합니다.
- TypeScript
-
import { Toolkit } from '@aws-cdk/toolkit-lib';
// Create a Toolkit instance
const toolkit = new Toolkit();
// Load a plugin by module name or path
// The module must export an object matching the Plugin interface
await toolkit.pluginHost.load('my-custom-plugin');
// You can load multiple plugins if needed
await toolkit.pluginHost.load('./path/to/another-plugin');
// Now proceed with other CDK Toolkit Library operations
// The plugin's functionality will be available to the toolkit
- JavaScript
-
const { Toolkit } = require('@aws-cdk/toolkit-lib');
// Create a Toolkit instance
const toolkit = new Toolkit();
// Load a plugin by module name or path
// The module must export an object matching the Plugin interface
await toolkit.pluginHost.load('my-custom-plugin');
// You can load multiple plugins if needed
await toolkit.pluginHost.load('./path/to/another-plugin');
// Now proceed with other CDK Toolkit Library operations
// The plugin's functionality will be available to the toolkit
load()
메서드는 로드할 플러그인 모듈의 이름 또는 경로인 단일 파라미터 moduleSpec
를 사용합니다. 다음 중 하나일 수 있습니다.
자격 증명 공급자 플러그인 구현
플러그인의 현재 기본 사용 사례는 사용자 지정 AWS 자격 증명 공급자를 생성하는 것입니다. AWS CLI와 마찬가지로 CDK CLI는 인증 및 권한 부여를 위해 AWS 자격 증명이 필요합니다. 그러나 표준 자격 증명 확인이 실패할 수 있는 몇 가지 시나리오가 있습니다.
이러한 시나리오를 해결하기 위해 CDK Toolkit은 자격 증명 공급자 플러그인을 지원합니다. 이러한 플러그인은 @aws-cdk/cli-plugin-contract
패키지에서 CredentialProviderSource
인터페이스를 구현하고 registerCredentialProviderSource
메서드를 사용하여 도구 키트에 등록됩니다. 이를 통해 CDK Toolkit은 특수 인증 시스템 또는 사용자 지정 AWS 자격 증명 저장소와 같은 비표준 소스에서 자격 증명을 얻을 수 있습니다.
사용자 지정 자격 증명 공급자를 구현하려면 필요한 인터페이스를 구현하는 클래스를 생성합니다.
- TypeScript
-
- CommonJS
-
import type { CredentialProviderSource, ForReading, ForWriting, IPluginHost, Plugin, PluginProviderResult, SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract';
class CustomCredentialProviderSource implements CredentialProviderSource {
// Friendly name for the provider, used in error messages
public readonly name: string = 'custom-credential-provider';
// Check if this provider is available on the current system
public async isAvailable(): Promise<boolean> {
// Return false if the plugin cannot be used
// For example, if it depends on files not present on the host
return true;
}
// Check if this provider can provide credentials for a specific account
public async canProvideCredentials(accountId: string): Promise<boolean> {
// Return false if the plugin cannot provide credentials for this account
// For example, if the account is not managed by this credential system
return true;
// You can use patterns to filter specific accounts
// return accountId.startsWith('123456');
}
// Get credentials for the specified account and access mode
// Returns PluginProviderResult which can be one of:
// - SDKv2CompatibleCredentials (AWS SDK v2 entered maintenance on Sept 8, 2024 and will reach end-of-life on Sept 8, 2025)
// - SDKv3CompatibleCredentialProvider
// - SDKv3CompatibleCredentials
public async getProvider(accountId: string, mode: ForReading | ForWriting): Promise<PluginProviderResult> {
// The access mode can be used to provide different credential sets
const readOnly = mode === 0 satisfies ForReading;
// Create appropriate credentials based on your authentication mechanism
const credentials: SDKv3CompatibleCredentials = {
accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
// Add sessionToken if using temporary credentials
// sessionToken: 'AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk',
// expireTime: new Date(Date.now() + 3600 * 1000), // 1 hour from now
};
return credentials;
}
}
const plugin: Plugin = {
version: '1',
init(host: IPluginHost): void {
// Register the credential provider to the PluginHost.
host.registerCredentialProviderSource(new CustomCredentialProviderSource());
}
};
export = plugin;
- ESM
-
import type { CredentialProviderSource, ForReading, ForWriting, IPluginHost, Plugin, PluginProviderResult, SDKv3CompatibleCredentials } from '@aws-cdk/cli-plugin-contract';
class CustomCredentialProviderSource implements CredentialProviderSource {
// Friendly name for the provider, used in error messages
public readonly name: string = 'custom-credential-provider';
// Check if this provider is available on the current system
public async isAvailable(): Promise<boolean> {
// Return false if the plugin cannot be used
// For example, if it depends on files not present on the host
return true;
}
// Check if this provider can provide credentials for a specific account
public async canProvideCredentials(accountId: string): Promise<boolean> {
// Return false if the plugin cannot provide credentials for this account
// For example, if the account is not managed by this credential system
return true;
// You can use patterns to filter specific accounts
// return accountId.startsWith('123456');
}
// Get credentials for the specified account and access mode
// Returns PluginProviderResult which can be one of:
// - SDKv2CompatibleCredentials (AWS SDK v2 entered maintenance on Sept 8, 2024 and will reach end-of-life on Sept 8, 2025)
// - SDKv3CompatibleCredentialProvider
// - SDKv3CompatibleCredentials
public async getProvider(accountId: string, mode: ForReading | ForWriting): Promise<PluginProviderResult> {
// The access mode can be used to provide different credential sets
const readOnly = mode === 0 satisfies ForReading;
// Create appropriate credentials based on your authentication mechanism
const credentials: SDKv3CompatibleCredentials = {
accessKeyId: 'AKIAIOSFODNN7EXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
// Add sessionToken if using temporary credentials
// sessionToken: 'AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk',
// expireTime: new Date(Date.now() + 3600 * 1000), // 1 hour from now
};
return credentials;
}
}
const plugin: Plugin = {
version: '1',
init(host: IPluginHost): void {
// Register the credential provider to the PluginHost.
host.registerCredentialProviderSource(new CustomCredentialProviderSource());
}
};
export { plugin as 'module.exports' };
- JavaScript
-
- CommonJS
-
// Implement the CredentialProviderSource interface
class CustomCredentialProviderSource {
constructor() {
// Friendly name for the provider, used in error messages
this.name = 'custom-credential-provider';
}
// Check if this provider is available on the current system
async isAvailable() {
// Return false if the plugin cannot be used
// For example, if it depends on files not present on the host
return true;
}
// Check if this provider can provide credentials for a specific account
async canProvideCredentials(accountId) {
// Return false if the plugin cannot provide credentials for this account
// For example, if the account is not managed by this credential system
return true;
// You can use patterns to filter specific accounts
// return accountId.startsWith('123456');
}
// Get credentials for the specified account and access mode
// Returns PluginProviderResult which can be one of:
// - SDKv2CompatibleCredentials (AWS SDK v2 entered maintenance on Sept 8, 2024 and will reach end-of-life on Sept 8, 2025)
// - SDKv3CompatibleCredentialProvider
// - SDKv3CompatibleCredentials
async getProvider(accountId, mode) {
// The access mode can be used to provide different credential sets
const readOnly = mode === 0; // 0 indicates ForReading; 1 indicates ForWriting
// Create appropriate credentials based on your authentication mechanism
const credentials = {
accessKeyId: 'ASIAIOSFODNN7EXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
// Add sessionToken if using temporary credentials
// sessionToken: 'AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk',
// expireTime: new Date(Date.now() + 3600 * 1000), // 1 hour from now
};
return credentials;
}
}
const plugin = {
version: '1',
init(host) {
// Register the credential provider to the PluginHost.
host.registerCredentialProviderSource(new CustomCredentialProviderSource());
}
};
module.exports = plugin;
- ESM
-
// Implement the CredentialProviderSource interface
class CustomCredentialProviderSource {
constructor() {
// Friendly name for the provider, used in error messages
this.name = 'custom-credential-provider';
}
// Check if this provider is available on the current system
async isAvailable() {
// Return false if the plugin cannot be used
// For example, if it depends on files not present on the host
return true;
}
// Check if this provider can provide credentials for a specific account
async canProvideCredentials(accountId) {
// Return false if the plugin cannot provide credentials for this account
// For example, if the account is not managed by this credential system
return true;
// You can use patterns to filter specific accounts
// return accountId.startsWith('123456');
}
// Get credentials for the specified account and access mode
// Returns PluginProviderResult which can be one of:
// - SDKv2CompatibleCredentials (AWS SDK v2 entered maintenance on Sept 8, 2024 and will reach end-of-life on Sept 8, 2025)
// - SDKv3CompatibleCredentialProvider
// - SDKv3CompatibleCredentials
async getProvider(accountId, mode) {
// The access mode can be used to provide different credential sets
const readOnly = mode === 0; // 0 indicates ForReading; 1 indicates ForWriting
// Create appropriate credentials based on your authentication mechanism
const credentials = {
accessKeyId: 'ASIAIOSFODNN7EXAMPLE',
secretAccessKey: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
// Add sessionToken if using temporary credentials
// sessionToken: 'AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4Olgk',
// expireTime: new Date(Date.now() + 3600 * 1000), // 1 hour from now
};
return credentials;
}
}
const plugin = {
version: '1',
init(host) {
// Register the credential provider to the PluginHost.
host.registerCredentialProviderSource(new CustomCredentialProviderSource());
}
};
export { plugin as 'module.exports' };
공급자로부터 얻은 자격 증명은 CDK Toolkit에 의해 캐시됩니다. 장기 실행 작업 중에 만료 문제를 방지하려면 공급자가 반환한 자격 증명 객체를 자체 새로 고치는 것이 좋습니다. 자세한 내용은 AWS SDK for JavaScript v3 설명서의 자격 증명을 참조하세요.
자세히 알아보기
CDK Toolkit 플러그인에 대한 자세한 내용은 aws-cdk-cli GitHub 리포지토리의 AWS CDK Toolkit 플러그인 계약을 참조하세요.