AWS Secrets Manager Caching

1.1.3 · active · verified Fri Apr 10

The `aws-secretsmanager-caching` library provides a client-side caching solution for AWS Secrets Manager. It helps reduce API calls to Secrets Manager, improving application performance and potentially lowering costs, by storing secret values in memory for a configurable duration. The current version is 1.1.3 and it is actively maintained by AWS.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `SecretCache` with optional configuration, retrieve a secret, and observe the caching behavior. Ensure your AWS credentials and region are configured (e.g., via environment variables or AWS CLI configuration) for `boto3` to work correctly. The `os.environ.get` calls are for demonstration purposes; replace `'my-test-secret'` with an actual secret name.

import os
import boto3
from aws_secretsmanager_caching import SecretCache, SecretCacheConfig

# Configure cache (optional, default values are usually good)
cache_config = SecretCacheConfig(
    max_cache_size=100,
    cache_item_ttl_in_milliseconds=3600000, # 1 hour
    stall_time_in_milliseconds=1000 # 1 second
)

# Initialize a Secrets Manager client (optional, can be passed to SecretCache)
# Ensure AWS credentials and region are configured via env vars or boto3 config
secrets_client = boto3.client(
    'secretsmanager',
    region_name=os.environ.get('AWS_REGION', 'us-east-1')
)

# Initialize the cache
cache = SecretCache(client=secrets_client, config=cache_config)

# Retrieve a secret
try:
    secret_name = os.environ.get('MY_SECRET_NAME', 'my-test-secret')
    secret_value = cache.get_secret_string(secret_name)
    print(f"Retrieved secret '{secret_name}': {secret_value}")

    # Subsequent calls will hit the cache until TTL expires
    secret_value_cached = cache.get_secret_string(secret_name)
    print(f"Retrieved secret (cached) '{secret_name}': {secret_value_cached}")

except Exception as e:
    print(f"Error retrieving secret: {e}")

finally:
    # It's good practice to close the cache when done, especially in short-lived processes
    cache.close()

view raw JSON →