How to Mock AWS Secrets Manager in Python
Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.
Python code
40 linesimport json
from typing import Optional
class MockSecretsManager:
"""A simple mock of AWS Secrets Manager's get_secret_value API."""
def __init__(self):
self._secrets: dict[str, str] = {}
def create_secret(self, secret_id: str, secret_value: str) -> None:
"""Store a secret value under a given ID."""
self._secrets[secret_id] = secret_value
def get_secret_value(self, secret_id: str) -> Optional[str]:
"""Fetch a secret's string value by ID, or None if not found."""
return self._secrets.get(secret_id)
if __name__ == "__main__":
mock_client = MockSecretsManager()
# Seed with sample data
mock_client.create_secret("prod/db/password", "s3cr3t-p@ssw0rd")
mock_client.create_secret("dev/api/key", "dev_key_12345")
# Fetch and display results
db_secret = mock_client.get_secret_value("prod/db/password")
api_secret = mock_client.get_secret_value("dev/api/key")
missing_secret = mock_client.get_secret_value("nonexistent/secret")
print(f"DB password: {db_secret}")
print(f"API key: {api_secret}")
print(f"Missing secret: {missing_secret}")
# Demonstrate parsing as JSON
mock_client.create_secret("service/config", json.dumps({"timeout": 30, "retries": 3}))
config_raw = mock_client.get_secret_value("service/config")
config = json.loads(config_raw) if config_raw else {}
print(f"Config timeout: {config.get('timeout')}")
Output
DB password: s3cr3t-p@ssw0rd
API key: dev_key_12345
Missing secret: None
Config timeout: 30
How it works
The MockSecretsManager class stores secrets in an internal dictionary keyed by secret ID, mirroring how Secrets Manager organizes data. The get_secret_value method uses .get() to safely return None for missing secrets instead of raising an exception. The if __name__ == '__main__' block seeds sample secrets and demonstrates both direct string retrieval and JSON parsing. This approach lets you test code that depends on Secrets Manager without making real AWS calls or mocking the boto3 client. The mock maintains the same method signature as the real AWS SDK, making it a drop-in replacement for unit tests.
Common mistakes
- Forgetting that real Secrets Manager returns bytes, not strings
- Not handling None when a secret ID doesn't exist
- Hardcoding secret values instead of seeding them via create_secret
Variations
- Use unittest.mock.patch to replace boto3 client methods instead of a custom class
- Extend the mock to support get_secret_value with version_id parameters
Real-world use cases
- Unit testing application code that fetches database credentials from Secrets Manager in CI/CD pipelines.
- Developing locally against a microservice that requires secret retrieval without AWS credentials.
- Writing integration tests that simulate secret rotation scenarios for production deployment validation.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.