Ini adalah Panduan Pengembang AWS CDK v2. CDK v1 yang lebih lama memasuki pemeliharaan pada 1 Juni 2022 dan mengakhiri dukungan pada 1 Juni 2023.
Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Konfigurasikan plugin untuk CDK Toolkit
AWS CDK Toolkit mendukung plugin yang menambahkan kemampuan baru ke alur kerja CDK Anda. Plugin terutama dirancang untuk digunakan dengan CDK Command Line Interface (CDK CLI), meskipun mereka juga dapat digunakan dengan CDK Toolkit Library secara terprogram. Mereka menyediakan cara standar untuk memperluas fungsionalitas, seperti sumber kredensi alternatif.
Sementara sistem plugin bekerja dengan CDK CLI dan CDK Toolkit Library, ini terutama ditujukan untuk penggunaan CLI. Saat menggunakan CDK Toolkit Library secara terprogram, seringkali ada cara yang lebih sederhana dan lebih langsung untuk menyelesaikan tugas yang sama tanpa plugin, terutama untuk manajemen kredensi.
Saat ini, CDK Toolkit mendukung satu kemampuan plugin:
Cara membuat plugin
Untuk membuat plugin CDK Toolkit, pertama-tama Anda membuat modul Node.js, ditulis dalam TypeScript atau JavaScript, yang dapat dimuat oleh CDK Toolkit. Modul ini mengekspor objek dengan struktur tertentu yang dapat dikenali oleh CDK Toolkit. Minimal, objek yang diekspor harus menyertakan pengenal versi dan fungsi inisialisasi yang menerima IPluginHost
instance, yang digunakan plugin untuk mendaftarkan kemampuannya.
- 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' };
Plugin CDK Toolkit dimuat sebagai modul CommonJS. Anda dapat membangun plugin Anda sebagai ECMAScript modul (ESM), tetapi harus mematuhi beberapa kendala:
-
Modul tidak dapat berisi tingkat atasawait
, atau mengimpor modul apa pun yang berisi tingkat atasawait
.
-
Modul harus memastikan kompatibilitas dengan mengekspor objek plugin di bawah nama module.exports
ekspor:export { plugin as 'module.exports' }
.
Cara memuat plugin dengan CDK CLI
Anda memiliki dua opsi untuk menentukan plugin:
- Opsi 1: Gunakan opsi baris
--plugin
perintah
-
# Load a single plugin
$ cdk list --plugin=my-custom-plugin
# Load multiple plugins
$ cdk deploy --plugin=custom-plugin-1 --plugin=custom-plugin-2
Nilai --plugin
argumen harus berupa JavaScript file yang, ketika diimpor melalui require()
fungsi Node.js, mengembalikan objek yang mengimplementasikan Plugin
antarmuka.
- Opsi 2: Tambahkan entri ke file konfigurasi
-
Anda dapat menambahkan spesifikasi plugin ke cdk.json
file khusus proyek atau file konfigurasi ~/.cdk.json
global:
{
"plugin": [
"custom-plugin-1",
"custom-plugin-2"
]
}
Dengan salah satu pendekatan, CDK CLI akan memuat plugin yang ditentukan sebelum menjalankan perintah.
Muat plugin dalam kode dengan CDK Toolkit Library
Saat bekerja dengan CDK Toolkit Library secara terprogram, Anda dapat memuat plugin langsung dalam kode Anda menggunakan instance dari PluginHost
paket. @aws-cdk/toolkit-lib
PluginHost
Ini menyediakan load()
metode untuk memuat plugin dengan nama modul atau jalur.
- 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()
Metode ini mengambil satu parametermoduleSpec
, yang merupakan nama atau jalur modul plugin untuk dimuat. Ini bisa berupa:
Menerapkan plugin penyedia kredensi
Kasus penggunaan utama saat ini untuk plugin adalah untuk membuat penyedia AWS kredensi khusus. Seperti AWS CLI, CDK CLI AWS membutuhkan kredensil untuk otentikasi dan otorisasi. Namun, ada beberapa skenario di mana resolusi kredenal standar mungkin gagal:
-
Kumpulan kredensil awal tidak dapat diperoleh.
-
Akun yang menjadi milik kredensi awal tidak dapat diperoleh.
-
Akun yang terkait dengan kredensil berbeda dari akun tempat CLI mencoba beroperasi.
Untuk mengatasi skenario ini, CDK Toolkit mendukung plugin penyedia kredensi. Plugin ini mengimplementasikan CredentialProviderSource
antarmuka dari @aws-cdk/cli-plugin-contract
paket dan terdaftar ke Toolkit menggunakan metode iniregisterCredentialProviderSource
. Ini memungkinkan CDK Toolkit untuk mendapatkan AWS kredensil dari sumber non-standar seperti sistem otentikasi khusus atau toko kredensi khusus.
Untuk mengimplementasikan penyedia kredensi khusus, buat kelas yang mengimplementasikan antarmuka yang diperlukan:
- 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' };
Kredensil yang diperoleh dari penyedia di-cache oleh CDK Toolkit. Sangat disarankan agar objek kredensi yang dikembalikan oleh penyedia Anda menyegarkan diri untuk mencegah masalah kedaluwarsa selama operasi yang berjalan lama. Untuk informasi selengkapnya, lihat Kredensial dalam dokumentasi AWS SDK for JavaScript v3.
Pelajari selengkapnya
Untuk mempelajari lebih lanjut tentang plugin CDK Toolkit, lihat Kontrak Plugin AWS CDK Toolkit di repositori. aws-cdk-cli GitHub