"""Fetch Credentials from AWS secrets manager for QA Royalty Accounting DB connection.""" import json import logging from typing import Any import boto3 from botocore.exceptions import ClientError from tests import config logger = logging.getLogger(__name__) def get_secret( secret_name: str, region_name: str = config.AWS_REGION ) -> dict[str, Any]: """ Retrieve and return the secret as a dictionary from AWS Secrets Manager. Args: secret_name (str): The name or ARN of the secret to retrieve. region_name (str): The AWS region where the secret is stored. Defaults to AWS_REGION from config. Returns: dict[str, Any]: A dictionary containing the secret data parsed from JSON. Raises: ClientError: If the secret cannot be retrieved from AWS Secrets Manager. """ session = boto3.session.Session() client = session.client('secretsmanager', region_name=region_name) try: secret = client.get_secret_value(SecretId=secret_name)['SecretString'] secret_data: dict[str, Any] = json.loads(secret) return secret_data except ClientError: logger.error( f"Error retrieving secret from AWS Secrets Manager for secret '{secret_name}'", exc_info=True, ) raise