Plugins für das CDK Toolkit konfigurieren - AWS Cloud Development Kit (AWS CDK) v2

Dies ist der AWS CDK v2-Entwicklerhandbuch. Das ältere CDK v1 wurde am 1. Juni 2022 in die Wartung aufgenommen und der Support wurde am 1. Juni 2023 eingestellt.

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Plugins für das CDK Toolkit konfigurieren

Das AWS CDK Toolkit unterstützt Plugins, die Ihren CDK-Workflows neue Funktionen hinzufügen. Plugins sind in erster Linie für die Verwendung mit dem CDK Command Line Interface (CDK CLI) konzipiert, können aber auch programmgesteuert mit der CDK Toolkit Library verwendet werden. Sie bieten eine standardisierte Möglichkeit, Funktionen zu erweitern, z. B. alternative Quellen für Anmeldeinformationen.

Anmerkung

Das Plugin-System funktioniert zwar sowohl mit der CDK CLI als auch mit der CDK Toolkit Library, ist aber hauptsächlich für die Verwendung über die CLI vorgesehen. Wenn Sie die CDK Toolkit Library programmgesteuert verwenden, gibt es oft einfachere und direktere Möglichkeiten, dieselben Aufgaben ohne Plugins zu erledigen, insbesondere für die Verwaltung von Anmeldeinformationen.

Derzeit unterstützt das CDK Toolkit eine Plugin-Funktion:

  • Anbieter von benutzerdefinierten AWS Anmeldeinformationen — Erstellen Sie alternative Methoden, um AWS Anmeldeinformationen zu erhalten, die über die integrierten Mechanismen hinausgehen.

Wie erstellt man Plugins

Um ein CDK Toolkit-Plugin zu erstellen, erstellen Sie zunächst ein in TypeScript oder verfasstes Modul Node.js JavaScript, das vom CDK Toolkit geladen werden kann. Dieses Modul exportiert ein Objekt mit einer bestimmten Struktur, die das CDK Toolkit erkennen kann. Das exportierte Objekt muss mindestens eine Versionskennung und eine Initialisierungsfunktion enthalten, die eine IPluginHost Instanz empfängt, die das Plugin verwendet, um seine Fähigkeiten zu registrieren.

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
Gemeinsames 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' };
Anmerkung

CDK Toolkit-Plugins werden als CommonJS-Module geladen. Du kannst dein Plugin als ECMAScript Modul (ESM) bauen, musst dich aber an einige Einschränkungen halten:

  • Das Modul darf keine Module der obersten Ebene enthalten oder Module importierenawait, die die oberste Ebene enthalten. await

  • Das Modul muss die Kompatibilität sicherstellen, indem es das Plugin-Objekt unter dem module.exports Exportnamen exportiert:. export { plugin as 'module.exports' }

Wie lade ich Plugins mit der CDK CLI

Sie haben zwei Möglichkeiten, Plugins zu spezifizieren:

Option 1: Verwenden Sie die --plugin Befehlszeilenoption
# Load a single plugin $ cdk list --plugin=my-custom-plugin # Load multiple plugins $ cdk deploy --plugin=custom-plugin-1 --plugin=custom-plugin-2

Der Wert des --plugin Arguments sollte eine JavaScript Datei sein, die, wenn sie über die require() Funktion Node.js importiert wird, ein Objekt zurückgibt, das die Plugin Schnittstelle implementiert.

Option 2: Fügen Sie Einträge zu Konfigurationsdateien hinzu

Sie können der projektspezifischen cdk.json Datei oder der ~/.cdk.json globalen Konfigurationsdatei Plugin-Spezifikationen hinzufügen:

{ "plugin": [ "custom-plugin-1", "custom-plugin-2" ] }

Bei beiden Ansätzen lädt die CDK-CLI die angegebenen Plugins, bevor Befehle ausgeführt werden.

Laden Sie Plugins mit der CDK Toolkit Library in Code

Wenn Sie programmgesteuert mit der CDK Toolkit Library arbeiten, können Sie Plugins mithilfe der Instanz aus dem Paket direkt in Ihren Code laden. PluginHost @aws-cdk/toolkit-lib Das PluginHost bietet eine load() Methode zum Laden von Plugins nach Modulname oder Pfad.

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

Die load() Methode verwendet einen einzigen ParametermoduleSpec, nämlich den Namen oder Pfad des zu ladenden Plugin-Moduls. Das kann entweder sein:

  • Ein im node_modules Verzeichnis installierter Modulname Node.js.

  • Ein relativer oder absoluter Dateipfad zu einem JavaScript TypeScript OR-Modul.

Implementierung von Credential Provider-Plugins

Der aktuelle Hauptanwendungsfall für Plugins ist die Erstellung benutzerdefinierter Anbieter für AWS Anmeldeinformationen. Wie die AWS CLI benötigt auch die CDK-CLI AWS Anmeldeinformationen für die Authentifizierung und Autorisierung. Es gibt jedoch mehrere Szenarien, in denen die Standardauflösung von Anmeldeinformationen fehlschlagen könnte:

  • Die ursprünglichen Anmeldeinformationen können nicht abgerufen werden.

  • Das Konto, zu dem die ersten Anmeldeinformationen gehören, kann nicht abgerufen werden.

  • Das mit den Anmeldeinformationen verknüpfte Konto unterscheidet sich von dem Konto, auf dem die CLI zu arbeiten versucht.

Um diesen Szenarien gerecht zu werden, unterstützt das CDK Toolkit Credential Provider-Plugins. Diese Plugins implementieren die CredentialProviderSource Schnittstelle aus dem @aws-cdk/cli-plugin-contract Paket und werden mithilfe der Methode im Toolkit registriert. registerCredentialProviderSource Auf diese Weise kann das CDK Toolkit AWS Anmeldeinformationen aus nicht standardmäßigen Quellen wie speziellen Authentifizierungssystemen oder benutzerdefinierten Anmeldeinformationsspeichern abrufen.

Um einen benutzerdefinierten Anbieter für Anmeldeinformationen zu implementieren, erstellen Sie eine Klasse, die die erforderliche Schnittstelle implementiert:

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
Gemeinsames 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' };
Wichtig

Von Anbietern erhaltene Anmeldeinformationen werden vom CDK Toolkit zwischengespeichert. Es wird dringend empfohlen, dass die von Ihrem Anbieter zurückgegebenen Anmeldeinformationsobjekte sich selbst aktualisieren, um Ablaufprobleme bei lang andauernden Vorgängen zu vermeiden. Weitere Informationen finden Sie in der Dokumentation zum AWS SDK für Version 3. JavaScript

Weitere Informationen

Weitere Informationen zu den CDK Toolkit-Plugins finden Sie im AWS CDK Toolkit-Plugin-Vertrag im Repository. aws-cdk-cli GitHub