Full Guide on AWS Secret Manager | How to Create-Store Fetch Secret Manager

Finwithtech

There are various instances where you are using tokens, credentials, API keys, and password usernames to access any services. One example is, that to log into your SQL Server you need to use IP, username, password, and port. But storing this in a plane text or inside your code is not the best idea in today’s world where hackers are moving all around. In Indian Hindi language, we have one quote-

                ‘Najar Hati Durghatna ghati’ means ‘focus Loose accident happens’.

Anyone who has access to your codebase may get access to production dB and knowingly or unknowingly they can update or delete something from production. To avoid the above situation to some extent, Amazon launched one of the AWS Services called Secret Manager. As the name suggests, this service is used to manage our Secrets. In this article, I‘ll talk about how to secret and retrieve programmatically and I will also discuss with code examples how to implement a secret manager in Java and how to use the secret manager in cron jobs.

AWS SECRET MANAGER

Secret Manager is an AWS Service that allows us to store our secrets such as Usernames, passwords, and many more. With Secret Manager, one can easily rotate, retrieve, and manage credentials. In the leh-man language, ‘We will store our credentials in a variable which will be saved in AWS Secret Manager, and we will call the variable in our code in place of actual credentials. Secret Manager Service is extended to store any type of secret, including API keys and Auth tokens. Also, Secret Manager can be integrated with IAM roles and permission where you don’t have access to read from AWS Console, but you can retrieve the secret from AWS CLI. Let’s get started step by step

Create and store the secret

To create the secret in the secret manager you can use the AWS Secrets manager console or AWS CLI.

Also, Read about ‘Installation of java in mac’

Secrets Manager Console

 1: Sign in to the console at: https://console.aws.amazon.com/secretsmanager/

2: On the Secrets page, click on Store a new Secret

Secret manager

3. Now Select ‘ Other Type of Secret’. Other types of secret will help you in storing key-value pairs or plain text. Then you can specify the key and value such as ‘username’ and value ‘admin’.

Secret Manager

Then in the ‘Select Encryption key’ select DefaultEncryptionKey. Aws Secret manager will always encrypt the secret when you select this, and the best part of this is that this option is as no extra charge.

Click on Next.

Under Secret Name, type a name for the secret. It can be alphanumeric. If you are going to maintain a huge number of secrets, then do follow some naming standards i.e. company/prod/dB secrets. Also, you can add names, descriptions, and tags if you want..

Double-check the final details, and if this is all right you can proceed. Hold on! Here you will also get a Code Snippet to add to your code base. Be it in java, python, Dotnet, JavaScript or Ruby Secret manager supports all languages.

 

Read : .Net Core Interview Questions

Create Secret using Secret Manager CLI

  1. Secret Manager CLI To create the secret via AWS CLI, you need to install the AWS CLI (https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)

 

  1. To create the secret run the following command:                    aws secretsmanager create-secret –name tutorial/firstkey 2–description “Basic Create Secret” –secret-string ‘{“username”:”admin”}’

Retrieving the secret from Secret Manager

Retrieve Secret manager from AWS console

  1. Log in to Secret manager console:

https://console.aws.amazon.com/secretsmanager/

  1. On the page of Secret list, click on the secret name which you created and then click on ‘Retrieve Secret Value’
  2. Yeaaa! You can see the secret in key-value pair and json format.

Retrieve Secret manager using AWS CLI

To fetch the secret from AWS CLI, you need to have AWS CLI configured and inside AWS CLI you can run the below command

 

aws secretsmanager get-secret-value –secret-id <secret-name> –region <region> –version-stage AWSCURRENT.

Configure Secret Manager in Java Code

Now that we have created the secret and also we can also fetch the secret from the secret manager, we will see how to implement the secret manager in Java code. So to integrate the secret manager in Java code, you can follow the below code snippet step-by-step

				
					public String getSecret(String secretName) {
		long requestStartTime = System.currentTimeMillis()/1000;
		String	region = ‘ap-souteast-1’		
			// Create a Secrets Manager client
			SecretsManagerClient secretsManagerClient = (SecretsManagerClient)((SecretsManagerClientBuilder)SecretsManagerClient.builder()
					.region(Region.of(region))).build();
			try {
	            GetSecretValueRequest valueRequest = GetSecretValueRequest.builder()
	                .secretId(secretName)
	                .build();
	            GetSecretValueResponse valueResponse = secretsManagerClient.getSecretValue(valueRequest);           
	            String secret = valueResponse.secretString();
	            //System.out.println("String: "+ secret);
	            return secret.toString();

	        } catch (SecretsManagerException e) {
	            System.err.println(e.awsErrorDetails().errorMessage());
	            System.exit(1);
	        }
			
			System.out.println(System.currentTimeMillis()/1000 - requestStartTime);
			
			return region;
					
	    }

				
			

The above code will fetch the raw secret from your secret manager in JSON format. As the output is in JSON format we need to deserialize the JSON in the string, to deserialize the JSON in Java we need to import ‘import org.json.JSONObject;’ and we will use the below code to connect with our database

				
					Public class fetchSecret(String stringJsonObj){
try{
JSONObject dbSecret= new JSONObject(stringJsonObj);
	String username = dbSecret.getString("db_username");
	String password = dbSecret.getString("db_password");
	String endpoint = dbSecret.getString("db_endpoint");
	String port = dbSecret.getString("db_port");
	String serviceId  = dbSecret.getString("db_name");

String connectionString = ("jdbc:oracle:thin:@"+ endpoint +":" + port + ":" + serviceId);
}
catch(Exception e) {
e.printStackTrace();
}
}

				
			

Implement Secret manager in Cron Jobs

Install jq before running the below command. You can install jq using , yum install jq. After installing JQ, we will write the script to fetch the secret manager in cron job.

				
					xyz=`echo $(aws secretsmanager get-secret-value --secret-id <secretname> --region <region> --version-stage AWSCURRENT|jq --raw-output .SecretString)`
uname=`echo  $xyz | jq -r ."username"`
pwd=`echo  $xyz | jq -r ."password"`
<oraclepath>/bin/sqlplus $uname/$pwd@SID path/file.sql;

				
			

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.