How to use Boto3 to restore all secret keys from a a specific location in AWS Secret Manager

Problem Statement: Use boto3 library in Python to restore all secret keys from specific location in AWS Secrets Manager.

Approach/Algorithm

  • Step 1: Import boto3 and botocore exceptions to handle exceptions.

  • Step 2: Define the secret_stored_location as the required parameter.

  • Step 3: Create an AWS session using boto3 library. Make sure region_name is mentioned in the default profile. If not specified, explicitly pass the region_name while creating the session.

  • Step 4: Create an AWS client for secretsmanager.

  • Step 5: Call restore_secret and pass the secret_stored_location as SecretId.

  • Step 6: It returns the metadata of the restored secret.

  • Step 7: Handle generic exceptions if something goes wrong while restoring the secret.

Example

Use the following code to restore secrets in AWS Secrets Manager ?

import boto3
from botocore.exceptions import ClientError

def restore_secret_details(secret_stored_location):
    session = boto3.session.Session()
    secrets_client = session.client('secretsmanager')
    try:
        response = secrets_client.restore_secret(SecretId=secret_stored_location)
        return response
    except ClientError as e:
        raise Exception("boto3 client error in restore_secret_details: " + e.__str__())
    except Exception as e:
        raise Exception("Unexpected error in restore_secret_details: " + e.__str__())

# Example usage
result = restore_secret_details('/secrets/aws')
print(result)

Output

{
    'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 
    'Name': '/secrets/aws', 
    'ResponseMetadata': {
        'RequestId': 'b32fe48d**************ab', 
        'HTTPStatusCode': 200, 
        'HTTPHeaders': {
            'date': 'Sat, 03 Apr 2021 09:40:48 GMT', 
            'content-type': 'application/x-amz-json-1.1', 
            'content-length': '197', 
            'connection': 'keep-alive', 
            'x-amzn-requestid': '*********************************'
        }, 
        'RetryAttempts': 0
    }
}

Key Points

  • The restore_secret function restores a secret that was previously scheduled for deletion.

  • Make sure you have proper AWS credentials configured before running this code.

  • The secret must have been previously deleted (scheduled for deletion) to be restored.

  • The function returns metadata about the restored secret, including its ARN and name.

Conclusion

The restore_secret method in boto3 allows you to restore previously deleted secrets from AWS Secrets Manager. Always handle exceptions properly when working with AWS services to ensure robust error handling.

Updated on: 2026-03-25T19:01:54+05:30

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements