Python YAML configuration with environment variables parsing
Tags: programming, python, yaml
Published: 2021-04-27 15:51:04

### Load a YAML configuration file and resolve any environment variables

![](https://cdn-images-1.medium.com/max/11700/1*4s_GrxE5sn2p2PNd8fS-6A.jpeg)
>  Note: if you want to use this, check the **UPDATE** at the end of the article :)

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](https://pyyaml.org/wiki/PyYAMLDocumentation) 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](https://medium.com/dataseries/hiding-secret-info-in-python-using-environment-variables-a2bab182eea) **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

{% gist https://gist.github.com/mkaranasou/17d57d7afe0509aa323b215beb5a7fd0 %}

Here’s a complete example:

{% gist https://gist.github.com/mkaranasou/ba83e25c835a8f7629e34dd7ede01931 %}

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

{% gist https://gist.github.com/mkaranasou/0eeeae1b65c4e50448f03fec79c826d1 %}

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

## UPDATE

Because I — and other people — have been using this a lot, I created a (very) small library, with tests and some extra features, to make it easier to use this without copy-pasting things all over :)

You can now just do:

    pip install pyaml-env

And then you can import parse_config to use it in your code.

    from pyaml_env import parse_config

    config = parse_config('path/to/yaml')

I also added support for default values (thanks [Jarosław Gilewski](https://medium.com/@jgilewski) for the idea!) and will probably add a few other — config related things that are getting transferred from one project to another.

You can find the repo here:
[**Python YAML configuration with environment variables parsing**
*A very small library that parses a yaml configuration file and it resolves the environment variables, so that no…*mariakaranasou.com](https://mariakaranasou.com/pyaml_env/)
[**mkaranasou/pyaml_env**
*A very small library that parses a yaml configuration file and it resolves the environment variables, so that no…*github.com](https://github.com/mkaranasou/pyaml_env)

## 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](https://hackersandslackers.com/simplify-your-python-projects-configuration/)
[**4 Ways to manage the configuration in Python**
*I’m not a native speaker. Sorry for my english. Please understand.*hackernoon.com](https://hackernoon.com/4-ways-to-manage-the-configuration-in-python-4623049e841b)
[**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](https://www.devdungeon.com/content/python-configuration-files)
[**Configuration files in Python**
*Most interesting programs need some kind of configuration: Content Management Systems like WordPress blogs, WikiMedia…*martin-thoma.com](https://martin-thoma.com/configuration-files-in-python/)

Originally published at [Medium](https://medium.com/swlh/python-yaml-configuration-with-environment-variables-parsing-77930f4273ac)

I could use a [coffee](https://www.buymeacoffee.com/mkaranasou) to keep me going :) 
Thanks!