You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Airflow Variables中运行时插入DAG_NAME、当前时间等动态值

Airflow Variables动态值访问实现方法

完全可以实现,有两种常用方案:

方案1:使用Airflow原生Jinja模板渲染(推荐)

Airflow所有支持模板的参数都会自动解析Jinja占位符,无需额外代码处理:

  • 首先在Airflow Variables中存入带占位符的模板内容,示例变量key为dynamic_start_msg,值为:
    Started {{ dag.dag_id }} on {{ execution_date.strftime('%d-%b-%Y %H:%M:%S') }}
    如果需要的是任务实际运行时间而非调度时间,把时间占位符替换为:
    {{ macros.datetime.now().strftime('%d-%b-%Y %H:%M:%S') }}
  • 之后在DAG代码的模板参数中直接引用变量即可,会自动完成渲染,示例代码:
from airflow import DAG
from airflow.operators.bash import BashOperator
from airflow.utils.dates import days_ago

DAG_NAME = "0_dag_1"

with DAG(
    dag_id=DAG_NAME,
    schedule_interval=None,
    start_date=days_ago(1),
    catchup=False
) as dag:
    test_task = BashOperator(
        task_id="test_render",
        # 这里直接引用变量,运行时会自动替换占位符
        bash_command='echo "{{ var.value.dynamic_start_msg }}"'
    )

方案2:手动替换占位符(非模板场景用)

如果是在不支持Jinja模板的代码位置使用,可以手动获取变量后做字符串替换:

from airflow.models import Variable
from datetime import datetime

DAG_NAME = "0_dag_1"
# 获取变量原始值
raw_notification = Variable.get("dynamic_start_msg", default_var="Started {dag_name} on {current_time}")
# 手动替换占位符得到最终内容
rendered_notification = raw_notification.format(
    dag_name=DAG_NAME,
    current_time=datetime.now().strftime("%d-%b-%Y %H:%M:%S")
)

注意:建议优先使用方案1的execution_date获取时间,它是Airflow内置的调度时间,时区统一,不会因为Worker节点时区差异出现时间错误。如果必须使用运行时的当前时间,建议用Airflow内置的时区感知函数macros.datetime.utcnow()替换原生datetime,避免时区问题。

内容的提问来源于stack exchange,提问作者Taimur Adil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:36:03