Skip to content

Commit bd5b063

Browse files
committed
Add environmental variables interpolation support
1 parent f45aa65 commit bd5b063

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

src/tentaclio/credentials/reader.py

+26-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import io
33
import logging
44
import os
5+
import re
56

67
import yaml
78

@@ -13,6 +14,8 @@
1314

1415
SECRETS = "secrets"
1516
TENTACLIO_SECRETS_FILE = "TENTACLIO__SECRETS_FILE"
17+
ENV_VARIABLE_PATTERN = r"\${[a-zA-Z_]+[a-zA-Z0-9_]*}"
18+
NOT_VALID_ENV_VARIABLE_VALUES = "[${}]"
1619

1720

1821
class TentaclioFileError(Exception):
@@ -33,7 +36,9 @@ class TentaclioFileError(Exception):
3336

3437
def __init__(self, message: str):
3538
"""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+
)
3742
super().__init__(message)
3843

3944

@@ -85,6 +90,25 @@ def _load_from_file(
8590
raise TentaclioFileError("File not found") from e
8691

8792

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+
88112
def add_credentials_from_reader(
89113
injector: injection.CredentialsInjector, yaml_reader: protocols.Reader
90114
) -> injection.CredentialsInjector:
@@ -99,6 +123,7 @@ def add_credentials_from_reader(
99123
creds = _load_creds_from_yaml(yaml_reader)
100124
for name, url in creds.items():
101125
logger.info(f"Adding secret: {name}")
126+
url = replace_env_variables(url)
102127
try:
103128
injector.register_credentials(urls.URL(url))
104129
except Exception as e:

0 commit comments

Comments
 (0)