Files
grid_application/app/config.py
Tobias Quadfasel 02f1b41cb9 feat(azure): Added necessary azure components to app
Using respective credentials for both local development as well as
deployment. When deployed on azure, the app authenticates with the SQL
database via Entra ID (formerly active directory) and accesses other
credentials via key vault as a system managed identity.
2024-09-03 21:51:12 +02:00

79 lines
2.8 KiB
Python

"""Global configuration for data preprocessing."""
import os
from azure.identity import (
AzureCliCredential,
ChainedTokenCredential,
ManagedIdentityCredential,
)
from azure.keyvault.secrets import SecretClient
def check_credentials() -> None:
"""Check and set up necessary credentials for the application.
This function verifies the presence of required environment variables.
If they are not set, it attempts to retrieve them using Azure-managed identity.
The function checks for the following environment variables:
- OPENAI_API_KEY
- AZURE_SQL_CONNECTION_STRING
- APP_UNAME
- APP_PW
If AZURE_SQL_CONNECTION_STRING is not set, it constructs the connection string
using other environment variables (AZURE_SQL_SERVER, AZURE_SQL_PORT,
AZURE_SQL_DATABASE, AZURE_SQL_AUTHENTICATION).
If any of the required credentials are missing, the function uses Azure Key Vault
to retrieve the secrets.
Raises
------
Exception
If the required environment variables are not set and cannot be retrieved
from Azure Key Vault.
Notes
-----
This function modifies the following environment variables:
- AZURE_SQL_CONNECTION_STRING (if not already set)
- OPENAI_API_KEY (if not already set)
- APP_UNAME (if not already set)
- APP_PW (if not already set)
The function uses Azure Managed Identity and Azure CLI credentials to access
the Key Vault.
"""
try:
assert os.getenv("OPENAI_API_KEY") is not None
assert os.getenv("AZURE_SQL_CONNECTION_STRING") is not None
assert os.getenv("APP_UNAME") is not None
assert os.getenv("APP_PW") is not None
except Exception:
# Environment variables not set, use azure-managed identity
if os.getenv("AZURE_SQL_CONNECTION_STRING") is None:
server = os.getenv("AZURE_SQL_SERVER")
port = os.getenv("AZURE_SQL_PORT")
database = os.getenv("AZURE_SQL_DATABASE")
authentication = os.getenv("AZURE_SQL_AUTHENTICATION")
os.environ["AZURE_SQL_CONNECTION_STRING"] = (
f"Driver={{ODBC Driver 18 for SQL Server}};"
f"Server={server},{port};Database={database};"
f"Authentication={authentication};Encrypt=yes;"
)
managed_identity = ManagedIdentityCredential()
azure_cli = AzureCliCredential()
credential_chain = ChainedTokenCredential(managed_identity, azure_cli)
keyVaultName = os.environ["KEY_VAULT_NAME"]
KVUri = f"https://{keyVaultName}.vault.azure.net"
client = SecretClient(vault_url=KVUri, credential=credential_chain)
os.environ["OPENAI_API_KEY"] = client.get_secret("openai-api-key").value
os.environ["APP_UNAME"] = client.get_secret("app-uname").value
os.environ["APP_PW"] = client.get_secret("app-pw").value