簡體   English   中英

如何從 Airflow 中的變量呈現 email 地址的默認列表?

[英]How can the default list of email addresses be rendered from a variable in Airflow?

我有很多 Airflow DAG,我想在任何任務失敗時自動向相同的收件人列表(存儲在 Airflow 變量中)發送 email 通知,因此我使用在 DAG 級別定義的以下默認運算符配置:

dag = DAG(
    ...
    default_args = {
        ...
        "email": "{{ ','.join( var.json.get("my_email_list", []) ) }}",
        "email_on_failure": True,
        ...
    },
    ...
)

不幸的是,看起來email參數不支持模板,它只是按原樣傳遞給 email 后端而不進行渲染,所以我的方法不起作用。

有人可以為我的特殊情況提出一個體面的解決方法嗎? 我真的不想在源代碼中對 email 地址列表進行硬編碼,因為將它們存儲在 Airflow 變量中會提供更大的靈活性。

您有兩種讀取 Airflow 變量的方法:

  1. 在執行任務時使用 jinja 模板在運行時讀取它們
  2. 在創建任務之前使用 class Variable在調度程序中讀取它們:
from airflow.models import Variable

emails = Variable.get("my_email_list", deserialize_json=True)

這是我的一個有點老套的解決方案,因為BaseOperator既沒有在email中模板化,也沒有辦法在任務級別調整template_fields (通過任務,我的意思是操作員的配置實例),而且我真的不想定義虛擬每個內置運算符的子類只需將email添加到template_fields ,例如:

from airflow.operators.python import PythonOperator

class MyPythonOperator(PythonOperator):
    template_fields = PythonOperator.template_fields + ("email",)  # this sucks!

因此,我決定堅持使用以下類似於猴子修補的方法,將自定義模板字段動態添加到當前模塊 scope 中可見/可訪問的所有運算符(function 必須在共享/公共模塊中的某處定義,然后在每個 DAG 的模塊級別上導入和調用):

from airflow.models import BaseOperator

def extend_operator_template_fields_with(
    extra_template_fields,
    base_operator_class=BaseOperator,
) -> None:
    for operator_class in base_operator_class.__subclasses__():
        # Use a dict (w/o values) instead of a set to keep the original order of template fields for the operator class.
        template_fields_dict = dict.fromkeys(operator_class.template_fields)
        template_fields_dict.update(dict.fromkeys(extra_template_fields))
        operator_class.template_fields = tuple(template_fields_dict.keys())

        extend_operator_template_fields_with(extra_template_fields, base_operator_class=operator_class)

PS 我仍然對更優雅的解決方案持開放態度,只是還沒有找到更好的解決方案(我正在使用 Airflow 2.2.5)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM