Configurar complementos para el kit de herramientas CDK - AWS Kit Cloud Development Kit (AWS CDK) v2

Esta es la guía para desarrolladores de AWS CDK v2. La primera versión del CDK pasó a la etapa de mantenimiento el 1.° de junio de 2022 y no cuenta con soporte desde el 1.° de junio de 2023.

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Configurar complementos para el kit de herramientas CDK

El kit de herramientas de AWS CDK admite complementos que añaden nuevas capacidades a sus flujos de trabajo de CDK. Los complementos están diseñados principalmente para usarse con la interfaz de línea de comandos CDK (CDK CLI), aunque también se pueden usar con la biblioteca del kit de herramientas CDK mediante programación. Proporcionan una forma estandarizada de ampliar la funcionalidad, como las fuentes de credenciales alternativas.

nota

Si bien el sistema de complementos funciona tanto con la CLI de CDK como con la biblioteca del kit de herramientas de CDK, está diseñado principalmente para su uso en CLI. Cuando se utiliza la biblioteca del kit de herramientas del CDK mediante programación, a menudo hay formas más sencillas y directas de realizar las mismas tareas sin complementos, especialmente en lo que respecta a la administración de credenciales.

Actualmente, el kit de herramientas del CDK admite una función de complemento:

  • Proveedores de AWS credenciales personalizados: cree métodos alternativos para obtener AWS credenciales más allá de los mecanismos integrados.

¿Cómo crear complementos

Para crear un complemento del kit de herramientas de CDK, primero debe crear un módulo de Node.js, creado en TypeScript o JavaScript, que se pueda cargar con el kit de herramientas de CDK. Este módulo exporta un objeto con una estructura específica que el kit de herramientas del CDK puede reconocer. Como mínimo, el objeto exportado debe incluir un identificador de versión y una función de inicialización que reciba una IPluginHost instancia, que el complemento utiliza para registrar sus capacidades.

TypeScript
Common.JS
// 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
JS común
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' };
nota

Los complementos de CDK Toolkit se cargan como módulos CommonJS. Puedes crear tu complemento como un ECMAScript módulo (ESM), pero debes cumplir con algunas restricciones:

  • El módulo no puede contener el nivel superior await ni importar ningún módulo que contenga el nivel superior. await

  • El módulo debe garantizar la compatibilidad exportando el objeto del complemento con el nombre de module.exports exportación:. export { plugin as 'module.exports' }

Cómo cargar complementos con la CLI de CDK

Tiene dos opciones para especificar los complementos:

Opción 1: utilice la opción de línea de --plugin comandos
# Load a single plugin $ cdk list --plugin=my-custom-plugin # Load multiple plugins $ cdk deploy --plugin=custom-plugin-1 --plugin=custom-plugin-2

El valor del --plugin argumento debe ser un JavaScript archivo que, al importarse mediante la require() función Node.js, devuelva un objeto que implemente la Plugin interfaz.

Opción 2: añadir entradas a los archivos de configuración

Puede añadir las especificaciones del complemento al cdk.json archivo específico del proyecto o al archivo de configuración ~/.cdk.json global:

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

Con cualquiera de los dos enfoques, la CLI de CDK cargará los complementos especificados antes de ejecutar los comandos.

Cargue los complementos en código con la biblioteca del kit de herramientas CDK

Al trabajar con la biblioteca del kit de herramientas del CDK mediante programación, puede cargar los complementos directamente en el código utilizando la instancia del paquete. PluginHost @aws-cdk/toolkit-lib PluginHostProporciona un load() método para cargar los complementos por nombre o ruta del módulo.

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

El load() método toma un único parámetromoduleSpec, que es el nombre o la ruta del módulo del complemento que se va a cargar. Puede ser una de las siguientes opciones:

  • Un nombre de módulo Node.js instalado en el node_modules directorio.

  • Una ruta de archivo relativa o absoluta a un TypeScript módulo JavaScript o.

Implementación de complementos para proveedores de credenciales

El principal caso de uso actual de los complementos es crear proveedores de AWS credenciales personalizados. Al igual que la AWS CLI, la CLI de CDK necesita AWS credenciales para la autenticación y la autorización. Sin embargo, hay varios escenarios en los que la resolución de credenciales estándar podría fallar:

  • No se puede obtener el conjunto inicial de credenciales.

  • No se puede obtener la cuenta a la que pertenecen las credenciales iniciales.

  • La cuenta asociada a las credenciales es diferente de la cuenta en la que la CLI intenta operar.

Para abordar estos escenarios, el kit de herramientas CDK admite los complementos de los proveedores de credenciales. Estos complementos implementan la CredentialProviderSource interfaz del @aws-cdk/cli-plugin-contract paquete y se registran en el kit de herramientas mediante el método. registerCredentialProviderSource Esto permite al CDK Toolkit obtener AWS credenciales de fuentes no estándar, como sistemas de autenticación especializados o almacenes de credenciales personalizados.

Para implementar un proveedor de credenciales personalizado, cree una clase que implemente la interfaz requerida:

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
JS común
// 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' };
importante

El CDK Toolkit almacena en caché las credenciales obtenidas de los proveedores. Se recomienda encarecidamente que los objetos de credenciales devueltos por el proveedor se actualicen automáticamente para evitar problemas de caducidad durante las operaciones de larga duración. Para obtener más información, consulte la documentación sobre las credenciales del AWS SDK para JavaScript la versión 3.

Más información

Para obtener más información sobre los complementos del CDK Toolkit, consulta el contrato del complemento del AWS CDK Toolkit en el repositorio. aws-cdk-cli GitHub