Search code examples
pythonjinja2

How to read in an environment variable for Jinja2 so that it can be interpolated in an if condition?


I try to wrap-around my head on how to skip certain parts of code based on an environment variable when using a Jinja2 template to generate a file with a YAML document. I did some research online, asked ChatGPT, but I did not find any answer that helped me.

So I made this minimal example:

import os
from jinja2 import Template


os.environ['SKIP']="False"
print(
    Template(
        "{% if env['SKIP'] %}\n"
        '{{ "do not skip" }}\n'
        "{% else %}\n"
        '{{ "skip" }}\n'
        "{% endif %}"
    ).render(env=os.environ)
)

outputs do not skip (as expected).

Executing the following:

import os
os.environ['SKIP']="True"

print(
    Template(
        "{% if env['SKIP'] %}\n"
        '{{ "do not skip" }}\n'
        "{% else %}\n"
        '{{ "skip" }}\n'
        "{% endif %}"
    ).render(env=os.environ)
)

also returns do not skip, but I expected skip. So I assume it is not reading the environment variable correctly.

How can I use environment variables in Jinja2 correctly? And how to fix this minimal example?


Solution

  • A few issues here - I think your logic is backwards for skipping, you properly intended this:

    print(
        Template(
            "{% if env['SKIP'] %}\n"
            '{{ "skip" }}\n'
            "{% else %}\n"
            '{{ "do not skip" }}\n'
            "{% endif %}"
        ).render(env=os.environ)
    )
    

    Secondly, to my knowledge, in python all strings except the empty string will evaluate to a truthy value. So, for instance,

    if "False":
        print('hi')
    

    Will output "hi".

    Since it seems environment variables in this context can only be string values, you should check for equality with the string "True" to reach the desired behavior:

    import os
    
    os.environ['SKIP']="False"
    
    print(
        Template(
            "{% if env['SKIP'] == 'True' %}\n"
            '{{ "skip" }}\n'
            "{% else %}\n"
            '{{ "do not skip" }}\n'
            "{% endif %}"
        ).render(env=os.environ)
    )