Configuração de plug-ins para o Kit de Ferramentas CDK - 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á.

Configuração de plug-ins para o Kit de Ferramentas CDK

O Kit de Ferramentas CDK da AWS 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 interface de linha de comandos do CDK (CLI do CDK), embora também possam ser usados programaticamente com a Biblioteca do Kit de Ferramentas CDK. Eles fornecem uma forma padronizada de ampliar a funcionalidade, como fontes alternativas de credenciais.

nota

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

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

  • Provedores de credenciais da AWS personalizados: crie métodos alternativos para obter credenciais da AWS além dos mecanismos integrados.

Como criar plug-ins

Para criar um plug-in do Kit de Ferramentas CDK, primeiro você cria um módulo Node.js, criado em TypeScript ou JavaScript, que possa ser carregado pelo Kit de Ferramentas CDK. Esse módulo exporta um objeto com uma estrutura específica que o Kit de Ferramentas CDK 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 instância IPluginHost, que o plug-in usa para registrar seus recursos.

exemplo
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 Kit de Ferramentas CDK são carregados como módulos do CommonJS. É possível criar seu plug-in como um módulo de ECMAScript (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 superior await.

  • O módulo deve garantir a compatibilidade exportando o objeto do plug-in com o nome de exportação module.exports: 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 comando --plugin
# 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 argumento --plugin deve ser um arquivo de JavaScript que, quando importado por meio da função require() de Node.js, retorna um objeto que implementa a interface Plugin.

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

É possível adicionar especificações do plug-in ao arquivo cdk.json específico do projeto ou ao arquivo ~/.cdk.json de configuração 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.

Carregamento de plug-ins em código com a Biblioteca do Kit de Ferramentas CDK

Ao trabalhar com a Biblioteca do Kit de Ferramentas CDK de forma programática, é possível carregar plug-ins diretamente no seu código usando a instância PluginHost do pacote @aws-cdk/toolkit-lib. O PluginHost fornece um método load() para carregar plug-ins por nome ou caminho do módulo.

exemplo
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 método load() 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 do Node.js instalado no diretório node_modules.

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

Implementação de plug-ins de provedores de credenciais

O principal caso de uso atual dos plug-ins é criar provedores personalizados de credenciais da AWS. Assim como a AWS CLI, a CLI do CDK precisa de credenciais da AWS 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 Kit de Ferramentas CDK oferece suporte a plug-ins de provedores de credenciais. Esses plug-ins implementam a interface CredentialProviderSource do pacote @aws-cdk/cli-plugin-contract, e são registrados no Kit de Ferramentas usando o método registerCredentialProviderSource. Isso permite que o Kit de Ferramentas CDK obtenha credenciais da AWS 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:

exemplo
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 Kit de Ferramentas CDK. É 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 Credentials na Documentação do AWS SDK para JavaScript v3.

Saiba mais

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