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:
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:
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.
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:
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: