diff --git a/Pipfile b/Pipfile new file mode 100644 index 0000000..d203aff --- /dev/null +++ b/Pipfile @@ -0,0 +1,12 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +pyyaml = "<6.1,>=5" + +[dev-packages] + +[requires] +python_version = "3.10" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 0000000..b573265 --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,67 @@ +{ + "_meta": { + "hash": { + "sha256": "f15e333c1cb0391a3429804ce0dde290f3642680ebaa5f20622a837c07e182d6" + }, + "pipfile-spec": 6, + "requires": { + "python_version": "3.10" + }, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "pyyaml": { + "hashes": [ + "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc", + "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741", + "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206", + "sha256:18aeb1bf9a78867dc38b259769503436b7c72f7a1f1f4c93ff9a17de54319b27", + "sha256:1d4c7e777c441b20e32f52bd377e0c409713e8bb1386e1099c2415f26e479595", + "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62", + "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98", + "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696", + "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d", + "sha256:4fb147e7a67ef577a588a0e2c17b6db51dda102c71de36f8549b6816a96e1867", + "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47", + "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486", + "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6", + "sha256:596106435fa6ad000c2991a98fa58eeb8656ef2325d7e158344fb33864ed87e3", + "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007", + "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938", + "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c", + "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735", + "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d", + "sha256:9046c58c4395dff28dd494285c82ba00b546adfc7ef001486fbf0324bc174fba", + "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8", + "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5", + "sha256:afd7e57eddb1a54f0f1a974bc4391af8bcce0b444685d936840f125cf046d5bd", + "sha256:b1275ad35a5d18c62a7220633c913e1b42d44b46ee12554e5fd39c70a243d6a3", + "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0", + "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515", + "sha256:baa90d3f661d43131ca170712d903e6295d1f7a0f595074f151c0aed377c9b9c", + "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c", + "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924", + "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34", + "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43", + "sha256:c8098ddcc2a85b61647b2590f825f3db38891662cfc2fc776415143f599bb859", + "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673", + "sha256:d858aa552c999bc8a8d57426ed01e40bef403cd8ccdd0fc5f6f04a00414cac2a", + "sha256:f003ed9ad21d6a4713f0a9b5a7a0a79e08dd0f221aff4525a2be4c346ee60aab", + "sha256:f22ac1c3cac4dbc50079e965eba2c1058622631e526bd9afd45fedd49ba781fa", + "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c", + "sha256:fca0e3a251908a499833aa292323f32437106001d436eca0e6e7833256674585", + "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d", + "sha256:fd66fc5d0da6d9815ba2cebeb4205f95818ff4b79c3ebe268e75d961704af52f" + ], + "index": "pypi", + "version": "==6.0.1" + } + }, + "develop": {} +} diff --git a/README.md b/README.md index d0dc57b..2b459f7 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ # Python YAML configuration with environment variables parsing ## TL;DR -A very small library that parses a yaml configuration file and it resolves the environment variables, +A very small library that parses a yaml configuration file and it resolves the environment variables, so that no secrets are kept in text. ### Install @@ -16,7 +16,7 @@ pip install pyaml-env ``` ### How to use: ---- +--- #### Basic Usage: Environment variable parsing This yaml file: @@ -124,12 +124,12 @@ test1: ``` will raise a `ValueError` because `data1: !TEST ${ENV_TAG2}` there is no default value for `ENV_TAG2` in this line. ---- +--- #### Using a different loader: -The default yaml loader is `yaml.SafeLoader`. If you need to work with serialized Python objects, +The default yaml loader is `yaml.SafeLoader`. If you need to work with serialized Python objects, you can specify a different loader. So given a class: @@ -157,6 +157,29 @@ other_load_test = parse_config(path='path/to/config.yaml', loader=yaml.UnsafeLoa print(other_load_test) <__main__.OtherLoadTest object at 0x7fc38ccd5470> ``` + +--- + +#### Using PyamlEnvConstructor: + +Simple way to add !ENV constructor to a pyyaml loader. + +```python +from yaml import Loader +from pyaml_env import PyamlEnvConstructor + +PyamlEnvConstructor.add_to_loader_class(loader_class=Loader) +# or +PyamlEnvConstructor.add_to_loader_class( + loader_class=Loader, + tag=custom_tag, + add_implicit_resolver=True, + sep=custom_sep, + default_value=custom_default_value, + raise_if_na=True +) +``` + --- ## Long story: Load a YAML configuration file and resolve any environment variables @@ -263,7 +286,7 @@ Or even better, so that the password is not echoed in the terminal: ```python # To run this: -# export DB_PASS=very_secret_and_complex +# export DB_PASS=very_secret_and_complex # python use_env_variables_in_config_example.py -c /path/to/yaml # do stuff with conf, e.g. access the database password like this: conf['database']['DB_PASS'] diff --git a/requirements.txt b/requirements.txt index 6c1cb55..26ba73f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1 @@ -PyYAML>=5.*, <=6.* +PyYAML>=5,<6.1 diff --git a/src/pyaml_env/__init__.py b/src/pyaml_env/__init__.py index 11ba5e3..82af319 100644 --- a/src/pyaml_env/__init__.py +++ b/src/pyaml_env/__init__.py @@ -1,4 +1,5 @@ +from .constructor import PyamlEnvConstructor from .parse_config import parse_config from .base_config import BaseConfig -__all__ = ['parse_config', 'BaseConfig'] \ No newline at end of file +__all__ = ['PyamlEnvConstructor', 'parse_config', 'BaseConfig'] diff --git a/src/pyaml_env/base_config.py b/src/pyaml_env/base_config.py index a89191a..a381f47 100644 --- a/src/pyaml_env/base_config.py +++ b/src/pyaml_env/base_config.py @@ -26,4 +26,4 @@ def errors(self): return self._errors def validate(self): - raise NotImplementedError() \ No newline at end of file + raise NotImplementedError() diff --git a/src/pyaml_env/constructor.py b/src/pyaml_env/constructor.py new file mode 100644 index 0000000..c52f3e5 --- /dev/null +++ b/src/pyaml_env/constructor.py @@ -0,0 +1,86 @@ +import os +import re +import yaml + + +class PyamlEnvConstructor: + """The `env constructor` for PyYAML Loaders + + Call :meth:`add_to_loader_class` or :meth:`yaml.Loader.add_constructor` to + add it into loader. + + In YAML files, use ``!ENV`` to resolves the environment variables:: + + !ENV ${DB_USER:paws} + + or:: + + !ENV 'http://${DB_BASE_URL:straight_to_production}:${DB_PORT:12345}' + + """ + + DEFAULT_TAG_NAME = '!ENV' + DEFAULT_ADD_IMPLICIT_RESOLVER = False + DEFAULT_SEP = ':' + DEFAULT_VALUE = 'N/A' + DEFAULT_RAISE_IF_NA = False + + @classmethod + def add_to_loader_class(cls, + loader_class=None, + tag=DEFAULT_TAG_NAME, + add_implicit_resolver=DEFAULT_ADD_IMPLICIT_RESOLVER, + **kwargs): + instance = cls(**kwargs) + if add_implicit_resolver: + yaml.add_implicit_resolver(tag, instance.pattern, None, loader_class) + yaml.add_constructor(tag, instance, loader_class) + return instance + + @property + def pattern(self): + sep_pattern = r'(' + self.sep + '[^}]+)?' if self.sep else '' + return re.compile(r'.*?\$\{([^}{' + self.sep + r']+)' + sep_pattern + r'\}.*?') + + def __init__(self, sep=DEFAULT_SEP, default_value=DEFAULT_VALUE, raise_if_na=DEFAULT_RAISE_IF_NA): + self.sep = sep + self.default_value = default_value + self.raise_if_na = raise_if_na + + def __call__(self, loader, node): + """ + Extracts the environment variable from the yaml node's value + :param yaml.Loader loader: the yaml loader (as defined above) + :param node: the current node (key-value) in the yaml + :return: the parsed string that contains the value of the environment + variable or the default value if defined for the variable. If no value + for the variable can be found, then the value is replaced by + default_value='N/A' + """ + value = loader.construct_scalar(node) + match = self.pattern.findall(value) # to find all env variables in line + if match: + full_value = value + for g in match: + curr_default_value = self.default_value + env_var_name = g + env_var_name_with_default = g + if self.sep and isinstance(g, tuple) and len(g) > 1: + env_var_name = g[0] + env_var_name_with_default = ''.join(g) + found = False + for each in g: + if self.sep in each: + _, curr_default_value = each.split(self.sep, 1) + found = True + break + if not found and self.raise_if_na: + raise ValueError( + f'Could not find default value for {env_var_name}' + ) + full_value = full_value.replace( + f'${{{env_var_name_with_default}}}', + os.environ.get(env_var_name, curr_default_value) + ) + return full_value + return value diff --git a/src/pyaml_env/parse_config.py b/src/pyaml_env/parse_config.py index 59a8404..abd89fe 100644 --- a/src/pyaml_env/parse_config.py +++ b/src/pyaml_env/parse_config.py @@ -1,15 +1,15 @@ -import os -import re import yaml +from .constructor import PyamlEnvConstructor def parse_config( path=None, data=None, - tag='!ENV', - default_sep=':', - default_value='N/A', - raise_if_na=False, + tag=PyamlEnvConstructor.DEFAULT_TAG_NAME, + add_implicit_resolver=PyamlEnvConstructor.DEFAULT_ADD_IMPLICIT_RESOLVER, + default_sep=PyamlEnvConstructor.DEFAULT_SEP, + default_value=PyamlEnvConstructor.DEFAULT_VALUE, + raise_if_na=PyamlEnvConstructor.DEFAULT_RAISE_IF_NA, loader=yaml.SafeLoader, encoding='utf-8' ): @@ -29,6 +29,8 @@ def parse_config( :param str data: the yaml data itself as a stream :param str tag: the tag to look for, if None, all env variables will be resolved. + :param str add_implicit_resolver: add implicit resolver. All env variables + will be resolved. :param str default_sep: if any default values are set, use this field to separate them from the enironment variable name. E.g. ':' can be used. @@ -44,54 +46,17 @@ def parse_config( """ default_sep = default_sep or '' default_value = default_value or '' - default_sep_pattern = r'(' + default_sep + '[^}]+)?' if default_sep else '' - pattern = re.compile( - r'.*?\$\{([^}{' + default_sep + r']+)' + default_sep_pattern + r'\}.*?') loader = loader or yaml.SafeLoader + add_implicit_resolver = True if tag is None else add_implicit_resolver - # the tag will be used to mark where to start searching for the pattern - # e.g. a_key: !ENV somestring${ENV_VAR}other_stuff_follows - loader.add_implicit_resolver(tag, pattern, None) - - def constructor_env_variables(loader, node): - """ - Extracts the environment variable from the yaml node's value - :param yaml.Loader loader: the yaml loader (as defined above) - :param node: the current node (key-value) in the yaml - :return: the parsed string that contains the value of the environment - variable or the default value if defined for the variable. If no value - for the variable can be found, then the value is replaced by - default_value='N/A' - """ - value = loader.construct_scalar(node) - match = pattern.findall(value) # to find all env variables in line - if match: - full_value = value - for g in match: - curr_default_value = default_value - env_var_name = g - env_var_name_with_default = g - if default_sep and isinstance(g, tuple) and len(g) > 1: - env_var_name = g[0] - env_var_name_with_default = ''.join(g) - found = False - for each in g: - if default_sep in each: - _, curr_default_value = each.split(default_sep, 1) - found = True - break - if not found and raise_if_na: - raise ValueError( - f'Could not find default value for {env_var_name}' - ) - full_value = full_value.replace( - f'${{{env_var_name_with_default}}}', - os.environ.get(env_var_name, curr_default_value) - ) - return full_value - return value - - loader.add_constructor(tag, constructor_env_variables) + PyamlEnvConstructor.add_to_loader_class( + loader_class=loader, + tag=tag, + add_implicit_resolver=add_implicit_resolver, + sep=default_sep, + default_value=default_value, + raise_if_na=raise_if_na + ) if path: with open(path, encoding=encoding) as conf_data: diff --git a/tests/pyaml_env_tests/test_base_config.py b/tests/pyaml_env_tests/test_base_config.py index f204147..6f51d2a 100644 --- a/tests/pyaml_env_tests/test_base_config.py +++ b/tests/pyaml_env_tests/test_base_config.py @@ -1,4 +1,3 @@ -import os import unittest from pyaml_env import BaseConfig @@ -70,4 +69,4 @@ def test_base_config_complex_structure(self): self.assertIsInstance(base_config.a.b.c, list) self.assertIsInstance(base_config.a.b.d, BaseConfig) self.assertIsInstance(base_config.a.b.d.e, int) - self.assertIsInstance(base_config.a.b.d.f, str) \ No newline at end of file + self.assertIsInstance(base_config.a.b.d.f, str) diff --git a/tests/pyaml_env_tests/test_parse_config.py b/tests/pyaml_env_tests/test_parse_config.py index 1197c6f..d364001 100644 --- a/tests/pyaml_env_tests/test_parse_config.py +++ b/tests/pyaml_env_tests/test_parse_config.py @@ -709,4 +709,4 @@ def test_parse_config_no_tag_all_resolved(self): } result = parse_config(data=test_data, tag=None) - self.assertDictEqual(result, expected) \ No newline at end of file + self.assertDictEqual(result, expected)