django-yamlconf icon indicating copy to clipboard operation
django-yamlconf copied to clipboard

integrating environment variables

Open sdementen opened this issue 6 years ago • 1 comments

Can a yaml file refer to environment variables ? something like DATABASES.default.PASSWORD: "{MY_ENV_VARIABLE}"

As the syntax is used to refer to variable defined before in the yaml, it may be better to have something like DATABASES.default.PASSWORD: env.MY_ENV_VARIABLE ie with env available as os.environ

Or to be able to use it with https://github.com/joke2k/django-environ, have something like DATABASES.default.PASSWORD: "{env('MY_ENV_VARIABLE', default='foo')} (ie a django-environ env expression) However, as there is already a logic for defining default value (through the hierarchy of yaml files), I would prefer the simpler form DATABASES.default.PASSWORD: env.MY_ENV_VARIABLE where, if MY_ENV_VARIABLE is not defined (KeyError), the value is not assigned (and so it can keep its default value defined before if any)

sdementen avatar Sep 03 '19 04:09 sdementen

Environment variables beginning with YAMLCONF_ are pulled in automatically. To do what you want, the structure I would recommend is, in your settings.py file:

USER = os.environ.get('USER', 'goldrush')
DBUSER = USER
DBPASS = 'welcome'
DBNAME = USER
DBAPPNAME = 'metatdatamgr'

django_yamlconf.load()

DATABASES = {
    'default': {
        'ENGINE': 'django_prometheus.db.backends.postgresql',
        'NAME': DBNAME,
        'USER': DBUSER,
        'PASSWORD': DBPASS,
        'HOST': DBHOST,
        'PORT': DBPORT,
        'OPTIONS': {
            'application_name': DBAPPNAME
        },
    },
}

There are some additional config's in this which you can ignore, e.g., the prometheus stuff.

To use an environment defined password, simply set YAMLCONF_DBPASS, e.g.,

export YAMLCONF_DBPASS="some secure password"

The indirect setting here of DATABASES after the yamlconf load is to avoid displaying the DATABASES dict via the "/yamlconf/" view (not sure if you have enabled that).

Does this sound like a reasonable path? I accept that, eventually, I will likely need to extend this to allow callout's to general functions via value but haven't considered what the syntax would look like.

mkrohan avatar Sep 03 '19 18:09 mkrohan