How to use Boto3 to get a list of all secrets in AWS Secret Manager

Problem Statement: Use boto3 library in Python to get a list of all secrets in AWS Secret Manager

Approach/Algorithm to solve this problem

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

  • Step 2: There are no parameters here.

  • 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 list_secrets function to retrieve all secrets.

  • Step 6: It returns the metadata of all secrets.

  • Step 7: Handle the generic exception if something went wrong while getting details of all secrets.

Example Code

Use the following code to get the list of all secrets in AWS Secret Manager −

import boto3
from botocore.exceptions import ClientError

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

a = get_all_secrets()
for details in a['SecretList']: