Skip to content

Secrets Manager

Utilities for working with AWS Secrets Manager.


get_secret_value

get_secret_value(
    secret_name: str,
    as_dict: Literal[False] = False,
    region: Optional[str] = None,
) -> str
get_secret_value(
    secret_name: str,
    as_dict: Literal[True],
    region: Optional[str] = None,
) -> Dict[str, Any]
get_secret_value(secret_name, as_dict=False, region=None)

Retrieves a Secrets Manager secret value

Parameters:

Name Type Description Default
secret_name str

the Secrets Manager secret name

required
as_dict bool

If True, return the secret as a dictionary. Defaults to False.

False
region Optional[str]

AWS region. Defaults to None.

None

Raises:

Type Description
ValueError

If there is no such key

Returns:

Type Description
Union[str, dict[str, Any]]

Union[str, dict]: The secret value stored at the key name, as string or dict

Source code in src/aibs_informatics_aws_utils/secretsmanager.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
def get_secret_value(
    secret_name: str, as_dict: bool = False, region: Optional[str] = None
) -> Union[str, dict[str, Any]]:
    """Retrieves a Secrets Manager secret value

    Args:
        secret_name (str): the Secrets Manager secret name
        as_dict (bool): If True, return the secret as a dictionary. Defaults to False.
        region (Optional[str]): AWS region. Defaults to None.

    Raises:
        ValueError: If there is no such key

    Returns:
        Union[str, dict]: The secret value stored at the key name, as string or dict
    """
    secretsmanager = get_secretsmanager_client(region=region)

    response = secretsmanager.get_secret_value(SecretId=secret_name)

    secret = response["SecretString"]
    if as_dict:
        return json.loads(secret)
    else:
        return secret