2.0 中的气流 dag 和任务装饰器:如何将配置参数传递给任务?

时间:2021-01-12 17:05:41

标签: airflow

我正在努力理解如何使用 Airflow 2.0 dag 和任务装饰器读取任务中的 DAG 配置参数。

考虑这个简单的 DAG 定义文件:

from airflow.decorators import dag, task
from airflow.utils.dates import days_ago

@dag()
def lovely_dag():
   
    @task(start_date=days_ago(1))
    def task1():
       return 1

    something = task1()

my_dag = lovely_dag()

我可以使用 UI 或控制台触发 dag 并将一些(键,值)配置传递给它,例如:

airflow dags trigger --conf '{"hello":"there"}' lovely_dag

如何在 task1 函数中访问 {"hello":"there"} ?

我的用例是我想将 2 个参数传递给 dag 并希望 task1 看到它们。

1 个答案:

答案 0 :(得分:3)

您可以按如下方式访问上下文:

from airflow.operators.python import task, get_current_context

@task
def my_task():
    context = get_current_context()
    dag_run = context["dag_run"]
    dagrun_conf = dag_run.conf

其中 dagrun_conf 将是包含 DAG 配置参数的变量

来源:http://airflow.apache.org/docs/apache-airflow/2.0.0/concepts.html#accessing-current-context