Skip to content

Instantly share code, notes, and snippets.

@hanula
Created January 18, 2018 07:26
Show Gist options
  • Save hanula/46577d67a2798acca5535ff878538a95 to your computer and use it in GitHub Desktop.
Save hanula/46577d67a2798acca5535ff878538a95 to your computer and use it in GitHub Desktop.
"""
Expands `${MY_VAR}` variables in a given dictionary from `os.environ` and
local INI-like file.
"""
import os
def load_secrets(filename):
"""
Load secrets file in INI-like format and return dictionary of the items.
"""
secrets = {}
with open(filename) as f:
for line in f.readlines():
line = line.strip()
if line.startswith('#'):
continue
if '=' in line:
key, value = line.split('=')
secrets[key.strip()] = value.strip()
return secrets
def load_secret_settings(settings, secrets_file):
"""
For given `settings` dict and secret file it loads the secrets,
puts them into `os.environ` and expands `settings` values from the environ.
Usage of the settings values to be expanded:
SOME_KEY = ${MY_ENV_VAR}
"""
if os.path.isfile(secrets_file):
for key, value in load_secrets(secrets_file).items():
os.environ[key] = value
return dict((key, os.path.expandvars(value)) for
key, value in settings.items())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment