airflow icon indicating copy to clipboard operation
airflow copied to clipboard

Allow usage of Jinja templating inside task `param`

Open elephantmetropolis opened this issue 3 years ago • 12 comments

Description

Currently, it is not possible to use Jinja templates inside the params field of a task.

It is not possible to do the following :

bo = BashOperator(
   task_id="bash_task",
   bash_command = "do-something.sh {{params.path}}",
   params = {"path": "/path/to/thing/{{ ds }}/thing.csv"}
)

Use case/motivation

We have a case using the PostgresOperator :

PostgresOperator(
      task_id="do_postgres_operation",
      sql="my_sql_script.sql",
      params={
            "schema": "my_schema",
            "bucket": "my_bucket"
      }
)

Say my_sql_script.sql is a script that let you copy data from S3 bucket to Postgres. It's pretty common and we would like to reuse it here and there. But in our case, we get the s3_file_name from the xcom of the previous task, so to get that filename we need to use {{ ti.xcom_pull(task_ids='my_previous_task') }} and we would like to use it in params that way :

      ...
      params={
            "schema": "my_schema",
            "bucket": "my_bucket",
            "s3_file_name": "{{ ti.xcom_pull(task_ids='my_previous_task') }}"
      }
      ...

But it's not possible, we thus need to hard-code {{ ti.xcom_pull(task_ids='my_previous_task') }} inside my_sql_script.sql script.

But later in the code, we don't want s3_file_name to come from xcom but rather from a python variable, and it's impossible because it's hard coded in the sql template. We have to create an other sql file with the exact same code except for s3_file_name.

Related issues

This issue is related to the problem : https://github.com/apache/airflow/issues/7910 It has been marked as resolved but the 2 PRs associated are closed

Are you willing to submit a PR?

  • [ ] Yes I am willing to submit a PR!

Code of Conduct

elephantmetropolis avatar Jun 08 '23 18:06 elephantmetropolis

Thanks for opening your first issue here! Be sure to follow the issue template! If you are willing to raise PR to address this issue please do so, no need to wait for approval.

boring-cyborg[bot] avatar Jun 08 '23 18:06 boring-cyborg[bot]

It's a good feature! If you truly need it and you want to become an Airflow contributor, I encourage you to take the initiative and implement it yourself. Otherwise, you'll have to wait for someone else to pick up the issue and implement it.

hussein-awala avatar Jun 08 '23 18:06 hussein-awala

Would love to do it !

elephantmetropolis avatar Jun 08 '23 19:06 elephantmetropolis

Great! I assigned you

hussein-awala avatar Jun 08 '23 19:06 hussein-awala

same than https://github.com/apache/airflow/discussions/18812

another missing templating are the mapped parameters of Dynamic Task Mapping tasks -> https://github.com/apache/airflow/discussions/29660#discussioncomment-5108231

raphaelauv avatar Jun 08 '23 22:06 raphaelauv

could i try adding templating for the mapped parameters of Dynamic Task mapping?

Bowrna avatar Jun 11 '23 17:06 Bowrna

@elephantmetropolis

hack to use templating on templated values

from os import path

from airflow.models import DAG
from airflow.utils.dates import days_ago
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator

with DAG(dag_id="toto",
         start_date=days_ago(1),
         schedule_interval="@daily"):
    def generate_sql_query():
        with open(path.join(path.dirname(path.abspath(__file__)), "toto.sql"), "r") as sql_file:
            return sql_file.read().format(something="TOTO", logical_date="{{ ds }}")


    class CustomSQLExecuteQueryOperator(SQLExecuteQueryOperator):
        from airflow.utils.context import Context
        import jinja2
        def render_template_fields(
                self,
                context: Context,
                jinja_env: jinja2.Environment = None,
        ) -> None:
            self.sql = self.sql()
            super().render_template_fields(context, jinja_env)


    CustomSQLExecuteQueryOperator(
        task_id="something",
        sql=generate_sql_query,
        conn_id='toto',
    )

sql file toto.sql in same path than the dag file

select
    *,
    date('{logical_date}')
from toto_{something}

give

image

raphaelauv avatar Jul 24 '23 23:07 raphaelauv

since airlfow 2.10.0

you can do

from pathlib import Path

from airflow.models import DAG
from airflow.utils.dates import days_ago
from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator

with DAG(dag_id="toto",
         start_date=days_ago(1),
         schedule="@daily"):


    def generate_sql_query(context, jinja_env) -> list[str]:
        with Path(__file__).with_name('toto.sql').open('r') as f:
            query = f.read().format(something="TOTO", logical_date="{{ ds }}")
            query = context["task"].render_template(query, context, jinja_env)
            return query.split(";")


    SQLExecuteQueryOperator(
        task_id="something",
        sql=generate_sql_query,
        conn_id='toto',
    )

sql file toto.sql in same path than the dag file

select
    *,
    date('{logical_date}')
from toto_{something}

raphaelauv avatar Nov 19 '24 02:11 raphaelauv

To parse params attribute, I've been taking the following approach.

  • Create a custom operator extending the original.
  • Override method render_template_fields to parse the params attribute in the context.

I've been using it for quite a while, no issues so far. This is an example with PostgresOperator.

from airflow import DAG
from airflow.decorators import task
from airflow.providers.postgres.operators.postgres import PostgresOperator

with DAG( 
    dag_id = 'Parsed-params-with-PG', 
    schedule_interval = None
) as dag:

    class CustomPostgresOperator(PostgresOperator):
        def render_template_fields(self, context, jinja_env = None):
            if isinstance(self.params, dict):
                context['params'] = self.render_template(self.params, context, jinja_env, set())
            else:
                context['params'] = self.render_template(self.params.dump(), context, jinja_env, set())
            super().render_template_fields(context, jinja_env)

    @task
    def push_to_xcom():
        return "Europe/Rome"

    pg_task = CustomPostgresOperator(
        task_id="pg_task",
        postgres_conn_id='DB',
        sql="SET TIME ZONE '{{ params.time_zone }}'",
        params = {
            "time_zone": '{{ ti.xcom_pull(task_ids="push_to_xcom", key="return_value") }}'
        }
    )

    push_to_xcom() >> pg_task

iAlevato avatar Jan 08 '25 18:01 iAlevato

since airlfow 2.10.0

you can do

from pathlib import Path

from airflow.models import DAG from airflow.utils.dates import days_ago from airflow.providers.common.sql.operators.sql import SQLExecuteQueryOperator

with DAG(dag_id="toto", start_date=days_ago(1), schedule="@daily"):

def generate_sql_query(context, jinja_env) -> list[str]:
    with Path(__file__).with_name('toto.sql').open('r') as f:
        query = f.read().format(something="TOTO", logical_date="{{ ds }}")
        query = context["task"].render_template(query, context, jinja_env)
        return query.split(";")


SQLExecuteQueryOperator(
    task_id="something",
    sql=generate_sql_query,
    conn_id='toto',
)

sql file toto.sql in same path than the dag file

select *, date('{logical_date}') from toto_{something}

@raphaelauv Great! Didn't know about it, but is weird we need to use {logical_date}, and not {{logical_date}}. Why is that? I thought Jinja worked all time with double curly brackets

set92 avatar Feb 04 '25 12:02 set92

@set92 the logical_date is "templated" with a format not by jinja, so my templating "pipeline" is

{logical_date} -> format -> {{ds}} -> jinja -> 2024-01-03

-- WHY ?

cause I don't want to put airflow jinja macro in my sql ( separation of concern )

raphaelauv avatar Feb 04 '25 12:02 raphaelauv

Hi, I'd like to work on this. My proposed approach: extend template rendering so that string values inside the task params dict are rendered with the task context (the same Jinja environment used for template_fields), e.g. in BaseOperator.render_template_fields / the template preparation path, walking params values recursively for dicts/lists. This would allow params={"s3_file_name": "{{ ti.xcom_pull(task_ids='my_previous_task') }}"} as requested.

One design question before I start: should params rendering be always-on, or opt-in per task (to avoid breaking existing Dags whose params contain literal {{ }} text)? Happy to follow maintainer preference and add tests either way.

dasarijashwanth avatar Nov 27 '26 06:11 dasarijashwanth