繁体   English   中英

如何使用传递的输入 json 配置的值来触发 dag 内的 airflow 作业?

[英]How to use the values of input json configurations passed to trigger the airflow job inside the dag?

我是 airflow 的新手,正在处理一个用例,我需要读取传递给 airflow dag 的输入 json 配置,并根据读取的配置构造一个字符串,该字符串将用作我们正在创建的集群的名称在 GCP 数据处理中。

例如:输入 Json 到 dag

{“x”:“数据”,“y”:“engg”,“z”:“用例”}

我希望集群名称为“my-cluster-for-data-engg-usecase”,代码如下,但出现无法识别“dag_run”的错误。 任何帮助,将不胜感激。

from datetime import datetime
from airflow import DAG
from airflow.utils.dates import days_ago
from airflow.operators.python_operator import PythonOperator
from airflow import models
from airflow.utils.dates import days_ago

CONN_ID = 'blah'
PROJECT_ID = 'xyz'
REGION = 'us-east4'
CLUSTER_NAME = "my-cluster-for-"+dag_run.conf['x']+dag_run.conf['y']+dag_run.conf['z']
with models.DAG('simple-python-dag', start_date=days_ago(1), schedule_interval=None) as dag:


    create_cluster_spark = XyzCreateClusterOperator(task_id='create_cluster_spark',
                                                    cluster_name=CLUSTER_NAME,
                                                    location=REGION,
                                                    gcp_conn_id=CONN_ID)

    create_cluster_spark

dag_run仅在活动的 DAG 运行中可用(即当您触发 DAG 并且它正在运行时)- 将dag_run.conf指定为 object 将不起作用,因为 Airflow 调度程序将解析您的 dag(默认情况下每 30 秒)并且不存在这样的 object。

有两种方式访问dag_run

  1. 使用模板系统
CLUSTER_NAME = "my-cluster-for-{{ dag_run.conf['x'] }}{{ dag_run.conf['y'] }}{{ dag_run.conf['z'] }}"

这仅在cluster_name字段是XyzCreateClusterOperator Operator 中的模板化字段时才有效。 您可以通过查看文档字符串或查看 Airflow 运算符文档来检查字段是否已模板化。

如果XyzCreateClusterOperator是第三方提供商,您可以在此处查看提供商的文档

您可以在此处查看模板中的所有可用项( dag_run是您可以使用此模板语法访问的众多内容之一)。

  1. 您可以在 python 操作员中访问dag_run
import pendulum
from airflow.decorators import dag, task

@dag(
    schedule_interval=None,
    start_date=pendulum.datetime(2022, 4, 18),
    catchup=False,
)
def example_dag():
    @task()
    def dag_run_example_task(**context):
        context["dag_run"].conf.get("x")
        context["dag_run"].conf.get("y")
        context["dag_run"].conf.get("z")

如果cluster_name不是模板化字段,您可以使用 Python 运算符环绕您的运算符并替换为:

import pendulum
from airflow.decorators import dag, task

@dag(
    schedule_interval=None,
    start_date=pendulum.datetime(2022, 4, 18),
    catchup=False,
)
def example_dag():
    @task()
    def dag_run_example_task(**context):
        cluster_name = "my-cluster-for-"+context["dag_run"].conf.get("x")+context["dag_run"].conf.get("y")+context["dag_run"].conf.get("z")

        create_cluster_spark = XyzCreateClusterOperator(
            task_id='create_cluster_spark',
            cluster_name=cluster_name,
            location=REGION,
            gcp_conn_id=CONN_ID,
        )

        create_cluster_spark.execute(context=context)

此处模板中可用的相同对象在传递给 PythonOperator 的context object 中可用(还有一些)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM