Jinja2 Templates for DevOps Automation
Template
What is Jinja2?
Jinja2 is a templating language used by Ansible, SaltStack, Helm (via Sprig),
and countless Python web frameworks. It uses {{ variable }} for interpolation
and {% for %} / {% if %} for control flow.
DevOps Use Cases
Dynamic Kubernetes Manifests
# deployment.j2
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ app_name }}
spec:
replicas: {{ replicas | default(2) }}
template:
spec:
containers:
- name: {{ app_name }}
image: "{{ image }}:{{ tag }}"
env:
{% for key, value in env_vars.items() %}
- name: {{ key }}
value: "{{ value }}"
{% endfor %}
Nginx Config Generation
Generate server blocks for multiple domains without copy-pasting:
{% for domain in domains %}
server {
server_name {{ domain }};
location / { proxy_pass http://{{ backend }}; }
}
{% endfor %}
Using the API
curl -X POST https://api.toolkitapi.io/v1/devtools/jinja2-render \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"template": "Hello {{ name }}!",
"variables": { "name": "World" }
}'
Filters
Jinja2 filters transform values inline:
| Filter | Example | Result |
|---|---|---|
upper |
{{ name\|upper }} |
ALICE |
default |
{{ val\|default("n/a") }} |
n/a if val is undefined |
join |
{{ list\|join(", ") }} |
a, b, c |
to_json |
{{ obj\|to_json }} |
JSON string |
Sandbox Mode
The API renders templates in a sandboxed environment — no filesystem access,
no __import__, no subprocess calls. It is safe to render user-supplied templates.