Updated so it now can either read from a path or environment variable
This commit is contained in:
1 parent
c2aa63ec54
commit
dd5bd18bcb
3 files changed
+33
-9
No files matched your search
@@ -1,9 +1,35 @@
|
||||
from simple_logger_handler import setup_logger
|
||||
import logging
|
||||
import os
|
||||
from typing import Set
|
||||
|
||||
logger = setup_logger(__name__)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class MissingCredentialError(RuntimeError):
|
||||
"""Neither the environment variable nor the secret file provided a value."""
|
||||
|
||||
def get_secret(env_var: str, path: str | None = None) -> str:
|
||||
"""Resolve a secret from an environment variable, falling back to a file.
|
||||
|
||||
Resolution order:
|
||||
1. The environment variable ``env_var`` (if set and non-empty).
|
||||
2. The file at ``path`` (if given and it exists).
|
||||
|
||||
Raises:
|
||||
MissingCredentialError: If neither source provides a value.
|
||||
"""
|
||||
value = os.getenv(env_var, "").strip()
|
||||
if value:
|
||||
logger.debug(f"Loaded secret from environment variable {env_var}")
|
||||
return value
|
||||
|
||||
if path:
|
||||
try:
|
||||
return return_credentials(path)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
sources = f"environment variable {env_var}" + (f" or file {path}" if path else "")
|
||||
raise MissingCredentialError(f"No credential found: set {sources}")
|
||||
|
||||
def return_credentials(path: str) -> str:
|
||||
"""Read and return credentials from a file."""
|
||||
|
||||
Reference in new issue
Block a user