使用 Java AWS SDK 获取 Secrets Manager 密钥值 - AWS Secrets Manager

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 Java AWS SDK 获取 Secrets Manager 密钥值

在应用程序中,您可以通过在任何 AWS SDK 中调用 GetSecretValueBatchGetSecretValue 来检索密钥。不过,我们建议您通过使用客户端缓存来缓存您的密钥值。缓存密钥可以提高速度并降低成本。

以下代码示例演示如何使用 GetSecretValue

所需权限: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); } } }