Accessing OS environment variables from Jinja2 template

前端 未结 3 662
予麋鹿
予麋鹿 2021-02-02 13:37

Is it possible to access a OS environment variable directly from a Jinja2 template?

相关标签:
3条回答
  • 2021-02-02 14:10

    I believe you can access environment variables like so:

    {{ env['XMPP_DOMAIN'] or "localhost" }}
    

    This is from an example in a config file that I saw recently for a Docker deployment of ejabberd.

    hosts:
      - "{{ env['XMPP_DOMAIN'] or "localhost" }}"
    

    NOTE: You can see the rest of the example in the run file from the Github repo.

    As I understand things the heavy lifting is done by this bit of code:

    readonly PYTHON_JINJA2="import os;
    import sys;
    import jinja2;
    sys.stdout.write(
        jinja2.Template
            (sys.stdin.read()
        ).render(env=os.environ))
    """
    

    And this code is what is used to generate a template file:

    cat ${CONFIGTEMPLATE} \
          | python -c "${PYTHON_JINJA2}" \
          > ${CONFIGFILE}
    

    References

    • rroemhild/docker-ejabberd docker image via github
    0 讨论(0)
  • 2021-02-02 14:24

    Following @Renier's pointer about custom filters in the comments, I figured out a possible solution.

    Define a custom filter:

    def env_override(value, key):
      return os.getenv(key, value)
    

    Install the filter in the environment:

    env.filters['env_override'] = env_override
    

    Use the filter as follows:

    "test" : {{ "default" | env_override('CUSTOM') }}
    

    Where the appropriate environment variable can be set as:

    export CUSTOM=some_value
    

    If the environment variable is set the output will be:

    "test" : some_value
    

    Otherwise:

    "test" : default
    
    0 讨论(0)
  • 2021-02-02 14:26

    The answer in https://stackoverflow.com/a/27984610/1070890 works beautifully but you can still get rid of the useless use of cat and compress it to a single statement:

    python -c 'import os
    import sys
    import jinja2
    sys.stdout.write(
        jinja2.Template(sys.stdin.read()
    ).render(env=os.environ))' <$CONFIGTEMPLATE >$CONFIGFILE
    

    P.S.: Stack Overflow does not allow formatted code in comments. Therefore I had to post this as a separate answer instead of commenting on https://stackoverflow.com/a/27984610/1070890.

    0 讨论(0)
提交回复
热议问题