Coder Social home page Coder Social logo

pyaml_env's Introduction

Downloads Downloads Tests and linting CodeQL License: MIT Upload Python Package

Buy Me A Coffee

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, so that no secrets are kept in text.

Install

pip install pyaml-env

How to use:


Basic Usage: Environment variable parsing

This yaml file:

database:
  name: test_db
  username: !ENV ${DB_USER}
  password: !ENV ${DB_PASS}
  url: !ENV 'http://${DB_BASE_URL}:${DB_PORT}'

given that we've set these:

export $DB_USER=super_secret_user
export $DB_PASS=extra_super_secret_password
export $DB_BASE_URL=localhost
export $DB_PORT=5432

becomes this:

from pyaml_env import parse_config
config = parse_config('path/to/config.yaml')

print(config)
# outputs the following, with the environment variables resolved
{
    'database': {
        'name': 'test_db',
        'username': 'super_secret_user',
        'password': 'extra_super_secret_password',
        'url': 'http://localhost:5432',
    }
}

Attribute Access using BaseConfig

Which can also become this:

from pyaml_env import parse_config, BaseConfig
config = BaseConfig(parse_config('path/to/config.yaml'))
# you can then access the config properties as atrributes
# I'll explain why this might be useful in a bit.
print(config.database.url)

Default Values with :

You can also set default values for when the environment variables are not set for some reason, using the default_sep kwarg (which is : by default) like this:

databse:
  name: test_db
  username: !ENV ${DB_USER:paws}
  password: !ENV ${DB_PASS:meaw2}
  url: !ENV 'http://${DB_BASE_URL:straight_to_production}:${DB_PORT}'

And if no environment variables are found then we get:

from pyaml_env import parse_config
config = parse_config('path/to/config.yaml')

print(config)
{
    'database': {
        'name': 'test_db',
        'username': 'paws',
        'password': 'meaw2',
        'url': 'http://straight_to_production:N/A',
    }
}

NOTE 0: Special characters like *, { etc. are not currently supported as separators. Let me know if you'd like them handled also.

NOTE 1: If you set tag to None, then, the current behavior is that environment variables in all places in the yaml will be resolved (if set).


Datatype parsing with yaml's tag:yaml.org,2002:

# because this is not allowed:
# data1: !TAG !!float ${ENV_TAG2:27017}
# use tag:yaml.org,2002:datatype to convert value:
test_data = '''
        data0: !TAG ${ENV_TAG1}
        data1: !TAG tag:yaml.org,2002:float ${ENV_TAG2:27017}
        data2: !!float 1024
        data3: !TAG ${ENV_TAG2:some_value}
        data4: !TAG tag:yaml.org,2002:bool ${ENV_TAG2:false}
        '''

Will become:

os.environ['ENV_TAG1'] = "1024"
config = parse_config(data=test_data, tag='!TAG')
print(config)
{
    'data0': '1024', 
    'data1': 27017.0, 
    'data2': 1024.0, 
    'data3': 'some_value', 
    'data4': False
}

reference in yaml code


If nothing matches: N/A as default_value:

If no defaults are found and no environment variables, the default_value (which is N/A by default) is used:

{
    'database': {
        'name': 'test_db',
        'username': 'N/A',
        'password': 'N/A',
        'url': 'http://N/A:N/A',
    }
}

Which, of course, means something went wrong and we need to set the correct environment variables. If you want this process to fail if a default value is not found, you can set the raise_if_na flag to True. For example:

test1:
    data0: !TEST ${ENV_TAG1:has_default}/somethingelse/${ENV_TAG2:also_has_default}
    data1:  !TEST ${ENV_TAG2}

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, you can specify a different loader.

So given a class:

class OtherLoadTest:
    def __init__(self):
        self.data0 = 'it works!'
        self.data1 = 'this works too!'

Which has become a yaml output like the following using yaml.dump(OtherLoadTest()):

!!python/object:__main__.OtherLoadTest
data0: it works!
data1: this works too!

You can use parse_config to load the object like this:

import yaml
from pyaml_env import parse_config

other_load_test = parse_config(path='path/to/config.yaml', loader=yaml.UnsafeLoader)
print(other_load_test)
<__main__.OtherLoadTest object at 0x7fc38ccd5470>

Long story: Load a YAML configuration file and resolve any environment variables

If you’ve worked with Python projects, you’ve probably have stumbled across the many ways to provide configuration. I am not going to go through all the ways here, but a few of them are:

  • using .ini files

  • using a python class

  • using .env files

  • using JSON or XML files

  • using a yaml file

And so on. I’ve put some useful links about the different ways below, in case you are interested in digging deeper.

My preference is working with yaml configuration because I usually find very handy and easy to use and I really like that yaml files are also used in e.g. docker-compose configuration so it is something most are familiar with.

For yaml parsing I use the PyYAML Python library.

In this article we’ll talk about the yaml file case and more specifically what you can do to avoid keeping your secrets, e.g. passwords, hosts, usernames etc, directly on it.

Let’s say we have a very simple example of a yaml file configuration:

database:
 name: database_name
 user: me
 password: very_secret_and_complex
 host: localhost
 port: 5432

ws:
 user: username
 password: very_secret_and_complex_too
 host: localhost

When you come to a point where you need to deploy your project, it is not really safe to have passwords and sensitive data in a plain text configuration file lying around on your production server. That’s where **environment variables **come in handy. So the goal here is to be able to easily replace the very_secret_and_complex password with input from an environment variable, e.g. DB_PASS, so that this variable only exists when you set it and run your program instead of it being hardcoded somewhere.

For PyYAML to be able to resolve environment variables, we need three main things:

  • A regex pattern for the environment variable identification e.g. pattern = re.compile(‘.?${(\w+)}.?’)

  • A tag that will signify that there’s an environment variable (or more) to be parsed, e.g. !ENV.

  • And a function that the loader will use to resolve the environment variables

def constructor_env_variables(loader, node):
    """
    Extracts the environment variable from the node's value
    :param yaml.Loader loader: the yaml loader
    :param node: the current node in the yaml
    :return: the parsed string that contains the value of the environment
    variable
    """
    value = loader.construct_scalar(node)
    match = pattern.findall(value)
    if match:
        full_value = value
        for g in match:
            full_value = full_value.replace(
                f'${{{g}}}', os.environ.get(g, g)
            )
        return full_value
    return value

Example of a YAML configuration with environment variables:

database:
 name: database_name
 user: !ENV ${DB_USER}
 password: !ENV ${DB_PASS}
 host: !ENV ${DB_HOST}
 port: 5432

ws:
 user: !ENV ${WS_USER}
 password: !ENV ${WS_PASS}
 host: !ENV ‘[https://${CURR_ENV}.ws.com.local'](https://${CURR_ENV}.ws.com.local')

This can also work with more than one environment variables declared in the same line for the same configuration parameter like this:

ws:
 user: !ENV ${WS_USER}
 password: !ENV ${WS_PASS}
 host: !ENV '[https://${CURR_ENV}.ws.com.](https://${CURR_ENV}.ws.com.local')[${MODE}](https://${CURR_ENV}.ws.com.local')'  # multiple env var

And how to use this:

First set the environment variables. For example, for the DB_PASS :

export DB_PASS=very_secret_and_complex

Or even better, so that the password is not echoed in the terminal:

read -s ‘Database password: ‘ db_pass
export DB_PASS=$db_pass
# To run this:
# 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']

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='My awesome script')
    parser.add_argument(
        "-c", "--conf", action="store", dest="conf_file",
        help="Path to config file"
    )
    args = parser.parse_args()
    conf = parse_config(path=args.conf_file)

Then you can run the above script:

python use_env_variables_in_config_example.py -c /path/to/yaml

And in your code, do stuff with conf, e.g. access the database password like this: conf['database']['DB_PASS']

I hope this was helpful. Any thoughts, questions, corrections and suggestions are very welcome :)

Useful links

The Many Faces and Files of Python Configs *As we cling harder and harder to Dockerfiles, Kubernetes, or any modern preconfigured app environment, our dependency…*hackersandslackers.com 4 Ways to manage the configuration in Python *I’m not a native speaker. Sorry for my english. Please understand.*hackernoon.com Python configuration files *A common need when writing an application is loading and saving configuration values in a human-readable text format…*www.devdungeon.com Configuration files in Python *Most interesting programs need some kind of configuration: Content Management Systems like WordPress blogs, WikiMedia…*martin-thoma.com

pyaml_env's People

Contributors

cburing avatar juur avatar ling32945 avatar lukasgemela avatar mkaranasou avatar rkrell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

pyaml_env's Issues

[BUG] gettattr / hasattr broken on BaseConfig since 1.2.1

Describe the bug
The has been introduced a change in commit 6aab658 (version 1.2.1) which makes it impossible to test for an not existing attribute on a BaseConfig object instance and use a default using

getattr(base, key, default)
hasattr(base, key)

If the attribute key doesn't exist, there is always thrown a KeyError due to the override of the __getattr__ function on BaseConfig. This is highly impractical and a bigger breaking change in this minor version step.

To Reproduce
Steps to reproduce the behavior:

YAML example:

jobs:
  a:
    foo: "bar"
    is_optional: true
  b:
    foo: "bar"

Results:

  File "/home/user/work/scripts/job.py", line ??, in __init__
    conf.is_optional if hasattr(conf, 'is_optional') else None
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/user/work/lib/python3.11/site-packages/pyaml_env/base_config.py", line 28, in __getattr__
    return self.__dict__[field_name]
           ~~~~~~~~~~~~~^^^^^^^^^^^^
KeyError: 'is_optional'

Expected behavior
getattr and hasattr should work on BaseConfig without limitations.

Additional context

  • Python version 3.11
  • OS Debian 12

[FEATURE] Publish PEP 561 types

Is your feature request related to a problem? Please describe.
It would be really nice if pyaml_env could publish PEP 561 type information allowing users of pyaml_env to use mypy to type check their code.

Thank you!

Describe the solution you'd like
Either include type information in this library so type checkers (like mypi) can use it, or publish a stub library with that information.

Describe alternatives you've considered
I'm currently ignoring pyaml_env entirely for type checking purposes as described in the documentation at https://mypy.readthedocs.io/en/stable/common_issues.html#spurious-errors-and-locally-silencing-the-checker

import pyaml_env  # type: ignore

using !ENV always gives a string

Having yml with ENV tag and default values:

...
mongodb:
  host: !ENV ${MONGO_HOST:192.168.2.8}
  port: !ENV ${MONGO_PORT:27017}  
  serverSelectionTimeoutMS: 1000
...

and loading it with:

from pyaml_env import parse_config
appSettings = parse_config('./app/settings/app.yml')

gives me:

  • a string for host and port (no matter if the ENV variable exists or not)
  • a number for serverSelectionTimeoutMS

I would expect that "port" is interpreted as a number too (cause the default value is a number). Otherwise I have to convert every time I use it.
Is there a way to accomplish that?

Using defaults for unresolved environment variables result in not resolving the whole value

Another point here in 1.0.1:

Given the following YAML:

xxx: !ENV ${DATABASE_HOST:def}

The resulting dictionary from parse_config is always

{'xxx': '${DATABASE_HOST:def}'}

regardless whether the environment variable $DATABASE_HOST is set or not.
This is caused by the default value.

If changing the YAML to:

xxx: !ENV ${DATABASE_HOST}

and setting $DATABASE_HOST to abc resolving works:

{'xxx': 'abc'}

Bump PyYAML dependency to major version 6

Hi @mkaranasou ,

thanks for your great project which I am using nearly daily 🙂

Lately I was running into an issue with the latest pyyaml major version 6, as pyaml-env won't let me update because it depends on 5.*

I was wondering, is there anything stopping you from updating to the latest version?

Cheers!

[FEATURE] - Allow different yaml Loader

Is your feature request related to a problem? Please describe.
Current version uses SafeLoader of PyYaml, but this loader does not allow python object serialization or other custom requirements.

Describe the solution you'd like
That parse_config method receive a loader. By default it could be SafeLoader but in that way other people could add more features over that Loader

Additional context
The call could be replaced by this:

parse_config(path="my_file.yml", loader=yaml.UnsafeLoader)

[BUG] Versions conflict due to wrong version constraint in requirements.txt

Describe the bug
Version conflict due to wrong version constraint in requirements.txt.
Looking at PEP440, >=5.*, <=6.* doesn't look right. It should be >=5.0, <7.0.

To Reproduce
Steps to reproduce the behavior:

  1. Create your own package your-package that depends on PyYAML 6.0 and pyaml-env 1.2.0

  2. Upload the package (I'm using an internal PyPI server)

  3. pip download your-package

  4. Error:

    ERROR: Cannot install your-package and your-package==1.0.0 because these package versions have conflicting dependencies.
    
    The conflict is caused by:
        your-package 1.0.0 depends on PyYAML<7.0 and >=6.0
        your-package pyaml-env 1.2.0 depends on PyYAML<=6.* and >=5.*
        your-package 2.0.0.dev540 depends on PyYAML<7.0 and >=6.0
        pyaml-env 1.1.5 depends on PyYAML<=6.* and >=5.*

Expected behavior
It shouldn't happen

Additional context
Add any other context about the problem here.

  • Python version: 3.7+
  • OS: macOS 12.6.1

BaseConfig does not work recursively in Dict

Hi, great small library.

In version 1.0.0., I found one issue: BaseConfig does not work as documented for me. It does not recurse deeper into parsed dictionaries.

Example:

config.yaml:

db:
  connection: mysql+pymysql://user1:pass1@localhost/db_name?charset=utf8
cfg = BaseConfig(parse_config('config.yaml))

returns an object of type BaseConfig with an attribute db of type dictionary, thus

cfg.db.connection

is not accessible in that way, the only way to get the connection is:

cfg.db['connection']

[BUG] add_implicit_resolver() - use of "first" argument required?!

Describe the bug
parse_config() uses this code to decide which YAML entries to actually look at: loader.add_implicit_resolver(tag, pattern, None) The third parameter, first, is intentionally set to None. However, if one takes a look at the YAML documentation, this exact argument controls whether a YAML entry should be looked at.

And indeed, it does not matter which value is passed as tag, as it will only be used to tag the entries and process them. But all entries will be processed, prefixed with the tag or not. As soon as first is also set to the value of tag, things start to work as expected: loader.add_implicit_resolver(tag, pattern, tag)

To Reproduce
Steps to reproduce the behavior:

  1. Add a prefixed and a non-prefixed environment variable substitution attempt to a YAML file, e. g.:
test:
  with-prefix: !ENV ${DPT_EXISTING_ENV}
  without-prefix: ${DPT_EXISTING_ENV}
  1. Try to use parse_config() on this YAML file, with tag set to different values as well as None.
  2. Each time both entries will be acted upon, as there is no first set and the pattern matches.

Expected behavior
Only the entries prefixed with the tag should be acted upon.

Additional context
Add any other context about the problem here.

  • Python version: 3.6 (sadly)
  • OS: Debian Buster
  • pyaml_env: 1.1.5

[FEATURE] Add the option to restore original values for saving a modified configuration.

I need to save a modified configuration back to the configuration file. Saving values instead of variables defeats the purpose of putting variables there in the first place. :/

I'd like to have a way to restore the original values before writing changes back to the configuration file.

I considered 'pre-loading' the file and looking for the various formats this can appear in, but that got hairy quickly. I then re-did your library in a relatively simplistic way in hopes of just grabbing the key and saving it and its value in another dict, but I can't figure out how to grab the key for the current value.

A stripped down example looks like this.

original_values = {}

def regex_resolver():
  # regex built here, pretty much untouched from your code

def substitute_variable_values(value: str):
  # again, match and replace ripped from your code

def load_yaml(filename):
  def resolve_env_vars(loader, node):
    value = loader.construct_scalar(node)
    return substitute_variable_values(value)

  def store_values(loader, node):
    # this is where things bogged down
    # I've gotten to this point, but I have no clue how to proceed
    value = loader.construct_mappings(node)
    # somehow, grab the key, but by this point, it's buried in the
    # object and I can see it, but I can't see how to pull it out via
    # code
    original_values[key] = value

    loader = yaml.SafeLoader
    loader.add_implicit_resolver(tag, regex_resolver(), None)
    loader.add_constructor(tag, resolve_env_vars)
    loader.add_constructor(tag, store_values)

    with open(yamlfile, 'r', encoding='utf-8') as raw:
      cfg = yaml.load(raw, Loader=loader)

    return cfg

# Writing the config would be easy.
def write_config(filename, data):
  if original_values.keys():
    data | original_values

  with open(filename, 'w', encoding='utf-8') as raw:
    yaml.dump(data, fh)

Though, it would be nice to include that in the library so the dev wouldn't have to remember to do that final step.

Broken regex for default value

Hi,
the regex pattern is broken. One needs to exclude the default_sep character from first matching group, otherwise the environment variable is not set. It should read:

pattern = re.compile(r'.*?\$\{([^}{' + default_sep + r']+)' + default_sep_pattern + r'\}.*?')

If one changes the default value of the separator from None to "", one could do:

    default_sep_pattern = r'(' + default_sep + '[^}^{]+)?'\
        if default_sep != "" else ''
    pattern = re.compile(r'.*?\$\{([^}{' + default_sep + r']+)' + default_sep_pattern + r'\}.*?')

A test like this will fail with current version:


    def test_parse_config_default_separator_strong_password_overwritten_by_env_var(self):
        os.environ["ENV_TAG1"] = "myWeakPassword"

        test_data = '''
        test1:
            data0: !TEST ${ENV_TAG1:NoHtnnmEuluGp2boPvGQkGrXqTAtBvIVz9VRmV65}/somethingelse/${ENV_TAG2}
            data1:  !TEST ${ENV_TAG2:0.0.0.0}
        '''
        config = parse_config(data=test_data, tag='!TEST', default_sep=':')

        expected_config = {
            'test1': {
                'data0': 'myWeakPassword/somethingelse/N/A',
                'data1': '0.0.0.0'
            }
        }

        self.assertDictEqual(
            config,
            expected_config
        )

Thanks a lot

[BUG] SyntaxWarning due to invalid escape sequence

Describe the bug
After upgrading to python 3.12 pylint started complaining about invalid escape sequence '\w' which I traced to pyaml_env and more precisely to line 58 in parse_config:

 type_tag_pattern = re.compile(f'({type_tag}\w+\s)')

To Reproduce Steps to reproduce the behavior:

  1. Create a test_read.py file with the following content:
"""Test for pyaml_env parse_config call"""
from pyaml_env import parse_config

def read_config():
    """Reads config from the app.yaml file"""
    return parse_config('app.yaml')
  1. Run pylint on this file
(.venv) bernt@work:~/python/projectx$ pylint test_read.py
  1. Results:
<unknown>:58: SyntaxWarning: invalid escape sequence '\w'

Expected behavior pylint shouldn't complain about a valid pattern.

The complaints can be removed by specifying a raw pattern to compile:

 type_tag_pattern = re.compile(fr'({type_tag}\w+\s)')

Additional context

  • Python version 3.12.0
  • OS Fedora 39

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.