Configurar plug-ins para o CDK Toolkit - AWS Kit de desenvolvimento em nuvem (AWS CDK) v2

Este é o Guia do desenvolvedor do AWS CDK v2. O CDK v1 antigo entrou em manutenção em 1º de junho de 2022 e encerrou o suporte em 1º de junho de 2023.

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Configurar plug-ins para o CDK Toolkit

O AWS CDK Toolkit oferece suporte a plug-ins que adicionam novos recursos aos seus fluxos de trabalho do CDK. Os plug-ins são projetados principalmente para uso com a CDK Command Line Interface (CDK CLI), embora também possam ser usados programaticamente com a CDK Toolkit Library. Eles fornecem uma forma padronizada de ampliar a funcionalidade, como fontes alternativas de credenciais.

nota

Embora o sistema de plug-ins funcione com a CDK CLI e a CDK Toolkit Library, ele se destina principalmente ao uso da CLI. Ao usar a CDK Toolkit Library programaticamente, geralmente há maneiras mais simples e diretas de realizar as mesmas tarefas sem plug-ins, principalmente para gerenciamento de credenciais.

Atualmente, o CDK Toolkit oferece suporte a um recurso de plug-in:

  • Provedores de AWS credenciais personalizados - Crie métodos alternativos para obter AWS credenciais além dos mecanismos integrados.

Como criar plug-ins

Para criar um plug-in do CDK Toolkit, primeiro você cria um módulo Node.js, criado em TypeScript ou JavaScript, que pode ser carregado pelo CDK Toolkit. Esse módulo exporta um objeto com uma estrutura específica que o CDK Toolkit pode reconhecer. No mínimo, o objeto exportado deve incluir um identificador de versão e uma função de inicialização que receba uma IPluginHost instância, que o plug-in usa para registrar seus recursos.

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' };
nota

Os plug-ins do CDK Toolkit são carregados como módulos CommonJS. Você pode criar seu plug-in como um ECMAScript módulo (ESM), mas precisa seguir algumas restrições:

  • O módulo não pode conter o nível superior await nem importar nenhum módulo que contenha o nível superiorawait.

  • O módulo deve garantir a compatibilidade exportando o objeto do plug-in com o nome de module.exports exportação:export { plugin as 'module.exports' }.

Como carregar plug-ins com a CLI do CDK

Você tem duas opções para especificar plug-ins:

Opção 1: usar a opção de linha de --plugin comando
# Load a single plugin $ cdk list --plugin=my-custom-plugin # Load multiple plugins $ cdk deploy --plugin=custom-plugin-1 --plugin=custom-plugin-2

O valor do --plugin argumento deve ser um JavaScript arquivo que, quando importado por meio da require() função Node.js, retorne um objeto que implementa a Plugin interface.

Opção 2: Adicionar entradas aos arquivos de configuração

Você pode adicionar especificações do plug-in ao cdk.json arquivo específico do projeto ou ao arquivo de configuração ~/.cdk.json global:

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

Com qualquer abordagem, a CLI do CDK carregará os plug-ins especificados antes de executar os comandos.

Carregue plug-ins em código com a biblioteca do CDK Toolkit

Ao trabalhar com a CDK Toolkit Library de forma programática, você pode carregar plug-ins diretamente no seu código usando a PluginHost instância do pacote. @aws-cdk/toolkit-lib PluginHostFornece um load() método para carregar plug-ins por nome ou caminho do 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

O load() método usa um único parâmetro,moduleSpec, que é o nome ou caminho do módulo do plug-in a ser carregado. Isso pode ser:

  • Um nome de módulo Node.js instalado no node_modules diretório.

  • Um caminho de arquivo relativo ou absoluto para um TypeScript módulo JavaScript ou.

Implementando plug-ins de provedores de credenciais

O principal caso de uso atual dos plug-ins é criar provedores de AWS credenciais personalizados. Assim como a AWS CLI, a CLI do CDK AWS precisa de credenciais para autenticação e autorização. No entanto, há vários cenários em que a resolução de credenciais padrão pode falhar:

  • O conjunto inicial de credenciais não pode ser obtido.

  • A conta à qual as credenciais iniciais pertencem não pode ser obtida.

  • A conta associada às credenciais é diferente da conta na qual a CLI está tentando operar.

Para lidar com esses cenários, o CDK Toolkit oferece suporte a plug-ins de provedores de credenciais. Esses plug-ins implementam a CredentialProviderSource interface do @aws-cdk/cli-plugin-contract pacote e são registrados no Toolkit usando o registerCredentialProviderSource método. Isso permite que o CDK Toolkit obtenha AWS credenciais de fontes não padronizadas, como sistemas de autenticação especializados ou armazenamentos de credenciais personalizados.

Para implementar um provedor de credenciais personalizado, crie uma classe que implemente a interface necessária:

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' };
Importante

As credenciais obtidas dos provedores são armazenadas em cache pelo CDK Toolkit. É altamente recomendável que os objetos de credenciais retornados pelo seu provedor sejam atualizados automaticamente para evitar problemas de expiração durante operações de longa duração. Para obter mais informações, consulte Credenciais na documentação do AWS SDK para JavaScript v3.

Saiba mais

Para saber mais sobre os plug-ins do CDK Toolkit, consulte o Contrato do plug-in do AWS CDK Toolkit no repositório. aws-cdk-cli GitHub