ttechdo
ttechdo

Reputation: 93

How to get Airflow user who manually trigger a DAG?

In the Airflow UI, one of the log events available under "Browser > Logs" is the event "Trigger" along with the DAG ID and Owner/User who's responsible for triggering this event. Is this information easily obtainable programmatically?

The use case is, I have a DAG that allows a subset of users to manually trigger the execution. Depending on the user who triggers the execution of this DAG, the behavior of code execution from this DAG will be different.

Thank you in advance.

Upvotes: 8

Views: 10022

Answers (2)

Bitte_Dritte
Bitte_Dritte

Reputation: 31

I will correct the previous answer a little:

    with create_session() as session:
       results = session.query(Log.dttm, Log.dag_id, Log.execution_date, 
       Log.owner, Log.extra)\
       .filter(Log.dag_id == 'dag_id', Log.event == 
       'trigger').order_by(Log.dttm.desc()).all()

Upvotes: 3

kaxil
kaxil

Reputation: 18874

You can directly fetch it from the Log table in the Airflow Metadata Database as follows:

from airflow.models.log import Log
from airflow.utils.db import create_session

with create_session() as session:
   results = session.query(Log.dttm, Log.dag_id, Log.execution_date, Log.owner, Log.extra).filter(Log.dag_id == 'example_trigger_target_dag', Log.event == 'trigger').all()

# Get top 2 records
results[2]

Output:

(datetime.datetime(2020, 3, 30, 23, 16, 52, 487095, tzinfo=<TimezoneInfo [UTC, GMT, +00:00:00, STD]>),
 'example_trigger_target_dag',
 None,
 'admin',
 '[(\'dag_id\', \'example_trigger_target_dag\'), (\'origin\', \'/tree?dag_id=example_trigger_target_dag\'), (\'csrf_token\', \'IjhmYzQ4MGU2NGFjMzg2ZWI3ZjgyMTA1MWM3N2RhYmZiOThkOTFhMTYi.XoJ92A.5q35ClFnQjKRiWwata8dNlVs-98\'), (\'conf\', \'{"message": "kaxil"}\')]')

Upvotes: 9

Related Questions