Skip to content
Latchkey

python -m jinja2: Render Jinja2 Without a CLI Package

A short python -c invocation renders a Jinja2 template using only the jinja2 library, no CLI wrapper required.

When a runner has Jinja2 the library but not jinja2-cli or j2cli, a one-liner does the job and gives you full control over undefined handling and autoescape.

What it does

This calls jinja2 directly from Python: load the template file, render it with a context (typically os.environ or a parsed data file), and print. Setting undefined=StrictUndefined makes missing variables raise instead of rendering empty.

Common usage

Terminal
python -c '
import os, sys
from jinja2 import Environment, FileSystemLoader, StrictUndefined
env = Environment(loader=FileSystemLoader("."), undefined=StrictUndefined, autoescape=False)
sys.stdout.write(env.get_template(sys.argv[1]).render(**os.environ))
' config.j2 > config.rendered

Options

SettingWhat it does
undefined=StrictUndefinedRaise UndefinedError on any missing variable
autoescape=FalseDo not HTML-escape (correct for YAML/config output)
FileSystemLoader(dir)Where get_template looks for the file and includes
**os.environPass environment variables as the render context

In CI

Keep autoescape=False for config output, otherwise <, >, and & get HTML-entity-encoded and corrupt YAML/JSON. Use StrictUndefined so a missing value fails the step. This one-liner avoids adding a dependency, which keeps the image and the version surface small.

Common errors in CI

"jinja2.exceptions.UndefinedError: 'X' is undefined" with StrictUndefined and a missing key. "ModuleNotFoundError: No module named 'jinja2'" means the library is not installed (pip install jinja2). "jinja2.exceptions.TemplateNotFound" means the FileSystemLoader path does not contain the template; use the directory the template lives in.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →