· 5 years ago · Mar 10, 2021, 02:26 PM
1// Use this code snippet in your app.
2// If you need more information about configurations or implementing the sample code, visit the AWS docs:
3// https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-samples.html#prerequisites
4
5public static void getSecret() {
6
7 String secretName = "prod/api/envvars";
8 Region region = Region.of("eu-central-1");
9
10 // Create a Secrets Manager client
11 SecretsManagerClient client = SecretsManagerClient.builder()
12 .region(region)
13 .build();
14
15 // In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
16 // See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
17 // We rethrow the exception by default.
18
19 String secret, decodedBinarySecret;
20 GetSecretValueRequest getSecretValueRequest = GetSecretValueRequest.builder()
21 .secretId(secretName)
22 .build();
23 GetSecretValueResponse getSecretValueResponse = null;
24
25 try {
26 getSecretValueResponse = client.getSecretValue(getSecretValueRequest);
27 } catch (DecryptionFailureException e) {
28 // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
29 // Deal with the exception here, and/or rethrow at your discretion.
30 throw e;
31 } catch (InternalServiceErrorException e) {
32 // An error occurred on the server side.
33 // Deal with the exception here, and/or rethrow at your discretion.
34 throw e;
35 } catch (InvalidParameterException e) {
36 // You provided an invalid value for a parameter.
37 // Deal with the exception here, and/or rethrow at your discretion.
38 throw e;
39 } catch (InvalidRequestException e) {
40 // You provided a parameter value that is not valid for the current state of the resource.
41 // Deal with the exception here, and/or rethrow at your discretion.
42 throw e;
43 } catch (ResourceNotFoundException e) {
44 // We can't find the resource that you asked for.
45 // Deal with the exception here, and/or rethrow at your discretion.
46 throw e;
47 }
48
49 // Decrypts secret using the associated KMS CMK.
50 // Depending on whether the secret is a string or binary, one of these fields will be populated.
51 if (getSecretValueResponse.secretString() != null) {
52 secret = getSecretValueResponse.secretString();
53 }
54 else {
55 decodedBinarySecret = new String(Base64.getDecoder().decode(getSecretValueResponse.secretBinary().asByteBuffer()).array());
56 }
57
58 // Your code goes here.
59}