j2cli: Jinja2 Command-Line Tool
j2cli is a command-line tool that enables Jinja2 templating directly within shell scripts, leveraging the powerful Jinja2 library. It supports various data sources, including INI, YAML, JSON files, and environment variables. The current PyPI version is 0.3.10. While still functional for many use cases, active development on PyPI appears to have slowed, with the last release in 2019, though newer versions (0.3.12b*) are seen in some Linux distributions.
Warnings
- breaking j2cli is incompatible with Python 3.12 and newer versions due to its reliance on the removed `imp` module. This prevents `j2cli` from running on Python 3.12+.
- deprecated The `j2cli` project appears to be largely unmaintained by its original author on PyPI, with the last release being in 2019. While the project is still widely used, the lack of updates has led to critical compatibility issues with newer Python versions.
- gotcha To enable YAML data source parsing, `j2cli` requires the `pyyaml` dependency. This is not installed by default and must be explicitly included during installation using `pip install j2cli[yaml]`.
- gotcha When no data file is provided, `j2cli` defaults to reading environment variables (implicitly setting `--format=env`). To explicitly import environment variables into the template as a specific variable (e.g., `env`), use `--import-env VAR` (or `-e VAR`). To import all environment variables into the global scope (which can overwrite existing variables), use `--import-env=`.
Install
-
pip install j2cli -
pip install j2cli[yaml]
Quickstart
# Create a Jinja2 template file
cat <<EOF > config.j2
server {
listen 80;
server_name {{ app.hostname }};
root {{ app.webroot }};
index index.htm;
}
EOF
# Create a JSON data file
cat <<EOF > data.json
{
"app": {
"hostname": "localhost",
"webroot": "/var/www/myproject"
}
}
EOF
# Render the template using j2cli
j2 -f json config.j2 data.json
# Expected output:
# server {
# listen 80;
# server_name localhost;
# root /var/www/myproject;
# index index.htm;
# }