Prerequisites
You already have configured AWS Credentials in ~/.aws/credentials
location
Overview
This post illustrates the utilization of Python, alongside libraries such as boto3
, to extract secrets from an AWS account along with their last access dates. With this method, we can generate a report identifying unused secrets.
Explanation with Inline Comments
import boto3
from botocore.exceptions import ClientError
def list_secrets_with_last_access_date():
# Create a Secrets Manager client using the default AWS credentials and region
client = boto3.client(service_name='secretsmanager')
# Try to retrieve the list of secrets with last accessed details
try:
secrets_list = []
# Paginator helps in handling large responses that are split into multiple pages
paginator = client.get_paginator('list_secrets')
# Loop through each page provided by the paginator
for page in paginator.paginate():
# Each 'secret' is a dictionary containing details of a secret stored in AWS Secrets Manager
for secret in page['SecretList']:
# Extract the 'Name' and 'LastAccessedDate' of each secret
secret_info = {
'Name': secret['Name'],
'LastAccessedDate': secret.get('LastAccessedDate')
}
# Add the dictionary with the secret information to the list
secrets_list.append(secret_info)
# Return the list of secrets with their access details
return secrets_list
# Handle exceptions that may occur during API calls
except ClientError as e:
print(f"An error occurred: {e}")
# Return None if an error occurs
return None
# Example usage:
secrets = list_secrets_with_last_access_date()
# Check if the secrets list is not empty or None
if secrets:
print("List of Secrets with Last Access Date:")
for secret in secrets:
# Format the last accessed date if available, or provide a placeholder
last_accessed = secret['LastAccessedDate'].strftime("%Y-%m-%d") if secret[
'LastAccessedDate'] else "Not Available"
print(f"Secret: {secret['Name']}, Last Accessed: {last_accessed}")
else:
print("No secrets found or unable to retrieve secrets.")
Boto3 Client Initialization
client = boto3.client(service_name='secretsmanager')
The script begins by creating a client object for interacting with AWS Secrets Manager. This client uses the default AWS credentials and region configured in your environment, facilitating seamless API calls to AWS services.
Using Paginator to Retrieve Secrets
paginator = client.get_paginator('list_secrets')
AWS responses can be large, and handling them might require multiple API calls. The Paginator object simplifies this by automating the pagination of responses. Here, we use it to paginate through all secrets managed by AWS Secrets Manager.
Looping Through Pages and Secrets
for page in paginator.paginate():
for secret in page['SecretList']:
The script loops through each page returned by the paginator. Each page contains a list of secrets, and the script iterates through each secret to extract relevant information.
Extracting Secret Details
secret_info = {
'Name': secret['Name'],
'LastAccessedDate': secret.get('LastAccessedDate')
}
secrets_list.append(secret_info)
For every secret, the script extracts the name and the last accessed date. This information is then added to a list, which will eventually contain all the secrets along with their last accessed dates.