Is there an easy way to merge environment variables from different sources?
paulcdejean opened this issue · comments
I'd like to use a combination of environment variables and data from a yml file when compiling a j2 file. Is there any easy way to do this?
Hm. You'll have to merge the two into something that's singular: it may be importing environment variables into your yml file, or it may be exporting yml data into the environment somehow.
Perhaps, the easiest (but somewhat akwward) way would be to have some Jinja2 placeholders inside your yml file:
# setttings.yml.template
user:
login: admin
password: {{ USER_PASS }}
Then, treating it as a template, compile it into a second yml file:
$ USER_PASS="qwerty123" j2 settings.yml.template > settings.yml
Now, having a settings.yml
file with environment variables in it, you use it as the context for rendering another template:
$ j2 your-file.j2 settings.yaml
Also, consider making a custom Jinja2 filter:
# filters.py
def env_override(default_value, key):
return os.getenv(key, default_value)
Now, you can import this filter with --filters
command-line option:
$ j2cli --filters filters.py ...
And use it like this in your templates:
{{ "default" | env_override("USER_PASS") }}
Alright, here's the best of all: I just released a new version of j2cli
for you, which supports the |env
filter in the template.
Have a look: |env
filter