kolypto / j2cli

Jinja2 Command-Line Tool, reworked

Home Page:http://pypi.python.org/pypi/j2cli

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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?

commented

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
commented

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") }}
commented

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