为apache气流任务获取unique_id

时间:2017-09-15 14:50:48

标签: python bash airflow

我是气流新手。在我公司的ETL管道中,目前我们正在使用Crontab和自定义调度程序(内部开发)。现在我们计划为所有数据管道方案实施apache气流。探索无法为每个任务实例/ Dag找到 unique_id 的功能。当我搜索大多数解决方案时,最终都是宏和模板。但是没有一个没有为任务提供唯一ID。但是我能够在UI中看到每个任务的增量uniqueID。有什么方法可以轻松访问我的python方法中的那些变量。主要的用例是我需要将这些ID作为参数传递给Python / ruby / Pentaho作业,称为脚本/方法。

例如

我的shell脚本' test.sh'需要两个参数,一个是run_id,另一个是collection_id。目前,我们正在从集中式数据库生成这个唯一的run_id并将其传递给作业。如果它已经存在于气流上下文中,我们将使用该

from airflow.operators.bash_operator import BashOperator
from datetime import date, datetime, timedelta
from airflow import DAG

shell_command =  "/data2/test.sh -r run_id -c collection_id"


putfiles_s3 = BashOperator(
                task_id='putfiles_s3',
                bash_command=shell_command,
                dag=dag)

在执行此Dag(计划/手动)时为每次运行寻找唯一的run_id(Dag级别/任务级别)

注意:这是一个示例任务。这个Dag将有多个依赖任务。 从气流UI附加Job_Id屏幕截图 enter image description here

由于 Anoop R

1 个答案:

答案 0 :(得分:2)

{{ ti.job_id }}就是你想要的:

from datetime import datetime, timedelta
from airflow.operators.bash_operator import BashOperator
from airflow import DAG


dag = DAG(
    "job_id",
    start_date=datetime(2018, 1, 1),
)

with dag:
    BashOperator(
        task_id='unique_id',
        bash_command="echo {{ ti.job_id }}",
    )

这在运行时有效。此执行的日志如下所示:

[2018-01-03 10:28:37,523] {bash_operator.py:80} INFO - Temporary script location: /tmp/airflowtmpcj0omuts//tmp/airflowtmpcj0omuts/unique_iddq7kw0yj  
[2018-01-03 10:28:37,524] {bash_operator.py:88} INFO - Running command: echo 4
[2018-01-03 10:28:37,621] {bash_operator.py:97} INFO - Output:
[2018-01-03 10:28:37,648] {bash_operator.py:101} INFO - 4

请注意,这仅在运行时有效,因此webui中的“呈现模板”视图将显示“无”而不是数字。