Questa è la AWS CDK v2 Developer Guide. Il vecchio CDK v1 è entrato in manutenzione il 1° giugno 2022 e ha terminato il supporto il 1° giugno 2023.
Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.
Configurazione dei plugin per il CDK Toolkit
Il AWS CDK Toolkit supporta plugin che aggiungono nuove funzionalità ai flussi di lavoro CDK. I plugin sono progettati principalmente per l'uso con l'interfaccia a riga di comando CDK (CDK CLI), sebbene possano essere utilizzati anche con la CDK Toolkit Library a livello di codice. Forniscono un modo standardizzato per estendere le funzionalità, ad esempio fonti di credenziali alternative.
Sebbene il sistema di plug-in funzioni sia con CDK CLI che con CDK Toolkit Library, è destinato principalmente all'utilizzo della CLI. Quando si utilizza la CDK Toolkit Library a livello di codice, esistono spesso modi più semplici e diretti per eseguire le stesse attività senza plug-in, in particolare per la gestione delle credenziali.
Attualmente, CDK Toolkit supporta una funzionalità di plug-in:
Come creare plugin
Per creare un plugin CDK Toolkit, dovete prima creare un modulo Node.js, creato in TypeScript o JavaScript, che può essere caricato dal CDK Toolkit. Questo modulo esporta un oggetto con una struttura specifica che CDK Toolkit è in grado di riconoscere. Come minimo, l'oggetto esportato deve includere un identificatore di versione e una funzione di inizializzazione che riceve un'IPluginHost
istanza, che il plugin utilizza per registrare le sue funzionalità.
- 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
-
- Common JS
-
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' };
Come caricare i plugin con la CLI CDK
Hai due opzioni per specificare i plugin:
- Opzione 1: utilizzare l'opzione della
--plugin
riga di comando
-
# Load a single plugin
$ cdk list --plugin=my-custom-plugin
# Load multiple plugins
$ cdk deploy --plugin=custom-plugin-1 --plugin=custom-plugin-2
Il valore dell'--plugin
argomento deve essere un JavaScript file che, se importato tramite la require()
funzione Node.js, restituisce un oggetto che implementa l'Plugin
interfaccia.
- Opzione 2: aggiungere voci ai file di configurazione
-
È possibile aggiungere le specifiche del plug-in al cdk.json
file specifico del progetto o al file di configurazione ~/.cdk.json
globale:
{
"plugin": [
"custom-plugin-1",
"custom-plugin-2"
]
}
Con entrambi gli approcci, la CLI CDK caricherà i plugin specificati prima di eseguire i comandi.
Carica i plugin nel codice con la CDK Toolkit Library
Quando lavori con la CDK Toolkit Library a livello di codice, puoi caricare i plugin direttamente nel codice usando l'istanza contenuta nel pacchetto. PluginHost
@aws-cdk/toolkit-lib
PluginHost
Fornisce un load()
metodo per caricare i plugin in base al nome o al percorso del modulo.
- 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
Il load()
metodo richiede un singolo parametromoduleSpec
, che è il nome o il percorso del modulo plugin da caricare. Questo può essere uno dei seguenti:
Implementazione di plugin per fornitori di credenziali
L'attuale caso d'uso principale dei plugin è la creazione di provider di credenziali personalizzati AWS . Come la AWS CLI, la CLI CDK AWS necessita di credenziali per l'autenticazione e l'autorizzazione. Tuttavia, esistono diversi scenari in cui la risoluzione delle credenziali standard potrebbe fallire:
-
Il set iniziale di credenziali non può essere ottenuto.
-
L'account a cui appartengono le credenziali iniziali non può essere ottenuto.
-
L'account associato alle credenziali è diverso dall'account su cui la CLI sta tentando di operare.
Per risolvere questi scenari, CDK Toolkit supporta i plugin dei provider di credenziali. Questi plugin implementano l'CredentialProviderSource
interfaccia del @aws-cdk/cli-plugin-contract
pacchetto e vengono registrati nel Toolkit utilizzando il metodo. registerCredentialProviderSource
Ciò consente a CDK Toolkit di ottenere AWS credenziali da fonti non standard come sistemi di autenticazione specializzati o archivi di credenziali personalizzati.
Per implementare un provider di credenziali personalizzato, create una classe che implementa l'interfaccia richiesta:
- 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
-
- Common JS
-
// 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' };
Le credenziali ottenute dai provider vengono memorizzate nella cache dal CDK Toolkit. Si consiglia vivamente che gli oggetti delle credenziali restituiti dal provider si aggiornino automaticamente per evitare problemi di scadenza durante le operazioni di lunga durata. Per ulteriori informazioni, consulta Credenziali nella documentazione dell'SDK per la versione 3 AWS . JavaScript
Ulteriori informazioni
Per ulteriori informazioni sui plugin CDK Toolkit, consultate il CDK Toolkit Plugin Contract nel AWS repository. aws-cdk-cli GitHub