import abc from typing import Dict import boto3 class SecretManager(abc.ABC): @abc.abstractmethod def get_secret(self, name: str) -> str: pass @abc.abstractmethod def add_secret(self, name: str, value: str) -> str: pass class InMemorySecretManager(SecretManager): def __init__(self): self._secrets: Dict[str, str] = {} def get_secret(self, name: str) -> str: return self._secrets[name] def add_secret(self, name: str, value: str): self._secrets[name] = value class Boto3SecretManager(SecretManager): def __init__(self): self._cache: Dict[str, str] = {} def get_secret(self, name: str) -> str: """ This needs AWS default config (or profile named "fansifter") """ if name not in self._cache: region_name = "eu-west-1" # Create a Secrets Manager client session = boto3.session.Session() # profile_name='fansifter' client = session.client( service_name="secretsmanager", region_name=region_name ) get_secret_value_response = client.get_secret_value(SecretId=name) self._cache[name] = get_secret_value_response["SecretString"] return self._cache[name] def add_secret(self, name: str, value: str) -> str: raise RuntimeError( "Adding new secret is not supported for boto3 implementation." ) def setup_secret_manager() -> SecretManager: from .settings import TESTING # Use in memory instance for unit testing if TESTING: return InMemorySecretManager() return Boto3SecretManager() secret_manager = setup_secret_manager() # Add shortcut get_secret = secret_manager.get_secret