Problem Statement: Use boto3 library in Python to get the secret keys as plain text from binary/encrypted format present in AWS Secret Manager
Approach/Algorithm to solve this problem
Step 1: Import boto3 and botocore exceptions to handle exceptions.
Step 2: secret_stored_location is the required parameter. It is a place where secrets are saved.
Step 3: Create an AWS session using boto3 lib. Make sure region_name is mentioned in the default profile. If it is not mentioned, then explicitly pass the region_name while creating the session.
Step 4: Create an AWS client for secretmanager.
Step 5: Call get_secret_value and pass the secret_stored_location as SecretId.
Step 6: Check whether it is plain text or encrypted one.
Step 7: If it is encrypted one, call the function to decode binary values using base64.b64decode
Step 8: It returns all the secrets as decrypted mode, i.e., plain text in the given location.
Step 9: Handle the generic exception if something went wrong while retrieving values.
Example Code
Use the following code to get the decrypted plain text secret from AWS secret Manager −
import boto3 from botocore.exceptions import ClientError def get_decrypted_secret_details(secret_stored_location): session = boto3.session.Session() s3_client = session.client('secretmanager') try: response = s3_client.get_secret_value(SecretId=secret_stored_location) if not ('SecretString' in response): decoded_secret_values = base64.b64decode(response['SecretBinary']) return decoded_secret_values except ClientError as e: raise Exception("boto3 client error in get_decrypted_secret_details: " + e.__str__()) except Exception as e: raise Exception("Unexpected error in get_decrypted_secret_details: " + e.__str__()) a = get_decrypted_secret_details('/secrets/aws') print(a)
Output
{"user":"SERVICE_USER","accesskey":"I**************"}