【问题标题】:Getting unique_id for apache airflow tasks获取 apache 气流任务的 unique_id
【发布时间】:2017-09-15 14:50:48
【问题描述】:

我是气流新手。在我的 ETL 管道公司中,目前我们正在使用 Crontab 和自定义调度程序(内部开发)。现在我们计划为我们的所有数据管道场景实施 apache 气流。为此探索无法为每个任务实例/Dag 找到 unique_id 的功能。当我搜索大多数解决方案时,大多数解决方案都以宏和模板结尾。但是它们都没有为任务提供唯一 ID。但是我能够在 UI 中看到每个任务的增量唯一 ID。有什么方法可以轻松访问我的 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 屏幕截图

谢谢 阿努普R

【问题讨论】:

  • 包含您的代码
  • @MicahElliott 感谢您的建议。我们可以像这样或从 shell 随机命令生成随机 id。我正在寻找一些由气流本身生成的 id,就像 job_id 一样。附上 Airflow UI 的屏幕截图以供参考.

标签: python bash airflow


【解决方案1】:

{{ 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 中的“渲染模板”视图将显示 None 而不是数字。

【讨论】:

  • {{ ti.job_id }} 我可以与任何运算符一起使用,也可以作为参数传递给 Python 方法,对吗?如果你不介意,你能给我举个例子,将这个值传递给python方法感谢Ash Berlin-Taylor。
  • 我得到了将相同的方法传递给 python 方法 def test_failure(**kwargs): print ' Instance variables access from context ' ti=kwargs['ti'] print ti.job_id @Ash Is有任何文件可以通过“task_instance”提供所有可用的值。这个网址没有解释太多关于“ti”pythonhosted.org/airflow/code.html#macros
  • 现在不行,不行。 "ti" 是一个 TaskInstance pythonhosted.org/airflow/code.html#airflow.models.TaskInstance 但它没有记录该对象的任何属性,所以我转到代码。
猜你喜欢
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 2021-04-01
  • 2018-09-28
  • 1970-01-01
相关资源
最近更新 更多