Overview

5 Templating tasks using the Airflow context

This chapter explains how Airflow’s templating and task context make pipelines dynamic and time-aware, moving beyond static, one-size-fits-all workflows. Using a running example that ingests hourly Wikipedia pageviews for a handful of company pages, it shows how to plan incremental processing, construct parameterized URLs from scheduling metadata, and adapt behavior at runtime. The overarching goals are to render variables as tasks run, apply templating consistently across operators, debug rendered values efficiently, and interact reliably with external systems.

The core mechanics center on Jinja templating and the task context. Many operators (such as BashOperator) accept arguments that Airflow renders with Jinja at execution time, governed by each operator’s template_fields and optional template_ext for file-based templates. By contrast, PythonOperator passes the runtime context to a Python callable, which can accept named parameters (for explicit intent) or **kwargs to capture everything; you can also pass your own arguments via op_args and op_kwargs, and even template those values before they reach the callable. The chapter shows how to inspect rendered templates in the UI or via the CLI, and surveys the most useful context variables (for example logical_date, data_interval_start/end, ds, and ts) used to compute strings like zero-padded timestamps.

Bringing these ideas together, the workflow downloads an hourly gzip of pageviews, extracts it, parses counts for selected page titles, and persists results to Postgres using SQLExecuteQueryOperator. It demonstrates templating file paths and SQL, configuring a connection via conn_id, and adding template_searchpath so Airflow can render external .sql files. The discussion clarifies the roles of operators (what to do) and hooks (how to connect), and notes the need for provider dependencies when talking to external systems. The outcome is an automated, repeatable pipeline whose tasks run on the correct schedule, produce time-stamped outputs, and populate a database that supports downstream analysis such as identifying peak viewing hours.

Downloading and inspecting Wikimedia pageviews data
First simple analysis on Wikimedia pageviews data
First version of the StockSense workflow
Not all variables are known upfront when writing code, for example, when using interactive elements such as forms.
Providing task context with a PythonOperator
The PythonOperator takes a function instead of string arguments and thus cannot be Jinja-templated. In this called function, we extract datetime components from the data_interval_start to dynamically construct the URL.
Python determines if a given keyword argument is passed to one specific argument in the function, or to the ** argument if no matching name was found.
_get_data expects an argument named data_interval_start. No default value is set, so it will fail if not provided.
Any named argument can be given to _get_data(). data_interval_start must be provided explicitly because it’s listed as an argument, all other arguments are captured by **context.
The output_path is now configurable via an argument.
Inspecting the rendered template values after running a task.
Conceptual idea of workflow. After extracting the pageviews, write the pageview counts to a SQL database.
DAG fetching hourly Wikipedia pageviews and writing results to Postgres
Connection listed in Airflow UI
Running a SQL script against a Postgres database involves several components. Provide the correct settings to the SQLExecuteQueryOperator, and the DbApiHook will do the work under the hood.

Summary

  • In Airflow, templating allows for the dynamic parameterization of tasks at runtime. This enables the creation of more generic and reusable workflows, as values like dates or filepaths can be determined when the DAG is executed, rather than being hardcoded.
  • Jinja templating lets you create flexible workflows in Airflow operators. For example, you can dynamically generate a SQL 'SELECT' statement using Jinja templating. By including {{ logical_date }} within the query. Airflow will replace it with the current interval (e.g., '20240101').
  • The PythonOperator in Airflow is unique when it comes to templating. Unlike with other operators, the PythonOperator variables and runtime information are not templated with Jinja but instead all variables are passed as a dictionary directly to the function that the python_callable points to during execution.
  • By using op_args (a list of positional arguments) and op_kwargs (a dictionary of keyword arguments) you can pass additional parameters to the python callable of a PythonOperator.
  • The airflow tasks render command allows you to test and verify the output of the templated arguments before running the actual tasks in a workflow.
  • Operators describe what to do; hooks, on the other hand, define the how aspect, handling the interaction with external systems and services. They are connection interfaces to external systems like databases, cloud services, or file systems.

FAQ

What does “templating” mean in Airflow and why is it useful?Templating lets you insert runtime values into strings using Jinja syntax (e.g., {{ logical_date.year }}). Airflow renders these values right before a task runs, so your tasks can adapt to each run’s time window (for example, building hourly URLs, file names, or SQL queries). This makes pipelines dynamic instead of hard-coding dates or paths.
What is the difference between logical_date and data_interval_start/data_interval_end?logical_date is the pendulum.DateTime timestamp associated with a task run. data_interval_start and data_interval_end represent the start and end of the data window the run is supposed to process. For many time-based schedules, logical_date often corresponds to the interval start, but when you need the exact window boundaries, prefer data_interval_start and data_interval_end.
Which operator arguments can be templated?Only attributes listed in an operator’s template_fields are rendered by Jinja. If a field is not in template_fields, {{ ... }} stays literal. Some operators also support templating file contents based on allowed extensions in template_ext (e.g., .sql). Check the operator’s documentation for both lists.
How does templating differ for PythonOperator compared to other operators?Most operators (like BashOperator) accept templateable string arguments (e.g., bash_command). PythonOperator instead takes a python_callable (a function). Its function body is not Jinja-rendered; instead, Airflow passes task context values as keyword arguments when calling your function. You can still pass templated strings into the callable via op_args/op_kwargs, which Airflow renders before invocation.
How do I access the task context in a Python callable?- Accept **kwargs (often named **context for clarity) to receive all context variables as a dict. - Or explicitly name the ones you need in the function signature (e.g., def my_fn(data_interval_start, **context): ...). Airflow matches keyword arguments by name; anything not matched goes into **context.
How can I pass my own parameters into a PythonOperator function?Use op_args (positional) and op_kwargs (keyword) to supply arguments to your python_callable. These values can themselves be templated strings (e.g., "year": "{{ logical_date.year }}"), which Airflow renders at runtime. This keeps your functions reusable and configuration-driven.
How can I inspect or debug rendered template values?- Airflow UI: Open the task instance in Graph/Grid view and click “Rendered Template” to see rendered fields for that run. - CLI: airflow tasks render DAG_ID TASK_ID EXECUTION_DATE prints the rendered values without scheduling or executing the task. This is convenient during development.
What context variables and helpers are available for templating?Common ones include: - Dates/times: logical_date, data_interval_start, data_interval_end, ds (YYYY-MM-DD), ds_nodash (YYYYMMDD), ts (ISO8601), ts_nodash, ts_nodash_with_tz - Metadata: dag, task, task_instance, run_id - User inputs: params, var (Variables) - Utilities: macros (airflow.macros) - Others: prev_data_interval_start_success, prev_data_interval_end_success, inlets/outlets, map_index_template. Note that some legacy variables are deprecated/removed in Airflow 3.
How do I template SQL files and make Airflow find them?Operators that list "sql" in template_fields and ".sql" in template_ext can render file contents. Provide the path (e.g., sql="my_query.sql") and set template_searchpath on the DAG to include the directory if the file isn’t alongside the DAG file. Airflow will load, render, and execute the SQL from that file.
How does Airflow interact with external systems like Postgres?Use provider operators (e.g., SQLExecuteQueryOperator) and configure a connection via conn_id. The operator delegates to a hook (e.g., DbApiHook) that opens the connection, runs queries, and closes it. Install the required provider packages, store credentials in Airflow Connections (UI or CLI), and then reference the conn_id in your task. For inter-task data, use XCom or persist to shared storage (e.g., files or databases) since tasks may run on different machines.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Data Pipelines with Apache Airflow, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Data Pipelines with Apache Airflow, Second Edition ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Data Pipelines with Apache Airflow, Second Edition ebook for free