Skip to content
Latchkey

j2cli: Render Jinja2 With Env and Data Files

j2cli provides the j2 command, which renders a Jinja2 template using data from the environment or a data file.

j2cli is a popular alternative to jinja2-cli, especially loved for defaulting to environment variables, which fits Docker and CI naturally.

What it does

j2 renders a Jinja2 template. With no data file it uses the current environment; with a data file it parses json, yaml, ini, or env format (auto-detected by extension or forced by the first positional format hint). Output goes to stdout unless -o is given.

Common usage

Terminal
# render using environment variables
j2 config.j2 > config.rendered
# render from a YAML data file
j2 config.j2 data.yaml > config.rendered
# force env format and fail on undefined
j2 --undefined=strict -f env config.j2

Options

FlagWhat it does
-f, --format <fmt>Data format: env, ini, json, yaml, auto (default auto)
--undefinedstrict raises on undefined; default renders empty
-o <path>Write output to a file
-e, --import-env <var>Import environment into a named variable in the template
--customize <py>Python file to customize the Jinja2 environment

In CI

j2 defaulting to the environment is convenient but means a typo'd variable renders empty; pass --undefined=strict in pipelines. YAML support again needs PyYAML installed. Render to a file and diff before applying so an empty field does not silently ship.

Common errors in CI

"jinja2.exceptions.UndefinedError: 'X' is undefined" under --undefined=strict, or a silently empty value without it. "yaml format requires PyYAML" if the extra is missing. "TypeError: expected str, bytes or os.PathLike object, not NoneType" usually means the template path argument was empty because a shell variable holding it was unset.

Related guides

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