Obtener un valor secreto de Secrets Manager con un SDK de AWS de Java
En las aplicaciones, puede recuperar sus secretos si llama a GetSecretValue o BatchGetSecretValue en cualquiera de los SDK de AWS. No obstante, se recomienda que almacene en caché sus valores secretos mediante el almacenamiento en caché del lado del cliente. El almacenado en caché de los secretos mejora la velocidad y reduce los costos.
-
Si almacena las credenciales de la base de datos en el secreto, utilice los controladores de conexión SQL de Secrets Manager para conectarse a una base de datos mediante esas credenciales.
-
Para otros tipos de secretos, utilice el componente de almacenamiento en caché basado en Java de Secrets Manager o llame al SDK directamente con
GetSecretValueoBatchGetSecretValue.
Los siguientes ejemplos de código muestran cómo utilizar GetSecretValue.
Permisos necesarios: secretsmanager:GetSecretValue
import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.secretsmanager.SecretsManagerClient; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueRequest; import software.amazon.awssdk.services.secretsmanager.model.GetSecretValueResponse; import software.amazon.awssdk.services.secretsmanager.model.SecretsManagerException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * We recommend that you cache your secret values by using client-side caching. * * Caching secrets improves speed and reduces your costs. For more information, * see the following documentation topic: * * https://docs.aws.amazon.com/secretsmanager/latest/userguide/retrieving-secrets.html */ public class GetSecretValue { public static void main(String[] args) { final String usage = """ Usage: <secretName>\s Where: secretName - The name of the secret (for example, tutorials/MyFirstSecret).\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String secretName = args[0]; Region region = Region.US_EAST_1; SecretsManagerClient secretsClient = SecretsManagerClient.builder() .region(region) .build(); getValue(secretsClient, secretName); secretsClient.close(); } public static void getValue(SecretsManagerClient secretsClient, String secretName) { try { GetSecretValueRequest valueRequest = GetSecretValueRequest.builder() .secretId(secretName) .build(); GetSecretValueResponse valueResponse = secretsClient.getSecretValue(valueRequest); String secret = valueResponse.secretString(); System.out.println(secret); } catch (SecretsManagerException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }