Search code examples
javaamazon-web-servicesmavenaws-secrets-managersecret-key

How do retrieve the specific value of an AWS Secrets Manager secret?


I have this java code that retrieves the values from a secret:

public class fetchSecrets {
    public static void main(String[] args) {
        String secretId = "test";
        SecretsManagerClient secretsClient = SecretsManagerClient.builder()
                .region(Region.EU_WEST_1)
                .build();
        fetchPassword(secretsClient, secretId);
        secretsClient.close();
    }

    public static void fetchPassword(SecretsManagerClient secretsClient, String secretId) {
        try {
            GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
                .secretId(secretId)
                .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);
        }
    }
}

When I run this code, I get:

{"username":"test","password":"password123456"}

How do i output only the value of the password or the username keys?

So expected output is e.g. password123456


Solution

  • Turns out I had to create a json object and pass in the string to extract its value:

    try {
        GetSecretValueRequest request = GetSecretValueRequest.builder()
               .secretId(secretId)
               .build();
    
        GetSecretValueResponse valueResponse = secretsClient.getSecretValue(request);
        String secret = valueResponse.secretString();
    
        //defining a JSON string     
        Object obj = JSONValue.parse(secret); 
       
        //creating an object of JSONObject class
        //and casting the object into JSONObject type  
        JSONObject jsonObject = (JSONObject) obj;   
     
        //getting values form the JSONObject
        //and casting that values into corresponding types  
        String username = (String) jsonObject.get("username");    
    
        //printing the values   
        System.out.println(username); 
    
    } catch (SecretsManagerException e) {
        System.err.println(e.awsErrorDetails().errorMessage());
        System.exit(1);
    }
    

    Output : password123456