动态生成气流DAG

时间:2020-06-04 12:52:07

标签: airflow

我正在尝试使用python代码中的模板并使用定义为here的globals()来生成气流损失

定义并保存dag对象。下面是我的代码:

import datetime as dt
import sys 

import airflow
from airflow.models import DAG
from airflow.operators.bash_operator import BashOperator

argumentList = sys.argv
owner = argumentList[1]
dag_name = argumentList[2]
taskID = argumentList[3]
bashCommand = argumentList[4]

default_args = {
    'owner': owner,
    'start_date': dt.datetime(2019, 6, 1),
    'retries': 1,
    'retry_delay': dt.timedelta(minutes=5),
}

def dagCreate():
    with DAG(dag_name,
             default_args=default_args,
             schedule_interval=None,
             ) as dag:

        print_hello = BashOperator(task_id=taskID, bash_command=bashCommand)
    return dag

globals()[dag_name] = dagCreate()

我已将此Python代码保留在dag_folder之外,并按如下所示执行它:

python bash-dag-generator.py Airflow test_bash_generate auto_bash_task ls

但是我没有在气流Web服务器用户界面中看到任何DAG。我不确定我要去哪里错了。

2 个答案:

答案 0 :(得分:0)

根据official documentation

DAG是在Airflow的DAG_FOLDER中放置的标准Python文件中定义的。 Airflow将执行每个文件中的代码以动态构建DAG对象。您可以根据需要拥有任意数量的DAG,每个DAG描述任意数量的任务。通常,每个人应该对应一个逻辑工作流程。

因此,除非您的代码实际上位于DAG_FOLDER内,否则它将不会注册为DAG。

答案 1 :(得分:0)

我能够实现动态DAG的方法是使用气流变量。 在下面的示例中,我有一个csv文件,其中包含Bash命令的列表,如ls,echo等。作为read_file任务的一部分,我正在将文件位置更新为Airflow Variable。我们读取csv文件并循环执行命令的部分是创建动态DAG的位置。

from airflow import DAG

from airflow.operators.python_operator import PythonOperator
from airflow.operators.bash_operator import BashOperator

from airflow.models import Variable
from datetime import datetime, timedelta
import csv
'''
Orchestrate the Dynamic Tasks
'''
def read_file_task():
    print('I am reading a File and setting variables ')
    Variable.set('dynamic-dag-sample','/home/bashoperator.csv')

with DAG('dynamic-dag-sample',
    start_date=datetime(2018, 11, 1)) as dag:
    read_file_task = PythonOperator(task_id='read_file_task',
                                              python_callable=read_file_task, provide_context=True,
                                               dag=dag)


dynamic_dag_sample_file_path = Variable.get("dynamic-dag-sample")
if dynamic_dag_sample_file_path != None:
    with open(dynamic_dag_sample_file_path) as csv_file:
        reader = csv.DictReader(csv_file)
        line_count = 0
        for row in reader:
            bash_task = BashOperator(task_id=row['Taskname'], bash_command=row['Command'])
            read_file_task.set_downstream(bash_task)