2
2
import io
3
3
import logging
4
4
import os
5
+ import re
5
6
6
7
import yaml
7
8
13
14
14
15
SECRETS = "secrets"
15
16
TENTACLIO_SECRETS_FILE = "TENTACLIO__SECRETS_FILE"
17
+ ENV_VARIABLE_PATTERN = r"\${[a-zA-Z_]+[a-zA-Z0-9_]*}"
18
+ NOT_VALID_ENV_VARIABLE_VALUES = "[${}]"
16
19
17
20
18
21
class TentaclioFileError (Exception ):
@@ -33,7 +36,9 @@ class TentaclioFileError(Exception):
33
36
34
37
def __init__ (self , message : str ):
35
38
"""Intialise a new TentaclioFileError."""
36
- message = self .ERROR_TEMPLATE .format (message = message , tentaclio_file = self .TENTACLIO_FILE )
39
+ message = self .ERROR_TEMPLATE .format (
40
+ message = message , tentaclio_file = self .TENTACLIO_FILE
41
+ )
37
42
super ().__init__ (message )
38
43
39
44
@@ -85,6 +90,25 @@ def _load_from_file(
85
90
raise TentaclioFileError ("File not found" ) from e
86
91
87
92
93
+ def replace_env_variables (url : str ) -> str :
94
+ """Replace the environment variables inside the url by its value in the environment.
95
+
96
+ Environment variables match the following format: ${ENV_VARIABLE_NAME}
97
+ """
98
+ pattern = re .compile (ENV_VARIABLE_PATTERN )
99
+ env_variables = re .findall (pattern , url )
100
+ for env_variable in env_variables :
101
+ env_variable_name = re .sub (NOT_VALID_ENV_VARIABLE_VALUES , "" , env_variable )
102
+ env_value = os .getenv (env_variable_name )
103
+ if not env_value :
104
+ raise EnvironmentError (
105
+ f"Error while reading variable '{ env_variable_name } ' from the environment. "
106
+ f"Check that the variable exists in your environment."
107
+ )
108
+ url = url .replace (env_variable , env_value )
109
+ return url
110
+
111
+
88
112
def add_credentials_from_reader (
89
113
injector : injection .CredentialsInjector , yaml_reader : protocols .Reader
90
114
) -> injection .CredentialsInjector :
@@ -99,6 +123,7 @@ def add_credentials_from_reader(
99
123
creds = _load_creds_from_yaml (yaml_reader )
100
124
for name , url in creds .items ():
101
125
logger .info (f"Adding secret: { name } " )
126
+ url = replace_env_variables (url )
102
127
try :
103
128
injector .register_credentials (urls .URL (url ))
104
129
except Exception as e :
0 commit comments