Skip to content
Latchkey

jinja2-cli: Render Jinja2 Templates With Data

jinja2-cli renders a Jinja2 template file against structured data, picking the parser from the data file extension or a --format flag.

jinja2-cli (the jinja2 command from the jinja2-cli package) is the quickest way to run Jinja2 outside Python code. It is the same engine Ansible uses, so behavior matches.

What it does

jinja2-cli loads a template and a data file, renders the template with Jinja2, and prints the result to stdout. It infers the data format (yaml, json, ini, env) from the file extension unless you override it with --format.

Common usage

Terminal
jinja2 template.j2 data.yaml > out.yaml
# force the parser and fail on any undefined variable
jinja2 --format=yaml --strict template.j2 data.yaml > out.yaml
# data from stdin as env vars
env | jinja2 --format=env template.j2 -

Options

FlagWhat it does
--format <fmt>Parser for the data: yaml, json, ini, env, querystring
--strictRaise on undefined variables instead of rendering empty
-D key=valueDefine/override a single variable on the command line
-e, --extensionEnable a Jinja2 extension (e.g. jinja2.ext.do)
-o, --outfile <path>Write to a file instead of stdout

In CI

Add --strict so an unset variable fails the render instead of silently producing an empty field that breaks the manifest later. YAML data support needs PyYAML installed (pip install jinja2-cli[yaml]); a bare install cannot parse .yaml.

Common errors in CI

"jinja2.exceptions.TemplateNotFound: template.j2" means the template path is wrong or resolved relative to the wrong directory; pass an absolute path. "jinja2.exceptions.UndefinedError: 'foo' is undefined" appears under --strict when the data file is missing a key the template uses. "ERROR: format yaml is not supported, install PyYAML" means the yaml extra was not installed.

Related guides

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