1
+ import os
2
+ import logging
3
+ import toml
4
+ from azure .identity import DefaultAzureCredential
5
+ from azure .keyvault .secrets import SecretClient
6
+ from dotenv import load_dotenv
7
+ from setup_logging import setup_logging
8
+
9
+
10
+ def fetch_kv_secret ():
11
+ """
12
+ Fetches secrets from an Azure Key Vault and sets them as environment variables.
13
+
14
+ This function reads the Key Vault name and secret names from a `config.toml` file,
15
+ retrieves the secrets from the Key Vault using Azure SDK, and stores them in the
16
+ environment variables for further use.
17
+
18
+ Raises:
19
+ KeyError: If the `config.toml` file does not contain the required keys.
20
+ azure.core.exceptions.HttpResponseError: If there is an issue with the Azure Key Vault request.
21
+ """
22
+ # Initialize a logger for logging information and errors
23
+ logger = logging .getLogger (__name__ )
24
+
25
+ # Authenticate using the default Azure credential chain
26
+ credential = DefaultAzureCredential ()
27
+
28
+ # Load configuration from the `config.toml` file
29
+ config = toml .load ("config.toml" )
30
+
31
+ # Retrieve the Key Vault name from the configuration
32
+ keyvault = keyvault_name = config ["keyvault" ]["name" ]
33
+
34
+ # Construct the Key Vault URL
35
+ vault_url = f"https://{ keyvault_name } .vault.azure.net/"
36
+
37
+ # Retrieve the secret names from the configuration
38
+ secret_names = config ["secrets" ]
39
+
40
+ # Create a SecretClient to interact with the Azure Key Vault
41
+ client = SecretClient (vault_url = vault_url , credential = credential )
42
+
43
+ # Dictionary to store the retrieved secrets
44
+ secrets = {}
45
+
46
+ # Iterate over the secret names and fetch their values from the Key Vault
47
+ for key , secret in secret_names .items ():
48
+ secret_name = secret
49
+ # Retrieve the secret value from the Key Vault
50
+ get_secret = client .get_secret (secret_name )
51
+ # Store the secret value in the dictionary
52
+ secrets [key ] = get_secret .value
53
+ # Set the secret value as an environment variable
54
+ os .environ [key ] = get_secret .value
55
+
56
+
57
+ def main ():
58
+ """
59
+ Main function to fetch a secret from Azure Key Vault.
60
+ """
61
+ load_dotenv ()
62
+ setup_logging ()
63
+ logger = logging .getLogger (__name__ )
64
+ logger .info ("Starting to fetch secrets from Azure Key Vault" )
65
+ fetch_kv_secret ()
66
+ logger .info ("Finished fetching secrets from Azure Key Vault" )
67
+
68
+ if __name__ == "__main__" :
69
+ main ()
0 commit comments