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

Problem Statement: Use boto3 library in Python to delete all secret keys from a specific location 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.

  • 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 delete_secret and pass the secret_stored_location as SecretId.

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

  • Step 7: Handle the generic exception if something went wrong while deleting secret.

Example Code

Use the following code to delete secrets in AWS Secret Manager −

import boto3
from botocore.exceptions import ClientError

def delete_secret_details(secret_stored_location):
   session = boto3.session.Session()
   s3_client = session.client('secretmanager')
   response = s3_client.create_secret(SecretId=secret_stored_location)
   return response
   except ClientError as e:
      raise Exception("boto3 client error in delete_secret_details: " + e.__str__())
   except Exception as e:
      raise Exception("Unexpected error in delete_secret_details: " + e.__str__())

a = delete_secret_details('/secrets/aws')


{'ARN': 'arn:aws:secretsmanager:us-east-1:***************:secret:/secrets/aws-wr1Aj6', 'Name': '/secrets/aws', 'DeletionDate': datetime.datetime(2021, 5, 3, 15, 26, 19, 898000, tzinfo=tzlocal()), '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}}

Updated on: 16-Apr-2021


Kickstart Your Career

Get certified by completing the course

Get Started