Get an XCom value in the Airflow on_failure_callback function

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

When we want to get an XCom variable in the on_failure_callback, we will face a nasty bug. Using the ti key to retrieve a value from the context gives us a None value.

# This does not work

It happens because in the on_failure_callback the task instance is passed to the function using the task_instance key. Therefore to get a value from XCom, we must execute this code:

task: TaskInstance = context.get('task_instance')

Alternatively, we can import XCom and access it directly:

from airflow.models import XCom
XCom.get_one(execution_date = context.get('execution_date'), key='test')

Subscribe to the newsletter and join the free email course.

Remember to share on social media!
If you like this text, please share it on Facebook/Twitter/LinkedIn/Reddit or other social media.

If you want to contact me, send me a message on LinkedIn or Twitter.

Bartosz Mikulski
Bartosz Mikulski * MLOps Engineer / data engineer * conference speaker * co-founder of Software Craft Poznan & Poznan Scala User Group

Subscribe to the newsletter and get access to my free email course on building trustworthy data pipelines.