Jinja2 Template
This page shows how to use Apache Airflow® Jinja2 templating within a YAML-based DAG definition using DAG-Factory.
Built-in Variables
Airflow exposes a set of built-in Jinja2 variables (e.g. ds, run_id, task) that are available in all task templates without any configuration.
Example DAG
example_jinja2_template_dag:
default_args:
start_date: "2025-01-01"
schedule: "@daily"
description: "A DAG that uses Airflow's built-in Jinja templates"
catchup: false
tasks:
- task_id: "print_run_id"
operator: "airflow.operators.bash.BashOperator"
bash_command: "echo 'run-id is {{ run_id }}'"
- task_id: "print_task"
operator: "airflow.operators.bash.BashOperator"
bash_command: "echo 'The task is {{ task }}'"
dependencies:
- print_run_id
User-Defined Macros
Airflow allows you to extend the Jinja2 templating environment with custom macros via the user_defined_macros DAG parameter. These macros are callable functions or values made available in all task templates of the DAG.
In DAG-Factory, user_defined_macros values are specified as dotted import paths (e.g. module.function) and are imported at DAG build time. Nested dicts are supported, allowing you to group related macros under a namespace.
Example DAG
default:
catchup: false
default_args:
start_date: 2025-01-01
example_user_defined_macros:
description: "DAG-Factory example using user_defined_macros"
schedule: "@daily"
user_defined_macros:
add_days: "sample.add_days" # top-level callable
date_utils: # nested dict with callable leaf
shift: "sample.add_days"
tasks:
- task_id: "print_macros"
operator: "airflow.providers.standard.operators.bash.BashOperator"
bash_command: >-
echo 'Run date: {{ ds }} |
Yesterday: {{ add_days(ds, -1) }} |
Tomorrow: {{ add_days(ds, 1) }} |
Nested yesterday: {{ date_utils.shift(ds, -1) }}'
Accessing macros in templates
- Top-level callable:
{{ add_days(ds, -1) }} - Nested callable:
{{ date_utils.shift(ds, -1) }}