How to use xcom_pull to get a variable from another DAG

This article is a part of my "100 data engineering tutorials in 100 days" challenge. (62/100)

In this article, I will show you how to get an XCOM variable from another Airflow DAG.

Please remember that it is not the recommended way of writing Airflow DAGs because DAGs should be independent of each other.

Airflow, however, does not stop us from using XCOM to communicate between DAGs. Here is a description of how we can do that:

  1. First, we need a reference to the task instance. We can get that, for example, in the PythonOperator when we set the provide_context parameter to True:
1
2
3
4
5
6
some_task = PythonOperator(
    task_id='the_task_id',
    python_callable=function_name,
    provide_context=True,
    dag=dag
)

When we do that, the function gets the DAG context as the parameter, and we can extract the task instance from the context:

1
2
def function_name(**kwargs):
    task_instance = kwargs['task_instance']
  1. Now, we can use the xcom_pull function to get the variable. Note that I have to specify both the name of the task that published the variable and the DAG identifier:
1
task_instance.xcom_pull(dag_id='dag_id', task_ids='task_id', key="variable_name")

There is one caveat that makes this approach almost useless. Both DAGs must have the same execution date. It is caused by the implementation of xcom_pull in the TaskInstance class. The code in the Airflow repository looks like this:

1
2
3
4
5
6
7
8
query = XCom.get_many(
    execution_date=self.execution_date,
    key=key,
    dag_ids=dag_id,
    task_ids=task_ids,
    include_prior_dates=include_prior_dates,
    session=session,
).with_entities(XCom.value)

Did you enjoy reading this article?
Would you like to learn more about software craft in data engineering and MLOps?

Subscribe to the newsletter or add this blog to your RSS reader (does anyone still use them?) to get a notification when I publish a new essay!

Newsletter

Do you enjoy reading my articles?
Subscribe to the newsletter if you don't want to miss the new content, business offers, and free training materials.

Bartosz Mikulski

Bartosz Mikulski

  • Data/MLOps engineer by day
  • DevRel/copywriter by night
  • Python and data engineering trainer
  • Conference speaker
  • Contributed a chapter to the book "97 Things Every Data Engineer Should Know"
  • Twitter: @mikulskibartosz
Newsletter

Do you enjoy reading my articles?
Subscribe to the newsletter if you don't want to miss the new content, business offers, and free training materials.